context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
#define MCG_WINRT_SUPPORTED
using Mcg.System;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
// -----------------------------------------------------------------------------------------------------------
//
// WARNING: THIS SOURCE FILE IS FOR 32-BIT BUILDS ONLY!
//
// MCG GENERATED CODE
//
// This C# source file is generated by MCG and is added into the application at compile time to support interop features.
//
// It has three primary components:
//
// 1. Public type definitions with interop implementation used by this application including WinRT & COM data structures and P/Invokes.
//
// 2. The 'McgInterop' class containing marshaling code that acts as a bridge from managed code to native code.
//
// 3. The 'McgNative' class containing marshaling code and native type definitions that call into native code and are called by native code.
//
// -----------------------------------------------------------------------------------------------------------
//
// warning CS0067: The event 'event' is never used
#pragma warning disable 67
// warning CS0169: The field 'field' is never used
#pragma warning disable 169
// warning CS0649: Field 'field' is never assigned to, and will always have its default value 0
#pragma warning disable 414
// warning CS0414: The private field 'field' is assigned but its value is never used
#pragma warning disable 649
// warning CS1591: Missing XML comment for publicly visible type or member 'Type_or_Member'
#pragma warning disable 1591
// warning CS0108 'member1' hides inherited member 'member2'. Use the new keyword if hiding was intended.
#pragma warning disable 108
// warning CS0114 'member1' hides inherited member 'member2'. To make the current method override that implementation, add the override keyword. Otherwise add the new keyword.
#pragma warning disable 114
// warning CS0659 'type' overrides Object.Equals but does not override GetHashCode.
#pragma warning disable 659
// warning CS0465 Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?
#pragma warning disable 465
// warning CS0028 'function declaration' has the wrong signature to be an entry point
#pragma warning disable 28
// warning CS0162 Unreachable code Detected
#pragma warning disable 162
// warning CS0628 new protected member declared in sealed class
#pragma warning disable 628
namespace McgInterop
{
/// <summary>
/// P/Invoke class for module 'sqlite3'
/// </summary>
public unsafe static partial class sqlite3
{
// Signature, Open, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.AnsiStringMarshaller] string__unsigned char *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Open")]
public static global::SQLite.Net.Interop.Result__SQLite_Net Open(
string filename,
out global::System.IntPtr db)
{
// Setup
byte* unsafe_filename = default(byte*);
global::System.IntPtr unsafe_db;
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
try
{
// Marshalling
unsafe_filename = global::System.Runtime.InteropServices.McgMarshal.StringToAnsiString(filename, true, false);
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Open(
unsafe_filename,
&(unsafe_db)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
db = unsafe_db;
// Return
return unsafe___value;
}
finally
{
// Cleanup
global::System.Runtime.InteropServices.ExternalInterop.SafeCoTaskMemFree(unsafe_filename);
}
}
// Signature, Open__0, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.AnsiStringMarshaller] string__unsigned char *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Open")]
public static global::SQLite.Net.Interop.Result__SQLite_Net Open__0(
string filename,
out global::System.IntPtr db,
int flags,
global::System.IntPtr zvfs)
{
// Setup
byte* unsafe_filename = default(byte*);
global::System.IntPtr unsafe_db;
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
try
{
// Marshalling
unsafe_filename = global::System.Runtime.InteropServices.McgMarshal.StringToAnsiString(filename, true, false);
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Open__0(
unsafe_filename,
&(unsafe_db),
flags,
zvfs
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
db = unsafe_db;
// Return
return unsafe___value;
}
finally
{
// Cleanup
global::System.Runtime.InteropServices.ExternalInterop.SafeCoTaskMemFree(unsafe_filename);
}
}
// Signature, Open__1, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableArrayMarshaller] rg_byte__unsigned char *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Open")]
public static global::SQLite.Net.Interop.Result__SQLite_Net Open__1(
byte[] filename,
out global::System.IntPtr db,
int flags,
global::System.IntPtr zvfs)
{
// Setup
byte* unsafe_filename;
global::System.IntPtr unsafe_db;
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
// Marshalling
fixed (byte* pinned_filename = global::McgInterop.McgCoreHelpers.GetArrayForCompat(filename))
{
unsafe_filename = (byte*)pinned_filename;
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Open__1(
unsafe_filename,
&(unsafe_db),
flags,
zvfs
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
db = unsafe_db;
}
// Return
return unsafe___value;
}
// Signature, Open16, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.UnicodeStringMarshaller] string__wchar_t *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Open16")]
public static global::SQLite.Net.Interop.Result__SQLite_Net Open16(
string filename,
out global::System.IntPtr db)
{
// Setup
ushort* unsafe_filename = default(ushort*);
global::System.IntPtr unsafe_db;
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
// Marshalling
fixed (char* pinned_filename = filename)
{
unsafe_filename = (ushort*)pinned_filename;
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Open16(
unsafe_filename,
&(unsafe_db)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
db = unsafe_db;
}
// Return
return unsafe___value;
}
// Signature, Close, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Close")]
public static global::SQLite.Net.Interop.Result__SQLite_Net Close(global::System.IntPtr db)
{
// Setup
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Close(db);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, Config, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_ConfigOption__SQLite_Net__ConfigOption__SQLite_Net,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Config")]
public static global::SQLite.Net.Interop.Result__SQLite_Net Config(global::SQLite.Net.Interop.ConfigOption__SQLite_Net option)
{
// Setup
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Config(option);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, SetDirectory, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.UnicodeStringMarshaller] string__wchar_t *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "SetDirectory")]
public static int SetDirectory(
uint directoryType,
string directoryPath)
{
// Setup
ushort* unsafe_directoryPath = default(ushort*);
int unsafe___value;
// Marshalling
fixed (char* pinned_directoryPath = directoryPath)
{
unsafe_directoryPath = (ushort*)pinned_directoryPath;
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.SetDirectory(
directoryType,
unsafe_directoryPath
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
}
// Return
return unsafe___value;
}
// Signature, BusyTimeout, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BusyTimeout")]
public static global::SQLite.Net.Interop.Result__SQLite_Net BusyTimeout(
global::System.IntPtr db,
int milliseconds)
{
// Setup
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.BusyTimeout(
db,
milliseconds
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, Changes, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Changes")]
public static int Changes(global::System.IntPtr db)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Changes(db);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, Prepare2, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.AnsiStringMarshaller] string__unsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Prepare2")]
public static global::SQLite.Net.Interop.Result__SQLite_Net Prepare2(
global::System.IntPtr db,
string sql,
int numBytes,
out global::System.IntPtr stmt,
global::System.IntPtr pzTail)
{
// Setup
byte* unsafe_sql = default(byte*);
global::System.IntPtr unsafe_stmt;
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
try
{
// Marshalling
unsafe_sql = global::System.Runtime.InteropServices.McgMarshal.StringToAnsiString(sql, true, false);
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Prepare2(
db,
unsafe_sql,
numBytes,
&(unsafe_stmt),
pzTail
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
stmt = unsafe_stmt;
// Return
return unsafe___value;
}
finally
{
// Cleanup
global::System.Runtime.InteropServices.ExternalInterop.SafeCoTaskMemFree(unsafe_sql);
}
}
// Signature, Step, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Step")]
public static global::SQLite.Net.Interop.Result__SQLite_Net Step(global::System.IntPtr stmt)
{
// Setup
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Step(stmt);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, Reset, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Reset")]
public static global::SQLite.Net.Interop.Result__SQLite_Net Reset(global::System.IntPtr stmt)
{
// Setup
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Reset(stmt);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, Finalize, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Finalize")]
public static global::SQLite.Net.Interop.Result__SQLite_Net Finalize(global::System.IntPtr stmt)
{
// Setup
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Finalize(stmt);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, LastInsertRowid, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] long____int64, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "LastInsertRowid")]
public static long LastInsertRowid(global::System.IntPtr db)
{
// Setup
long unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.LastInsertRowid(db);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, Errmsg, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Errmsg")]
public static global::System.IntPtr Errmsg(global::System.IntPtr db)
{
// Setup
global::System.IntPtr unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Errmsg(db);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, BindParameterIndex, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.AnsiStringMarshaller] string__unsigned char *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BindParameterIndex")]
public static int BindParameterIndex(
global::System.IntPtr stmt,
string name)
{
// Setup
byte* unsafe_name = default(byte*);
int unsafe___value;
try
{
// Marshalling
unsafe_name = global::System.Runtime.InteropServices.McgMarshal.StringToAnsiString(name, true, false);
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.BindParameterIndex(
stmt,
unsafe_name
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
finally
{
// Cleanup
global::System.Runtime.InteropServices.ExternalInterop.SafeCoTaskMemFree(unsafe_name);
}
}
// Signature, BindNull, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BindNull")]
public static int BindNull(
global::System.IntPtr stmt,
int index)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.BindNull(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, BindInt, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BindInt")]
public static int BindInt(
global::System.IntPtr stmt,
int index,
int val)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.BindInt(
stmt,
index,
val
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, BindInt64, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] long____int64,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BindInt64")]
public static int BindInt64(
global::System.IntPtr stmt,
int index,
long val)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.BindInt64(
stmt,
index,
val
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, BindDouble, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] double__double,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BindDouble")]
public static int BindDouble(
global::System.IntPtr stmt,
int index,
double val)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.BindDouble(
stmt,
index,
val
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, BindText, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.UnicodeStringMarshaller] string__wchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BindText")]
public static int BindText(
global::System.IntPtr stmt,
int index,
string val,
int n,
global::System.IntPtr free)
{
// Setup
ushort* unsafe_val = default(ushort*);
int unsafe___value;
// Marshalling
fixed (char* pinned_val = val)
{
unsafe_val = (ushort*)pinned_val;
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.BindText(
stmt,
index,
unsafe_val,
n,
free
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
}
// Return
return unsafe___value;
}
// Signature, BindBlob, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableArrayMarshaller] rg_byte__unsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BindBlob")]
public static int BindBlob(
global::System.IntPtr stmt,
int index,
byte[] val,
int n,
global::System.IntPtr free)
{
// Setup
byte* unsafe_val;
int unsafe___value;
// Marshalling
fixed (byte* pinned_val = global::McgInterop.McgCoreHelpers.GetArrayForCompat(val))
{
unsafe_val = (byte*)pinned_val;
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.BindBlob(
stmt,
index,
unsafe_val,
n,
free
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
}
// Return
return unsafe___value;
}
// Signature, ColumnCount, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnCount")]
public static int ColumnCount(global::System.IntPtr stmt)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnCount(stmt);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ColumnName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnName")]
public static global::System.IntPtr ColumnName(
global::System.IntPtr stmt,
int index)
{
// Setup
global::System.IntPtr unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnName(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ColumnName16Internal, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnName16Internal")]
public static global::System.IntPtr ColumnName16Internal(
global::System.IntPtr stmt,
int index)
{
// Setup
global::System.IntPtr unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnName16Internal(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ColumnType, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_ColType__SQLite_Net__ColType__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnType")]
public static global::SQLite.Net.Interop.ColType__SQLite_Net ColumnType(
global::System.IntPtr stmt,
int index)
{
// Setup
global::SQLite.Net.Interop.ColType__SQLite_Net unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnType(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ColumnInt, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnInt")]
public static int ColumnInt(
global::System.IntPtr stmt,
int index)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnInt(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ColumnInt64, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] long____int64, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnInt64")]
public static long ColumnInt64(
global::System.IntPtr stmt,
int index)
{
// Setup
long unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnInt64(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ColumnDouble, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] double__double, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnDouble")]
public static double ColumnDouble(
global::System.IntPtr stmt,
int index)
{
// Setup
double unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnDouble(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ColumnText, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnText")]
public static global::System.IntPtr ColumnText(
global::System.IntPtr stmt,
int index)
{
// Setup
global::System.IntPtr unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnText(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ColumnText16, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnText16")]
public static global::System.IntPtr ColumnText16(
global::System.IntPtr stmt,
int index)
{
// Setup
global::System.IntPtr unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnText16(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ColumnBlob, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnBlob")]
public static global::System.IntPtr ColumnBlob(
global::System.IntPtr stmt,
int index)
{
// Setup
global::System.IntPtr unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnBlob(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ColumnBytes, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnBytes")]
public static int ColumnBytes(
global::System.IntPtr stmt,
int index)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnBytes(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, sqlite3_extended_errcode, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_ExtendedResult__SQLite_Net__ExtendedResult__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_extended_errcode")]
public static global::SQLite.Net.Interop.ExtendedResult__SQLite_Net sqlite3_extended_errcode(global::System.IntPtr db)
{
// Setup
global::SQLite.Net.Interop.ExtendedResult__SQLite_Net unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_extended_errcode(db);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, sqlite3_libversion_number, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_libversion_number")]
public static int sqlite3_libversion_number()
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_libversion_number();
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, sqlite3_sourceid, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_sourceid")]
public static global::System.IntPtr sqlite3_sourceid()
{
// Setup
global::System.IntPtr unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_sourceid();
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, sqlite3_backup_init, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.AnsiStringMarshaller] string__unsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.AnsiStringMarshaller] string__unsigned char *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_backup_init")]
public static global::System.IntPtr sqlite3_backup_init(
global::System.IntPtr destDB,
string destName,
global::System.IntPtr srcDB,
string srcName)
{
// Setup
byte* unsafe_destName = default(byte*);
byte* unsafe_srcName = default(byte*);
global::System.IntPtr unsafe___value;
try
{
// Marshalling
unsafe_destName = global::System.Runtime.InteropServices.McgMarshal.StringToAnsiString(destName, true, false);
unsafe_srcName = global::System.Runtime.InteropServices.McgMarshal.StringToAnsiString(srcName, true, false);
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_backup_init(
destDB,
unsafe_destName,
srcDB,
unsafe_srcName
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
finally
{
// Cleanup
global::System.Runtime.InteropServices.ExternalInterop.SafeCoTaskMemFree(unsafe_destName);
global::System.Runtime.InteropServices.ExternalInterop.SafeCoTaskMemFree(unsafe_srcName);
}
}
// Signature, sqlite3_backup_step, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_backup_step")]
public static global::SQLite.Net.Interop.Result__SQLite_Net sqlite3_backup_step(
global::System.IntPtr backup,
int pageCount)
{
// Setup
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_backup_step(
backup,
pageCount
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, sqlite3_backup_finish, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_backup_finish")]
public static global::SQLite.Net.Interop.Result__SQLite_Net sqlite3_backup_finish(global::System.IntPtr backup)
{
// Setup
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_backup_finish(backup);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, sqlite3_backup_remaining, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_backup_remaining")]
public static int sqlite3_backup_remaining(global::System.IntPtr backup)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_backup_remaining(backup);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, sqlite3_backup_pagecount, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_backup_pagecount")]
public static int sqlite3_backup_pagecount(global::System.IntPtr backup)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_backup_pagecount(backup);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, sqlite3_sleep, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_sleep")]
public static int sqlite3_sleep(int millis)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_sleep(millis);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module '[MRT]'
/// </summary>
public unsafe static partial class _MRT_
{
// Signature, RhWaitForPendingFinalizers, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "RhWaitForPendingFinalizers")]
public static void RhWaitForPendingFinalizers(int allowReentrantWait)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes.RhWaitForPendingFinalizers(allowReentrantWait);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
// Signature, RhCompatibleReentrantWaitAny, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr___ptr__w64 int *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "RhCompatibleReentrantWaitAny")]
public static int RhCompatibleReentrantWaitAny(
int alertable,
int timeout,
int count,
global::System.IntPtr* handles)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop._MRT__PInvokes.RhCompatibleReentrantWaitAny(
alertable,
timeout,
count,
((global::System.IntPtr*)handles)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, _ecvt_s, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] double__double, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int___ptrint *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int___ptrint *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "_ecvt_s")]
public static void _ecvt_s(
byte* buffer,
int sizeInBytes,
double value,
int count,
int* dec,
int* sign)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes._ecvt_s(
((byte*)buffer),
sizeInBytes,
value,
count,
((int*)dec),
((int*)sign)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
// Signature, memmove, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "memmove")]
public static void memmove(
byte* dmem,
byte* smem,
uint size)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes.memmove(
((byte*)dmem),
((byte*)smem),
size
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
}
/// <summary>
/// P/Invoke class for module '*'
/// </summary>
public unsafe static partial class _
{
// Signature, CallingConventionConverter_GetStubs, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.TypeLoader, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.Runtime.TypeLoader.CallConverterThunk", "CallingConventionConverter_GetStubs")]
public static void CallingConventionConverter_GetStubs(
out global::System.IntPtr returnVoidStub,
out global::System.IntPtr returnIntegerStub,
out global::System.IntPtr commonStub,
out global::System.IntPtr returnFloatingPointReturn4Thunk,
out global::System.IntPtr returnFloatingPointReturn8Thunk)
{
// Setup
global::System.IntPtr unsafe_returnVoidStub;
global::System.IntPtr unsafe_returnIntegerStub;
global::System.IntPtr unsafe_commonStub;
global::System.IntPtr unsafe_returnFloatingPointReturn4Thunk;
global::System.IntPtr unsafe_returnFloatingPointReturn8Thunk;
// Marshalling
// Call to native method
global::McgInterop.__PInvokes.CallingConventionConverter_GetStubs(
&(unsafe_returnVoidStub),
&(unsafe_returnIntegerStub),
&(unsafe_commonStub),
&(unsafe_returnFloatingPointReturn4Thunk),
&(unsafe_returnFloatingPointReturn8Thunk)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
returnFloatingPointReturn8Thunk = unsafe_returnFloatingPointReturn8Thunk;
returnFloatingPointReturn4Thunk = unsafe_returnFloatingPointReturn4Thunk;
commonStub = unsafe_commonStub;
returnIntegerStub = unsafe_returnIntegerStub;
returnVoidStub = unsafe_returnVoidStub;
// Return
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-errorhandling-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_errorhandling_l1_1_0_dll
{
// Signature, GetLastError, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Runtime.Extensions, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetLastError")]
public static int GetLastError()
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_errorhandling_l1_1_0_dll_PInvokes.GetLastError();
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-winrt-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_winrt_l1_1_0_dll
{
// Signature, RoInitialize, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "RoInitialize")]
public static int RoInitialize(uint initType)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_winrt_l1_1_0_dll_PInvokes.RoInitialize(initType);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-localization-l1-2-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_localization_l1_2_0_dll
{
// Signature, IsValidLocaleName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "IsValidLocaleName")]
public static int IsValidLocaleName(char* lpLocaleName)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.IsValidLocaleName(((ushort*)lpLocaleName));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ResolveLocaleName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "ResolveLocaleName")]
public static int ResolveLocaleName(
char* lpNameToResolve,
char* lpLocaleName,
int cchLocaleName)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.ResolveLocaleName(
((ushort*)lpNameToResolve),
((ushort*)lpLocaleName),
cchLocaleName
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, GetCPInfoExW, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages___ptr__Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Text.Encoding.CodePages, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetCPInfoExW")]
public static int GetCPInfoExW(
uint CodePage,
uint dwFlags,
global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages* lpCPInfoEx)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.GetCPInfoExW(
CodePage,
dwFlags,
((global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages*)lpCPInfoEx)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-com-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_com_l1_1_0_dll
{
// Signature, CoCreateInstance, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.StackTraceGenerator, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.StackTraceGenerator.StackTraceGenerator", "CoCreateInstance")]
public static int CoCreateInstance(
byte* rclsid,
global::System.IntPtr pUnkOuter,
int dwClsContext,
byte* riid,
out global::System.IntPtr ppv)
{
// Setup
global::System.IntPtr unsafe_ppv;
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_com_l1_1_0_dll_PInvokes.CoCreateInstance(
((byte*)rclsid),
pUnkOuter,
dwClsContext,
((byte*)riid),
&(unsafe_ppv)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
ppv = unsafe_ppv;
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'OleAut32'
/// </summary>
public unsafe static partial class OleAut32
{
// Signature, SysFreeString, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.StackTraceGenerator, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.LightweightInterop.MarshalExtensions", "SysFreeString")]
public static void SysFreeString(global::System.IntPtr bstr)
{
// Marshalling
// Call to native method
global::McgInterop.OleAut32_PInvokes.SysFreeString(bstr);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-winrt-robuffer-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_winrt_robuffer_l1_1_0_dll
{
// Signature, RoGetBufferMarshaler, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.ComInterfaceMarshaller] System_Runtime_InteropServices_IMarshal__System_Runtime_WindowsRuntime__System_Runtime_InteropServices__IMarshal__System_Runtime_WindowsRuntime *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Runtime.WindowsRuntime, Version=4.0.11.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop+mincore", "RoGetBufferMarshaler")]
public static int RoGetBufferMarshaler(out global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime bufferMarshalerPtr)
{
// Setup
global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl** unsafe_bufferMarshalerPtr = default(global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl**);
int unsafe___value;
try
{
// Marshalling
unsafe_bufferMarshalerPtr = null;
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_winrt_robuffer_l1_1_0_dll_PInvokes.RoGetBufferMarshaler(&(unsafe_bufferMarshalerPtr));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
bufferMarshalerPtr = (global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime)global::System.Runtime.InteropServices.McgModuleManager.ComInterfaceToObject(
((global::System.IntPtr)unsafe_bufferMarshalerPtr),
global::System.Runtime.InteropServices.TypeOfHelper.RuntimeTypeHandleOf("System.Runtime.InteropServices.IMarshal,System.Runtime.WindowsRuntime, Version=4.0.11.0, Culture=neutral, Public" +
"KeyToken=b77a5c561934e089")
);
// Return
return unsafe___value;
}
finally
{
// Cleanup
global::System.Runtime.InteropServices.McgMarshal.ComSafeRelease(new global::System.IntPtr(((void*)unsafe_bufferMarshalerPtr)));
}
}
}
public unsafe static partial class sqlite3_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_open", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net Open(
byte* filename,
global::System.IntPtr* db);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_open_v2", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net Open__0(
byte* filename,
global::System.IntPtr* db,
int flags,
global::System.IntPtr zvfs);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_open_v2", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net Open__1(
byte* filename,
global::System.IntPtr* db,
int flags,
global::System.IntPtr zvfs);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_open16", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net Open16(
ushort* filename,
global::System.IntPtr* db);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_close", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net Close(global::System.IntPtr db);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_config", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net Config(global::SQLite.Net.Interop.ConfigOption__SQLite_Net option);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_win32_set_directory", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int SetDirectory(
uint directoryType,
ushort* directoryPath);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_busy_timeout", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net BusyTimeout(
global::System.IntPtr db,
int milliseconds);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_changes", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int Changes(global::System.IntPtr db);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_prepare_v2", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net Prepare2(
global::System.IntPtr db,
byte* sql,
int numBytes,
global::System.IntPtr* stmt,
global::System.IntPtr pzTail);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_step", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net Step(global::System.IntPtr stmt);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_reset", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net Reset(global::System.IntPtr stmt);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_finalize", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net Finalize(global::System.IntPtr stmt);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_last_insert_rowid", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static long LastInsertRowid(global::System.IntPtr db);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_errmsg16", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::System.IntPtr Errmsg(global::System.IntPtr db);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_bind_parameter_index", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int BindParameterIndex(
global::System.IntPtr stmt,
byte* name);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_bind_null", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int BindNull(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_bind_int", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int BindInt(
global::System.IntPtr stmt,
int index,
int val);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_bind_int64", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int BindInt64(
global::System.IntPtr stmt,
int index,
long val);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_bind_double", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int BindDouble(
global::System.IntPtr stmt,
int index,
double val);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_bind_text16", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int BindText(
global::System.IntPtr stmt,
int index,
ushort* val,
int n,
global::System.IntPtr free);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_bind_blob", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int BindBlob(
global::System.IntPtr stmt,
int index,
byte* val,
int n,
global::System.IntPtr free);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_count", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int ColumnCount(global::System.IntPtr stmt);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_name", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::System.IntPtr ColumnName(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_name16", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::System.IntPtr ColumnName16Internal(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_type", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.ColType__SQLite_Net ColumnType(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_int", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int ColumnInt(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_int64", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static long ColumnInt64(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_double", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static double ColumnDouble(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_text", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::System.IntPtr ColumnText(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_text16", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::System.IntPtr ColumnText16(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_blob", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::System.IntPtr ColumnBlob(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_bytes", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int ColumnBytes(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.ExtendedResult__SQLite_Net sqlite3_extended_errcode(global::System.IntPtr db);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int sqlite3_libversion_number();
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::System.IntPtr sqlite3_sourceid();
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::System.IntPtr sqlite3_backup_init(
global::System.IntPtr destDB,
byte* destName,
global::System.IntPtr srcDB,
byte* srcName);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net sqlite3_backup_step(
global::System.IntPtr backup,
int pageCount);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net sqlite3_backup_finish(global::System.IntPtr backup);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int sqlite3_backup_remaining(global::System.IntPtr backup);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int sqlite3_backup_pagecount(global::System.IntPtr backup);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int sqlite3_sleep(int millis);
}
public unsafe static partial class _MRT__PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void RhWaitForPendingFinalizers(int allowReentrantWait);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int RhCompatibleReentrantWaitAny(
int alertable,
int timeout,
int count,
global::System.IntPtr* handles);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void _ecvt_s(
byte* buffer,
int sizeInBytes,
double value,
int count,
int* dec,
int* sign);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void memmove(
byte* dmem,
byte* smem,
uint size);
}
public unsafe static partial class __PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("*", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void CallingConventionConverter_GetStubs(
global::System.IntPtr* returnVoidStub,
global::System.IntPtr* returnIntegerStub,
global::System.IntPtr* commonStub,
global::System.IntPtr* returnFloatingPointReturn4Thunk,
global::System.IntPtr* returnFloatingPointReturn8Thunk);
}
public unsafe static partial class api_ms_win_core_errorhandling_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-errorhandling-l1-1-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetLastError();
}
public unsafe static partial class api_ms_win_core_winrt_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-winrt-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int RoInitialize(uint initType);
}
public unsafe static partial class api_ms_win_core_localization_l1_2_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int IsValidLocaleName(ushort* lpLocaleName);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int ResolveLocaleName(
ushort* lpNameToResolve,
ushort* lpLocaleName,
int cchLocaleName);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetCPInfoExW(
uint CodePage,
uint dwFlags,
global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages* lpCPInfoEx);
}
public unsafe static partial class api_ms_win_core_com_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-com-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int CoCreateInstance(
byte* rclsid,
global::System.IntPtr pUnkOuter,
int dwClsContext,
byte* riid,
global::System.IntPtr* ppv);
}
public unsafe static partial class OleAut32_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("oleaut32.dll", EntryPoint="#6", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void SysFreeString(global::System.IntPtr bstr);
}
public unsafe static partial class api_ms_win_core_winrt_robuffer_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-winrt-robuffer-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.StdCall)]
public extern static int RoGetBufferMarshaler(global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl*** bufferMarshalerPtr);
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using SIL.WritingSystems.Migration;
namespace SIL.WritingSystems
{
/// <summary>
/// A folder-based, LDML writing system repository.
/// </summary>
public class LdmlInFolderWritingSystemRepository : LdmlInFolderWritingSystemRepository<WritingSystemDefinition>
{
public static LdmlInFolderWritingSystemRepository Initialize(string basePath)
{
return Initialize(basePath, Enumerable.Empty<ICustomDataMapper<WritingSystemDefinition>>());
}
/// <summary>
/// Returns an instance of an ldml in folder writing system reposistory.
/// </summary>
/// <param name="basePath">base location of the global writing system repository</param>
/// <param name="customDataMappers">The custom data mappers.</param>
/// <param name="globalRepository">The global repository.</param>
/// <param name="migrationHandler">Callback if during the initialization any writing system id's are changed</param>
/// <param name="loadProblemHandler">Callback if during the initialization any writing systems cannot be loaded</param>
/// <returns></returns>
public static LdmlInFolderWritingSystemRepository Initialize(
string basePath,
IEnumerable<ICustomDataMapper<WritingSystemDefinition>> customDataMappers,
GlobalWritingSystemRepository globalRepository = null,
Action<int, IEnumerable<LdmlMigrationInfo>> migrationHandler = null,
Action<IEnumerable<WritingSystemRepositoryProblem>> loadProblemHandler = null
)
{
var migrator = new LdmlInFolderWritingSystemRepositoryMigrator(basePath, migrationHandler);
migrator.Migrate();
var instance = new LdmlInFolderWritingSystemRepository(basePath, customDataMappers, globalRepository);
migrator.ResetRemovedProperties(instance);
// Call the loadProblemHandler with both migration problems and load problems
var loadProblems = new List<WritingSystemRepositoryProblem>();
loadProblems.AddRange(migrator.MigrationProblems);
loadProblems.AddRange(instance.LoadProblems);
if (loadProblems.Count > 0 && loadProblemHandler != null)
{
loadProblemHandler(loadProblems);
}
return instance;
}
protected internal LdmlInFolderWritingSystemRepository(string basePath, GlobalWritingSystemRepository<WritingSystemDefinition> globalRepository = null)
: base(basePath, globalRepository)
{
}
protected internal LdmlInFolderWritingSystemRepository(string basePath, IEnumerable<ICustomDataMapper<WritingSystemDefinition>> customDataMappers,
GlobalWritingSystemRepository globalRepository = null)
: base(basePath, customDataMappers, globalRepository)
{
}
protected override IWritingSystemFactory<WritingSystemDefinition> CreateWritingSystemFactory()
{
return new LdmlInFolderWritingSystemFactory(this);
}
}
/// <summary>
/// A folder-based, LDML writing system repository.
/// </summary>
public abstract class LdmlInFolderWritingSystemRepository<T> : LocalWritingSystemRepositoryBase<T> where T : WritingSystemDefinition
{
private const string Extension = ".ldml";
private string _path;
private IEnumerable<T> _systemWritingSystemProvider;
private readonly WritingSystemChangeLog _changeLog;
private readonly IList<WritingSystemRepositoryProblem> _loadProblems = new List<WritingSystemRepositoryProblem>();
private readonly ICustomDataMapper<T>[] _customDataMappers;
private readonly GlobalWritingSystemRepository<T> _globalRepository;
protected internal LdmlInFolderWritingSystemRepository(string basePath, GlobalWritingSystemRepository<T> globalRepository = null) :
this(basePath, Enumerable.Empty<ICustomDataMapper<T>>(), globalRepository)
{
}
protected internal LdmlInFolderWritingSystemRepository(string basePath, IEnumerable<ICustomDataMapper<T>> customDataMappers,
GlobalWritingSystemRepository<T> globalRepository = null)
: base(globalRepository)
{
_customDataMappers = customDataMappers.ToArray();
_globalRepository = globalRepository;
PathToWritingSystems = basePath;
_changeLog = new WritingSystemChangeLog(new WritingSystemChangeLogDataMapper(Path.Combine(PathToWritingSystems, "idchangelog.xml")));
ReadGlobalWritingSystemsToIgnore();
}
/// <summary>
/// Gets the load problems.
/// </summary>
public IList<WritingSystemRepositoryProblem> LoadProblems
{
get { return _loadProblems; }
}
public new GlobalWritingSystemRepository<T> GlobalWritingSystemRepository
{
get { return _globalRepository; }
}
/// <summary>
/// Gets or sets the path to the writing systems folder.
/// </summary>
public string PathToWritingSystems
{
get { return _path; }
set
{
_path = value;
if (!Directory.Exists(_path))
{
string parent = Directory.GetParent(_path).FullName;
if (!Directory.Exists(parent))
{
throw new ApplicationException(
"The writing system repository cannot be created because its parent folder, " + parent +
", does not exist.");
}
Directory.CreateDirectory(_path);
}
LoadAllDefinitions();
}
}
public IEnumerable<ICustomDataMapper<T>> CustomDataMappers
{
get { return _customDataMappers; }
}
///<summary>
/// Returns the full path to the underlying store for this writing system.
///</summary>
public string GetFilePathFromLanguageTag(string langTag)
{
return Path.Combine(PathToWritingSystems, GetFileNameFromLanguageTag(langTag));
}
/// <summary>
/// Gets the file name from the specified identifier.
/// </summary>
protected static string GetFileNameFromLanguageTag(string langTag)
{
return langTag + Extension;
}
/// <summary>
/// Loads all writing system definitions.
/// </summary>
protected void LoadAllDefinitions()
{
_loadProblems.Clear();
ChangedIds.Clear();
Clear();
foreach (string filePath in Directory.GetFiles(_path, "*.ldml"))
LoadDefinition(filePath);
LoadChangedIdsFromExistingWritingSystems();
}
protected virtual void LoadDefinition(string filePath)
{
T wsFromFile;
try
{
wsFromFile = WritingSystemFactory.Create();
var ldmlDataMapper = new LdmlDataMapper(WritingSystemFactory);
if (File.Exists(filePath))
{
ldmlDataMapper.Read(filePath, wsFromFile);
foreach (ICustomDataMapper<T> customDataMapper in _customDataMappers)
customDataMapper.Read(wsFromFile);
wsFromFile.Id = Path.GetFileNameWithoutExtension(filePath);
}
}
catch (Exception e)
{
// Add the exception to our list of problems and continue loading
var problem = new WritingSystemRepositoryProblem
{
Consequence = WritingSystemRepositoryProblem.ConsequenceType.WSWillNotBeAvailable,
Exception = e,
FilePath = filePath
};
_loadProblems.Add(problem);
return;
}
if (!StringComparer.InvariantCultureIgnoreCase.Equals(wsFromFile.Id, wsFromFile.LanguageTag))
{
// Add the exception to our list of problems and continue loading
var problem = new WritingSystemRepositoryProblem
{
Consequence = WritingSystemRepositoryProblem.ConsequenceType.WSWillNotBeAvailable,
Exception = new ApplicationException(
String.Format(
"The writing system file {0} seems to be named inconsistently. It contains the IETF language tag: '{1}'. The name should have been made consistent with its content upon migration of the writing systems.",
filePath, wsFromFile.LanguageTag)),
FilePath = filePath
};
_loadProblems.Add(problem);
}
try
{
Set(wsFromFile);
}
catch (Exception e)
{
// Add the exception to our list of problems and continue loading
var problem = new WritingSystemRepositoryProblem
{
Consequence = WritingSystemRepositoryProblem.ConsequenceType.WSWillNotBeAvailable,
Exception = e,
FilePath = filePath
};
_loadProblems.Add(problem);
}
}
private bool HaveMatchingDefinitionInTrash(string identifier)
{
string path = PathToWritingSystemTrash();
path = Path.Combine(path, GetFileNameFromLanguageTag(identifier));
return File.Exists(path);
}
private void AddActiveOSLanguages()
{
foreach (T ws in _systemWritingSystemProvider)
{
if (null == FindAlreadyLoadedWritingSystem(ws.LanguageTag))
{
if (!HaveMatchingDefinitionInTrash(ws.LanguageTag))
{
Set(ws);
}
}
}
}
/// <summary>
/// Provides writing systems from a repository that comes, for example, with the OS
/// </summary>
public IEnumerable<T> SystemWritingSystemProvider
{
get{ return _systemWritingSystemProvider;}
set
{
if (_systemWritingSystemProvider != value)
{
_systemWritingSystemProvider = value;
AddActiveOSLanguages();
}
}
}
private T FindAlreadyLoadedWritingSystem(string wsID)
{
return AllWritingSystems.FirstOrDefault(ws => ws.LanguageTag == wsID);
}
/// <summary>
/// Saves a writing system definition.
/// </summary>
protected internal virtual void SaveDefinition(T ws)
{
Set(ws);
string writingSystemFilePath = GetFilePathFromLanguageTag(ws.LanguageTag);
if (!File.Exists(writingSystemFilePath) && !string.IsNullOrEmpty(ws.Template) && File.Exists(ws.Template))
{
// this is a new writing system that was generated from a template, so copy the template over before saving
File.Copy(ws.Template, writingSystemFilePath);
ws.Template = null;
ws.AcceptChanges();
}
if (!ws.IsChanged && File.Exists(writingSystemFilePath))
return; // no need to save (better to preserve the modified date)
ws.DateModified = DateTime.UtcNow;
MemoryStream oldData = null;
if (File.Exists(writingSystemFilePath))
{
// load old data to preserve stuff in LDML that we don't use, but don't throw up an error if it fails
try
{
oldData = new MemoryStream(File.ReadAllBytes(writingSystemFilePath), false);
}
catch {}
// What to do? Assume that the UI has already checked for existing, asked, and allowed the overwrite.
File.Delete(writingSystemFilePath); //!!! Should this be move to trash?
}
var ldmlDataMapper = new LdmlDataMapper(WritingSystemFactory);
ldmlDataMapper.Write(writingSystemFilePath, ws, oldData);
foreach (ICustomDataMapper<T> customDataMapper in _customDataMappers)
customDataMapper.Write(ws);
ws.AcceptChanges();
if (ChangedIds.Any(p => p.Value == ws.Id))
{
// log this id change to the writing system change log
KeyValuePair<string, string> pair = ChangedIds.First(p => p.Value == ws.Id);
_changeLog.LogChange(pair.Key, pair.Value);
}
else
{
// log this addition
_changeLog.LogAdd(ws.Id);
}
}
public override void Conflate(string wsToConflate, string wsToConflateWith)
{
//conflation involves deleting the old writing system. That deletion should not appear int he log. which is what the "_conflating" is used for
base.Conflate(wsToConflate, wsToConflateWith);
_changeLog.LogConflate(wsToConflate, wsToConflateWith);
}
public override void Remove(string id)
{
base.Remove(id);
_changeLog.LogDelete(id);
}
protected override void RemoveDefinition(T ws)
{
int wsIgnoreCount = WritingSystemsToIgnore.Count;
//we really need to get it in the trash, else, if was auto-provided,
//it'll keep coming back!
if (!File.Exists(GetFilePathFromLanguageTag(ws.LanguageTag)))
SaveDefinition(ws);
if (File.Exists(GetFilePathFromLanguageTag(ws.LanguageTag)))
{
Directory.CreateDirectory(PathToWritingSystemTrash());
string destination = Path.Combine(PathToWritingSystemTrash(), GetFileNameFromLanguageTag(ws.LanguageTag));
//clear out any old on already in the trash
if (File.Exists(destination))
File.Delete(destination);
File.Move(GetFilePathFromLanguageTag(ws.LanguageTag), destination);
}
base.RemoveDefinition(ws);
foreach (ICustomDataMapper<T> customDataMapper in _customDataMappers)
customDataMapper.Remove(ws.LanguageTag);
if (wsIgnoreCount != WritingSystemsToIgnore.Count)
WriteGlobalWritingSystemsToIgnore();
}
private string PathToWritingSystemTrash()
{
return Path.Combine(_path, "trash");
}
/// <summary>
/// Return true if it will be possible (absent someone changing permissions while we aren't looking)
/// to save changes to the specified writing system.
/// </summary>
public override bool CanSave(T ws)
{
string filePath = GetFilePathFromLanguageTag(ws.LanguageTag);
if (File.Exists(filePath))
{
try
{
using (FileStream stream = File.Open(filePath, FileMode.Open))
stream.Close();
// don't really want to change anything
}
catch (UnauthorizedAccessException)
{
return false;
}
}
else if (Directory.Exists(PathToWritingSystems))
{
try
{
// See whether we're allowed to create the file (but if so, get rid of it).
// Pathologically we might have create but not delete permission...if so,
// we'll create an empty file and report we can't save. I don't see how to
// do better.
using (FileStream stream = File.Create(filePath))
stream.Close();
File.Delete(filePath);
}
catch (UnauthorizedAccessException)
{
return false;
}
}
else
{
try
{
Directory.CreateDirectory(PathToWritingSystems);
// Don't try to clean it up again. This is a vanishingly rare case,
// I don't think it's even possible to create a writing system store without
// the directory existing.
}
catch (UnauthorizedAccessException)
{
return false;
}
}
return true;
}
public override void Save()
{
int wsIgnoreCount = WritingSystemsToIgnore.Count;
//delete anything we're going to delete first, to prevent losing
//a WS we want by having it deleted by an old WS we don't want
//(but which has the same identifier)
foreach (string id in AllWritingSystems.Where(ws => ws.MarkedForDeletion).Select(ws => ws.Id).ToArray())
Remove(id);
// make a copy and then go through that list - SaveDefinition calls Set which
// may delete and then insert the same writing system - which would change WritingSystemDefinitions
// and not be allowed in a foreach loop
foreach (T ws in AllWritingSystems.Where(CanSet).ToArray())
{
SaveDefinition(ws);
OnChangeNotifySharedStore(ws);
}
LoadChangedIdsFromExistingWritingSystems();
if (wsIgnoreCount != WritingSystemsToIgnore.Count)
WriteGlobalWritingSystemsToIgnore();
base.Save();
}
public override void Set(T ws)
{
if (ws == null)
{
throw new ArgumentNullException("ws");
}
string oldStoreId = ws.Id;
base.Set(ws);
//Renaming the file here is a bit ugly as the content has not yet been updated. Thus there
//may be a mismatch between the filename and the contained rfc5646 tag. Doing it here however
//helps us avoid having to deal with situations where a writing system id is changed to be
//identical with the old id of another writing sytsem. This could otherwise lead to dataloss.
//The inconsistency is resolved on Save()
if (oldStoreId != ws.Id && File.Exists(GetFilePathFromLanguageTag(oldStoreId)))
File.Move(GetFilePathFromLanguageTag(oldStoreId), GetFilePathFromLanguageTag(ws.Id));
}
public override bool WritingSystemIdHasChanged(string id)
{
return _changeLog.HasChangeFor(id);
}
public override string WritingSystemIdHasChangedTo(string id)
{
return AllWritingSystems.Any(ws => ws.LanguageTag.Equals(id)) ? id : _changeLog.GetChangeFor(id);
}
protected override void LastChecked(string identifier, DateTime dateModified)
{
base.LastChecked(identifier, dateModified);
WriteGlobalWritingSystemsToIgnore();
}
private void WriteGlobalWritingSystemsToIgnore()
{
if (_globalRepository == null)
return;
string path = Path.Combine(PathToWritingSystems, "WritingSystemsToIgnore.xml");
if (WritingSystemsToIgnore.Count == 0)
{
if (File.Exists(path))
File.Delete(path);
}
else
{
var doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
new XElement("WritingSystems",
WritingSystemsToIgnore.Select(ignoredWs => new XElement("WritingSystem", new XAttribute("id", ignoredWs.Key), new XAttribute("dateModified", ignoredWs.Value.ToString("s"))))));
doc.Save(path);
}
}
private void ReadGlobalWritingSystemsToIgnore()
{
string path = Path.Combine(PathToWritingSystems, "WritingSystemsToIgnore.xml");
if (_globalRepository == null || !File.Exists(path))
return;
XElement wssElem = XElement.Load(path);
foreach (XElement wsElem in wssElem.Elements("WritingSystem"))
{
DateTime dateModified = DateTime.ParseExact((string) wsElem.Attribute("dateModified"), "s", null, DateTimeStyles.AdjustToUniversal);
WritingSystemsToIgnore[(string)wsElem.Attribute("id")] = dateModified;
}
}
public override IEnumerable<T> CheckForNewerGlobalWritingSystems()
{
foreach (T ws in base.CheckForNewerGlobalWritingSystems())
{
// load local settings using custom data mappers, so these settings won't be lost if these writing systems are used to
// replace the existing local writing systems
foreach (ICustomDataMapper<T> customDataMapper in _customDataMappers)
customDataMapper.Read(ws);
yield return ws;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Text;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Roslyn.Utilities;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed partial class CSharpFormatter : Formatter
{
private void AppendEnumTypeAndName(StringBuilder builder, Type typeToDisplayOpt, string name)
{
if (typeToDisplayOpt != null)
{
// We're showing the type of a value, so "dynamic" does not apply.
bool unused;
int index = 0;
AppendQualifiedTypeName(builder, typeToDisplayOpt, default(DynamicFlagsCustomTypeInfo), ref index, escapeKeywordIdentifiers: true, sawInvalidIdentifier: out unused);
builder.Append('.');
AppendIdentifierEscapingPotentialKeywords(builder, name, sawInvalidIdentifier: out unused);
}
else
{
builder.Append(name);
}
}
internal override string GetArrayDisplayString(Type lmrType, ReadOnlyCollection<int> sizes, ReadOnlyCollection<int> lowerBounds, ObjectDisplayOptions options)
{
Debug.Assert(lmrType.IsArray);
Type originalLmrType = lmrType;
// Strip off all array types. We'll process them at the end.
while (lmrType.IsArray)
{
lmrType = lmrType.GetElementType();
}
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append('{');
// We're showing the type of a value, so "dynamic" does not apply.
bool unused;
builder.Append(GetTypeName(new TypeAndCustomInfo(lmrType), escapeKeywordIdentifiers: false, sawInvalidIdentifier: out unused)); // NOTE: call our impl directly, since we're coupled anyway.
var numSizes = sizes.Count;
builder.Append('[');
for (int i = 0; i < numSizes; i++)
{
if (i > 0)
{
builder.Append(", ");
}
var lowerBound = lowerBounds[i];
var size = sizes[i];
if (lowerBound == 0)
{
builder.Append(FormatLiteral(size, options));
}
else
{
builder.Append(FormatLiteral(lowerBound, options));
builder.Append("..");
builder.Append(FormatLiteral(size + lowerBound - 1, options));
}
}
builder.Append(']');
lmrType = originalLmrType.GetElementType(); // Strip off one layer (already handled).
while (lmrType.IsArray)
{
builder.Append('[');
builder.Append(',', lmrType.GetArrayRank() - 1);
builder.Append(']');
lmrType = lmrType.GetElementType();
}
builder.Append('}');
return pooled.ToStringAndFree();
}
internal override string GetArrayIndexExpression(int[] indices)
{
Debug.Assert(indices != null);
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append('[');
bool any = false;
foreach (var index in indices)
{
if (any)
{
builder.Append(", ");
}
builder.Append(index);
any = true;
}
builder.Append(']');
return pooled.ToStringAndFree();
}
internal override string GetCastExpression(string argument, string type, bool parenthesizeArgument = false, bool parenthesizeEntireExpression = false)
{
Debug.Assert(!string.IsNullOrEmpty(argument));
Debug.Assert(!string.IsNullOrEmpty(type));
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
if (parenthesizeEntireExpression)
{
builder.Append('(');
}
var castExpressionFormat = parenthesizeArgument ? "({0})({1})" : "({0}){1}";
builder.AppendFormat(castExpressionFormat, type, argument);
if (parenthesizeEntireExpression)
{
builder.Append(')');
}
return pooled.ToStringAndFree();
}
internal override string GetNamesForFlagsEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt)
{
var usedFields = ArrayBuilder<EnumField>.GetInstance();
FillUsedEnumFields(usedFields, fields, underlyingValue);
if (usedFields.Count == 0)
{
return null;
}
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
for (int i = usedFields.Count - 1; i >= 0; i--) // Backwards to list smallest first.
{
AppendEnumTypeAndName(builder, typeToDisplayOpt, usedFields[i].Name);
if (i > 0)
{
builder.Append(" | ");
}
}
usedFields.Free();
return pooled.ToStringAndFree();
}
internal override string GetNameForEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt)
{
foreach (var field in fields)
{
// First match wins (deterministic since sorted).
if (underlyingValue == field.Value)
{
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
AppendEnumTypeAndName(builder, typeToDisplayOpt, field.Name);
return pooled.ToStringAndFree();
}
}
return null;
}
internal override string GetObjectCreationExpression(string type, string arguments)
{
Debug.Assert(!string.IsNullOrEmpty(type));
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append("new ");
builder.Append(type);
builder.Append('(');
builder.Append(arguments);
builder.Append(')');
return pooled.ToStringAndFree();
}
internal override string FormatLiteral(char c, ObjectDisplayOptions options)
{
return ObjectDisplay.FormatLiteral(c, options);
}
internal override string FormatLiteral(int value, ObjectDisplayOptions options)
{
return ObjectDisplay.FormatLiteral(value, options & ~(ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters));
}
internal override string FormatPrimitiveObject(object value, ObjectDisplayOptions options)
{
return ObjectDisplay.FormatPrimitive(value, options);
}
internal override string FormatString(string str, ObjectDisplayOptions options)
{
return ObjectDisplay.FormatLiteral(str, options);
}
}
}
| |
//-----------------------------------------------------------------------------
// EditCurveKeyCollection.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
namespace Xna.Tools
{
/// <summary>
/// This class provides same functionality of CurveEditCollection but
/// this contains EditCurveKey instead of CurveKey.
/// You have to use any curve key operations via this class because this class
/// also manipulates original curve keys.
/// </summary>
public class EditCurveKeyCollection : ICollection<EditCurveKey>
{
#region Constructors.
/// <summary>
/// Create new instance of EditCurveKeyCollection from Curve instance.
/// </summary>
/// <param name="curve"></param>
internal EditCurveKeyCollection(EditCurve owner)
{
// Generate EditCurveKey list from Curve class.
this.owner = owner;
foreach (CurveKey key in owner.OriginalCurve.Keys)
{
// Add EditCurveKey to keys.
int index = owner.OriginalCurve.Keys.IndexOf(key);
EditCurveKey newKey =
new EditCurveKey(EditCurveKey.GenerateUniqueId(), key);
keys.Insert(index, newKey);
idToKeyMap.Add(newKey.Id, newKey);
}
}
#endregion
#region IList<EditCurveKey> like Members
/// <summary>
/// Determines the index of a specfied CurveKey in the EditCurveKeyCollection.
/// </summary>
/// <param name="item">CurveKey to locate in the EditCurveKeyCollection</param>
/// <returns>The index of value if found in the EditCurveKeyCollection;
/// otherwise -1.</returns>
public int IndexOf(EditCurveKey item)
{
for (int i = 0; i < keys.Count; ++i)
{
if (keys[i].Id == item.Id) return i;
}
return -1;
}
/// <summary>
/// Remove a CurveKey from at the specfied index.
/// </summary>
/// <param name="index">The Zero-based index of the item to remove.</param>
public void RemoveAt(int index)
{
EditCurveKey key = keys[index];
idToKeyMap.Remove(key.Id);
keys.RemoveAt(index);
owner.OriginalCurve.Keys.RemoveAt(index);
}
/// <summary>
/// Gets or sets the element at the specfied index.
/// </summary>
/// <param name="index">The zero-based index of the element to
/// get or set.</param>
/// <returns>The element at the specfied index.</returns>
public EditCurveKey this[int index]
{
get
{
return keys[index];
}
set
{
if (value == null)
{
throw new System.ArgumentNullException();
}
// If new value has same position, it just change values.
float curPosition = keys[index].OriginalKey.Position;
if (curPosition == value.OriginalKey.Position)
{
keys[index] = value;
owner.OriginalCurve.Keys[index] = value.OriginalKey;
}
else
{
// Otherwise, remove given index key and add new one.
RemoveAt(index);
Add(value);
owner.Dirty = true;
}
}
}
#endregion
#region ICollection<EditCurveKey> Members
/// <summary>
/// Add an item to the EditCurveKeyCollection
/// </summary>
/// <param name="item">CurveKey to add to the EditCurveKeyCollection</param>
public void Add(EditCurveKey item)
{
if (item == null)
throw new System.ArgumentNullException("item");
// Add CurveKey to original curve.
owner.OriginalCurve.Keys.Add(item.OriginalKey);
// Add EditCurveKey to keys.
int index = owner.OriginalCurve.Keys.IndexOf(item.OriginalKey);
keys.Insert(index, item);
idToKeyMap.Add(item.Id, item);
owner.Dirty = true;
}
/// <summary>
/// Removes all EditCurveKeys from the EditCurveKeyCollection.
/// </summary>
public void Clear()
{
owner.OriginalCurve.Keys.Clear();
keys.Clear();
idToKeyMap.Clear();
owner.Dirty = true;
}
/// <summary>
/// Determines whether the ExpandEnvironmentVariables
/// contains a specific EditCurveKey.
/// </summary>
/// <param name="item">The EditCurveKey to locate in
/// the EditEditCurveKeyCollection. </param>
/// <returns>true if the EditCurveKey is found in
/// the ExpandEnvironmentVariables; otherwise, false. </returns>
public bool Contains(EditCurveKey item)
{
if (item == null)
throw new System.ArgumentNullException("item");
return keys.Contains(item);
}
public void CopyTo(EditCurveKey[] array, int arrayIndex)
{
throw new NotImplementedException(
"The method or operation is not implemented.");
}
/// <summary>
/// Gets the number of elements contained in the EditCurveKeyCollection.
/// </summary>
public int Count
{
get { return keys.Count; }
}
/// <summary>
/// Gets a value indicating whether the EditEditCurveKeyCollection is
/// read-only.
/// </summary>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Removes the first occurrence of a specific EditCurveKey from
/// the EditCurveKeyCollection.
/// </summary>
/// <param name="item">The EditCurveKey to remove from
/// the EditCurveKeyCollection. </param>
/// <returns>true if item is successfully removed; otherwise, false.
/// This method also returns false if item was not found in
/// the EditCurveKeyCollection. </returns>
public bool Remove(EditCurveKey item)
{
if (item == null)
throw new System.ArgumentNullException("item");
bool result = owner.OriginalCurve.Keys.Remove(item.OriginalKey);
idToKeyMap.Remove(item.Id);
owner.Dirty = true;
return keys.Remove(item) && result;
}
#endregion
#region IEnumerable<EditCurveKey> Members
/// <summary>
/// Returns an enumerator that iterates through the EditCurveKeyCollection.
/// </summary>
/// <returns>A IEnumerator>EditCurveKey<
/// for the EditCurveKeyCollection. </returns>
public IEnumerator<EditCurveKey> GetEnumerator()
{
return keys.GetEnumerator();
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that iterates through the EditCurveKeyCollection.
/// </summary>
/// <returns>A IEnumerator for the EditCurveKeyCollection. </returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((System.Collections.IEnumerable)keys).GetEnumerator();
}
#endregion
/// <summary>
/// Tries to look up a EditCurveKey by id.
/// </summary>
public bool TryGetValue(long keyId, out EditCurveKey value)
{
return idToKeyMap.TryGetValue(keyId, out value);
}
/// <summary>
/// look up a EditCurveKey by id.
/// </summary>
public EditCurveKey GetValue(long keyId)
{
return idToKeyMap[keyId];
}
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>A new object that is a copy of this instance.</returns>
public EditCurveKeyCollection Clone()
{
EditCurveKeyCollection newKeys = new EditCurveKeyCollection();
newKeys.keys = new List<EditCurveKey>(keys);
return newKeys;
}
#region Private methods.
/// <summary>
/// Private default construction.
/// </summary>
private EditCurveKeyCollection()
{
}
#endregion
#region Private members.
/// <summary>
/// Owner of this collection
/// </summary>
private EditCurve owner;
/// <summary>
/// EditCurveKey that contains EditCurveKey
/// </summary>
private List<EditCurveKey> keys = new List<EditCurveKey>();
/// <summary>
/// Id to EditCurveKey map.
/// </summary>
private Dictionary<long, EditCurveKey> idToKeyMap =
new Dictionary<long, EditCurveKey>();
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
namespace NQuery
{
/// <summary>
/// Represents a location in the source code. Due to the fact that line and column are stored together on 32 bit the
/// maximum line is limited to 2^21 (2,097,152) whereby the maximum column is limited to 2^11 (2,048). That should not
/// be a hard restriction since the same limits apply to the C# compiler.
/// </summary>
/// <remarks>
/// Both <see cref="Line"/> and <see cref="Column"/> are zero based.
/// </remarks>
[Serializable]
[DebuggerDisplay("Ln {Line}; Col {Column}")]
public struct SourceLocation : IEquatable<SourceLocation>, IComparable<SourceLocation>, IComparable
{
/// <summary>
/// Maximum column index.
/// </summary>
public static readonly int MaxColumn = (2 << 10) - 1; // 11 bit for col - 1 (= 2,047)
/// <summary>
/// Maximum line index.
/// </summary>
public static readonly int MaxLine = (2 << 20) - 1; // 21 bit for line - 1 (= 2,097,151)
private const int COLUMN_MASK = 0x000007FF;
private const int LINE_MASK = unchecked (~COLUMN_MASK);
private int _pos;
/// <summary>
/// Creates a new <c>SourceLocation</c> with the specified 32 bit value representing the line/col information. The line
/// index is stored in the higher 21 bit whereby the column index is stored in the lower 11 bit.
/// </summary>
/// <param name="pos">Column and line index stored in one <see cref="Int32"/></param>
private SourceLocation(int pos)
{
_pos = pos;
}
/// <summary>
/// Creates a new <c>SourceLocation</c> with the specified column and line.
/// </summary>
/// <param name="column">Column index (must not exceed 2,048)</param>
/// <param name="line">Line index (must not exceed 2,097,152)</param>
public SourceLocation(int column, int line)
{
if (column < 0 || column > MaxColumn)
throw ExceptionBuilder.ArgumentOutOfRange("column", column, 0, MaxColumn);
if (line < 0 || line > MaxLine)
throw ExceptionBuilder.ArgumentOutOfRange("line", line, 0, MaxLine);
_pos = column;
_pos |= line << 11;
}
/// <summary>
/// Represents a source pos that is not legal.
/// </summary>
public static readonly SourceLocation None = new SourceLocation(int.MaxValue);
/// <summary>
/// Represents an empty source location i.e. col = 0, line = 0.
/// </summary>
public static readonly SourceLocation Empty = new SourceLocation();
/// <summary>
/// Represents the smallest possible value of a <see cref="SourceLocation"/>.
/// </summary>
public static readonly SourceLocation MinValue = new SourceLocation(0, 0);
/// <summary>
/// Represents the largest possible value of a <see cref="SourceLocation"/>.
/// </summary>
public static readonly SourceLocation MaxValue = new SourceLocation(MaxColumn, MaxLine);
/// <summary>
/// Gets or sets the column index for this source location (zero based). Must not exceed 2,048.
/// </summary>
public int Column
{
get
{
// return col part
return _pos & COLUMN_MASK;
}
set
{
if (value < 0 || value > MaxColumn)
throw ExceptionBuilder.ArgumentOutOfRange("value", value, 0, MaxColumn);
// clear col part
_pos &= LINE_MASK;
// assign col part
_pos |= value;
}
}
/// <summary>
/// Gets or sets the line index for this source location (zero based). Must not exceed 2,097,152.
/// </summary>
public int Line
{
get
{
// Return higher 21 bit
//
// NOTE: The conversion from int -> uint -> int is needed to avoid the first bit being interpreted
// as negation bit.
return (int) (((uint) _pos) >> 11);
}
set
{
if (value < 0 || value > MaxLine)
throw ExceptionBuilder.ArgumentOutOfRange("value", value, 0, MaxLine);
// clear higher 21 bit
_pos &= COLUMN_MASK;
// assign line part
_pos |= (value << 11);
}
}
public override int GetHashCode()
{
return _pos.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj is SourceLocation)
return this == (SourceLocation) obj;
else
return false;
}
public bool Equals(SourceLocation other)
{
return this == other;
}
public bool IsBefore(SourceLocation location)
{
return this < location;
}
public bool IsBeforeOrEqual(SourceLocation location)
{
return this <= location;
}
public bool IsAfter(SourceLocation location)
{
return this > location;
}
public bool IsAfterOrEqual(SourceLocation location)
{
return this >= location;
}
public SourceLocation Increment()
{
return this++;
}
public SourceLocation Decrement()
{
return this--;
}
public static SourceLocation operator ++(SourceLocation sourceLocation)
{
return new SourceLocation(sourceLocation.Column + 1, sourceLocation.Line);
}
public static SourceLocation operator --(SourceLocation sourceLocation)
{
if (sourceLocation.Column > 0)
return new SourceLocation(sourceLocation.Column - 1, sourceLocation.Line);
if (sourceLocation.Column == 0 && sourceLocation.Line > 0)
return new SourceLocation(MaxColumn, sourceLocation.Line - 1);
return Empty;
}
public static bool operator ==(SourceLocation left, SourceLocation right)
{
return left.Line == right.Line && left.Column == right.Column;
}
public static bool operator !=(SourceLocation left, SourceLocation right)
{
return left.Line != right.Line || left.Column != right.Column;
}
public static bool operator <=(SourceLocation left, SourceLocation right)
{
return left.Line < right.Line || left.Line == right.Line && left.Column <= right.Column;
}
public static bool operator >=(SourceLocation left, SourceLocation right)
{
return left.Line > right.Line || left.Line == right.Line && left.Column >= right.Column;
}
public static bool operator <(SourceLocation left, SourceLocation right)
{
return left.Line < right.Line || left.Line == right.Line && left.Column < right.Column;
}
public static bool operator >(SourceLocation left, SourceLocation right)
{
return left.Line > right.Line || left.Line == right.Line && left.Column > right.Column;
}
public int CompareTo(SourceLocation other)
{
if (this < other)
return -1;
if (this > other)
return 1;
return 0;
}
public int CompareTo(object obj)
{
if (obj == null)
return 1;
if (!(obj is SourceLocation))
throw ExceptionBuilder.ArgumentMustBeOfType("obj", typeof(SourceLocation));
SourceLocation location = (SourceLocation) obj;
return CompareTo(location);
}
public override string ToString()
{
return String.Format(CultureInfo.InvariantCulture, "Ln {0}; Col {1}", Line, Column);
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
$PostFXManager::vebose = true;
function postVerbose(%string)
{
if($PostFXManager::vebose == true)
{
echo(%string);
}
}
function PostFXManager::onDialogPush( %this )
{
//Apply the settings to the controls
postVerbose("% - PostFX Manager - Loading GUI.");
%this.settingsRefreshAll();
}
// :: Controls for the overall postFX manager dialog
function ppOptionsEnable::onAction(%this)
{
//Disable / Enable all PostFX
if(ppOptionsEnable.getValue())
{
%toEnable = true;
}
else
{
%toEnable = false;
}
PostFXManager.settingsSetEnabled(%toEnable);
}
function PostFXManager::getEnableResultFromControl(%this, %control)
{
%toEnable = -1;
%bTest = %control.getValue();
if(%bTest == 1)
{
%toEnable = true;
}
else
{
%toEnable = false;
}
return %toEnable;
}
function ppOptionsEnableSSAO::onAction(%this)
{
%toEnable = PostFXManager.getEnableResultFromControl(%this);
PostFXManager.settingsEffectSetEnabled("SSAO", %toEnable);
}
function ppOptionsEnableHDR::onAction(%this)
{
%toEnable = PostFXManager.getEnableResultFromControl(%this);
PostFXManager.settingsEffectSetEnabled("HDR", %toEnable);
}
function ppOptionsEnableLightRays::onAction(%this)
{
%toEnable = PostFXManager.getEnableResultFromControl(%this);
PostFXManager.settingsEffectSetEnabled("LightRays", %toEnable);
}
function ppOptionsEnableDOF::onAction(%this)
{
%toEnable = PostFXManager.getEnableResultFromControl(%this);
PostFXManager.settingsEffectSetEnabled("DOF", %toEnable);
}
function ppOptionsSavePreset::onClick(%this)
{
//Stores the current settings into a preset file for loading and use later on
}
function ppOptionsLoadPreset::onClick(%this)
{
//Loads and applies the settings from a postfxpreset file
}
//Other controls, Quality dropdown
function ppOptionsSSAOQuality::onSelect( %this, %id, %text )
{
if(%id > -1 && %id < 3)
{
$SSAOPostFx::quality = %id;
}
}
//SSAO Slider controls
//General Tab
function ppOptionsSSAOOverallStrength::onMouseDragged(%this)
{
$SSAOPostFx::overallStrength = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
function ppOptionsSSAOBlurDepth::onMouseDragged(%this)
{
$SSAOPostFx::blurDepthTol = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
function ppOptionsSSAOBlurNormal::onMouseDragged(%this)
{
$SSAOPostFx::blurNormalTol = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
//Near Tab
function ppOptionsSSAONearRadius::onMouseDragged(%this)
{
$SSAOPostFx::sRadius = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
function ppOptionsSSAONearStrength::onMouseDragged(%this)
{
$SSAOPostFx::sStrength = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
function ppOptionsSSAONearDepthMin::onMouseDragged(%this)
{
$SSAOPostFx::sDepthMin = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
function ppOptionsSSAONearDepthMax::onMouseDragged(%this)
{
$SSAOPostFx::sDepthMax = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
function ppOptionsSSAONearToleranceNormal::onMouseDragged(%this)
{
$SSAOPostFx::sNormalTol = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
function ppOptionsSSAONearTolerancePower::onMouseDragged(%this)
{
$SSAOPostFx::sNormalPow = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
//Far Tab
function ppOptionsSSAOFarRadius::onMouseDragged(%this)
{
$SSAOPostFx::lRadius = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
function ppOptionsSSAOFarStrength::onMouseDragged(%this)
{
$SSAOPostFx::lStrength = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
function ppOptionsSSAOFarDepthMin::onMouseDragged(%this)
{
$SSAOPostFx::lDepthMin = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
function ppOptionsSSAOFarDepthMax::onMouseDragged(%this)
{
$SSAOPostFx::lDepthMax = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
function ppOptionsSSAOFarToleranceNormal::onMouseDragged(%this)
{
$SSAOPostFx::lNormalTol = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
function ppOptionsSSAOFarTolerancePower::onMouseDragged(%this)
{
$SSAOPostFx::lNormalPow = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
//HDR Slider Controls
//Brighness tab
function ppOptionsHDRToneMappingAmount::onMouseDragged(%this)
{
$HDRPostFX::enableToneMapping = %this.value;
%this.ToolTip = "value : " @ %this.value;
}
function ppOptionsHDRKeyValue::onMouseDragged(%this)
{
$HDRPostFX::keyValue = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
function ppOptionsHDRMinLuminance::onMouseDragged(%this)
{
$HDRPostFX::minLuminace = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
function ppOptionsHDRWhiteCutoff::onMouseDragged(%this)
{
$HDRPostFX::whiteCutoff = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
function ppOptionsHDRBrightnessAdaptRate::onMouseDragged(%this)
{
$HDRPostFX::adaptRate = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
//Blur tab
function ppOptionsHDRBloomBlurBrightPassThreshold::onMouseDragged(%this)
{
$HDRPostFX::brightPassThreshold = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
function ppOptionsHDRBloomBlurMultiplier::onMouseDragged(%this)
{
$HDRPostFX::gaussMultiplier = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
function ppOptionsHDRBloomBlurMean::onMouseDragged(%this)
{
$HDRPostFX::gaussMean = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
function ppOptionsHDRBloomBlurStdDev::onMouseDragged(%this)
{
$HDRPostFX::gaussStdDev = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
function ppOptionsHDRBloom::onAction(%this)
{
$HDRPostFX::enableBloom = %this.getValue();
}
function ppOptionsHDRToneMapping::onAction(%this)
{
//$HDRPostFX::enableToneMapping = %this.getValue();
}
function ppOptionsHDREffectsBlueShift::onAction(%this)
{
$HDRPostFX::enableBlueShift = %this.getValue();
}
//Controls for color range in blue Shift dialog
function ppOptionsHDREffectsBlueShiftColorBlend::onAction(%this)
{
$HDRPostFX::blueShiftColor = %this.PickColor;
%this.ToolTip = "Color Values : " @ %this.PickColor;
}
function ppOptionsHDREffectsBlueShiftColorBaseColor::onAction(%this)
{
//This one feeds the one above
ppOptionsHDREffectsBlueShiftColorBlend.baseColor = %this.PickColor;
%this.ToolTip = "Color Values : " @ %this.PickColor;
}
//Light rays Slider Controls
function ppOptionsLightRaysBrightScalar::onMouseDragged(%this)
{
$LightRayPostFX::brightScalar = %this.value;
%this.ToolTip = "Value : " @ %this.value;
}
function ppOptionsUpdateDOFSettings()
{
DOFPostEffect.setFocusParams( $DOFPostFx::BlurMin, $DOFPostFx::BlurMax, $DOFPostFx::FocusRangeMin, $DOFPostFx::FocusRangeMax, -($DOFPostFx::BlurCurveNear), $DOFPostFx::BlurCurveFar );
DOFPostEffect.setAutoFocus( $DOFPostFx::EnableAutoFocus );
DOFPostEffect.setFocalDist(0);
if($PostFXManager::PostFX::EnableDOF)
{
DOFPostEffect.enable();
}
else
{
DOFPostEffect.disable();
}
}
//DOF General Tab
//DOF Toggles
function ppOptionsDOFEnableDOF::onAction(%this)
{
$PostFXManager::PostFX::EnableDOF = %this.getValue();
ppOptionsUpdateDOFSettings();
}
function ppOptionsDOFEnableAutoFocus::onAction(%this)
{
$DOFPostFx::EnableAutoFocus = %this.getValue();
DOFPostEffect.setAutoFocus( %this.getValue() );
}
//DOF AutoFocus Slider controls
function ppOptionsDOFFarBlurMinSlider::onMouseDragged(%this)
{
$DOFPostFx::BlurMin = %this.value;
ppOptionsUpdateDOFSettings();
}
function ppOptionsDOFFarBlurMaxSlider::onMouseDragged(%this)
{
$DOFPostFx::BlurMax = %this.value;
ppOptionsUpdateDOFSettings();
}
function ppOptionsDOFFocusRangeMinSlider::onMouseDragged(%this)
{
$DOFPostFx::FocusRangeMin = %this.value;
ppOptionsUpdateDOFSettings();
}
function ppOptionsDOFFocusRangeMaxSlider::onMouseDragged(%this)
{
$DOFPostFx::FocusRangeMax = %this.value;
ppOptionsUpdateDOFSettings();
}
function ppOptionsDOFBlurCurveNearSlider::onMouseDragged(%this)
{
$DOFPostFx::BlurCurveNear = %this.value;
ppOptionsUpdateDOFSettings();
}
function ppOptionsDOFBlurCurveFarSlider::onMouseDragged(%this)
{
$DOFPostFx::BlurCurveFar = %this.value;
ppOptionsUpdateDOFSettings();
}
function ppOptionsEnableHDRDebug::onAction(%this)
{
if ( %this.getValue() )
LuminanceVisPostFX.enable();
else
LuminanceVisPostFX.disable();
}
function ppColorCorrection_selectFile()
{
%filter = "Image Files (*.png, *.jpg, *.dds, *.bmp, *.gif, *.jng. *.tga)|*.png;*.jpg;*.dds;*.bmp;*.gif;*.jng;*.tga|All Files (*.*)|*.*|";
getLoadFilename( %filter, "ppColorCorrection_selectFileHandler");
}
function ppColorCorrection_selectFileHandler( %filename )
{
if ( %filename $= "" || !isFile( %filename ) )
%filename = "core/scripts/client/postFx/null_color_ramp.png";
else
%filename = makeRelativePath( %filename, getMainDotCsDir() );
$HDRPostFX::colorCorrectionRamp = %filename;
PostFXManager-->ColorCorrectionFileName.Text = %filename;
}
| |
#region Using
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
using Janus.Windows.Common;
using Janus.Windows.UI.CommandBars;
using TribalWars.Controls;
using System.Drawing;
using TribalWars.Maps.Controls;
using TribalWars.Maps.Drawing;
using TribalWars.Maps.Drawing.Displays;
using TribalWars.Maps.Drawing.Views;
using TribalWars.Maps.Icons;
using TribalWars.Maps.Manipulators;
using TribalWars.Maps.Manipulators.EventArg;
using TribalWars.Maps.Manipulators.Managers;
using TribalWars.Maps.Markers;
using TribalWars.Tools;
using TribalWars.Tools.JanusExtensions;
using TribalWars.Villages;
using TribalWars.Worlds;
using TribalWars.Worlds.Events;
using TribalWars.Worlds.Events.Impls;
#endregion
namespace TribalWars.Maps
{
/// <summary>
/// Representation of a TW map
/// </summary>
public sealed class Map
{
#region Fields
private Display _display;
private ScrollableMapControl _control;
private readonly JanusSuperTip _toolTip;
private IContextMenu _activeContextMenu;
private DisplaySettings _displaysettings;
private readonly bool _isMiniMap;
#endregion
#region Properties
/// <summary>
/// Gets all villages to mark
/// </summary>
public MarkerManager MarkerManager { get; private set; }
/// <summary>
/// Gets the object that interacts with the user
/// </summary>
public ManipulatorManagerController Manipulators { get; private set; }
/// <summary>
/// Gets the object that encapsulates event raising
/// </summary>
public Publisher EventPublisher { get; private set; }
/// <summary>
/// Gets the map visual settings
/// </summary>
public Display Display
{
get { return _display; }
private set
{
if (_display != null)
{
_display.Dispose();
}
_display = value;
}
}
/// <summary>
/// Size of the map canvas
/// </summary>
public Size CanvasSize
{
get { return _control.ClientRectangle.Size; }
}
/// <summary>
/// Gets or sets the Map location & zoom level
/// </summary>
public Location Location { get; private set; }
/// <summary>
/// Gets or sets the home position of the map
/// </summary>
public Location HomeLocation { get; set; }
/// <summary>
/// Only after a map was painted, start reacting to events etc
/// </summary>
public bool HasPainted
{
get { return Location != null; }
}
private int LastShapeZoom
{
get { return _lastShapeZoom ?? 10; }
}
#endregion
#region Constructors
/// <summary>
/// Creates a new MiniMap
/// </summary>
private Map(Map mainMap)
{
_isMiniMap = true;
EventPublisher = new Publisher(this);
MarkerManager = mainMap.MarkerManager;
Manipulators = new ManipulatorManagerController(this, mainMap);
_toolTip = JanusControls.CreateTooltip();
SetTooltipProperties();
}
/// <summary>
/// Creates a new Map
/// </summary>
private Map()
{
_isMiniMap = false;
EventPublisher = new Publisher(this);
MarkerManager = new MarkerManager();
Manipulators = new ManipulatorManagerController(this);
_toolTip = JanusControls.CreateTooltip();
SetTooltipProperties();
}
public static Map CreateMap()
{
return new Map();
}
public static Map CreateMiniMap(Map mainMap)
{
return new Map(mainMap);
}
private void SetTooltipProperties()
{
_toolTip.InitialDelay = 400;
_toolTip.AutoPopDelay = 6000;
//_toolTip.ToolTipPopUp += (sender, args) =>
// {
// Debug.WriteLine("------------->" + _control.Cursor + " setting to " + _cursor);
// _control.Cursor = _cursor;
// };
}
public void InitializeMiniMapDisplay(DisplaySettings settings)
{
Debug.Assert(_isMiniMap);
_displaysettings = settings;
Location = new Location(DisplayTypes.Shape, 500, 500, MiniMapDrawerFactory.MaxZoomLevel);
var loc = Location;
Display = new Display(settings, true, this, ref loc);
}
public void SetDisplaySettings(DisplaySettings settings)
{
Debug.Assert(!_isMiniMap);
_displaysettings = settings;
}
/// <summary>
/// Sets the UserControl for the Map Class
/// </summary>
public void SetMapControl(MapControl map)
{
Debug.Assert(!_isMiniMap);
_control = map.ScrollableMap;
_control.SetMap(this);
map.SetMap(this);
}
/// <summary>
/// Sets the UserControl for the Map Class and start it as a minimap
/// </summary>
public void SetMiniMapControls(MiniMapControl miniMap, Map mainMap)
{
Debug.Assert(_isMiniMap);
_control = miniMap;
_control.SetMap(this);
miniMap.SetMap(this, mainMap);
}
#endregion
#region Change Map Center
private int? _lastShapeZoom;
private int? _lastIconZoom;
/// <summary>
/// Switch between Icon and Shape displays
/// </summary>
public void SwitchDisplay()
{
bool isInShapeDisplay = _display.Type == DisplayTypes.Shape;
if (isInShapeDisplay)
{
_lastShapeZoom = _display.Zoom.Current;
SetCenter(World.Default.Map.Location.ChangeShapeAndZoom(DisplayTypes.Icon, _lastIconZoom ?? 1));
}
else
{
_lastIconZoom = _display.Zoom.Current;
SetCenter(World.Default.Map.Location.ChangeShapeAndZoom(DisplayTypes.Shape, LastShapeZoom));
}
}
/// <summary>
/// Center on middle of a continent
/// </summary>
public void SetCenterContinent(int continent)
{
if (continent <= 99 && continent >= 0)
{
int x = continent % 10 * 100 + 50;
int y = (continent - continent % 10) * 10 + 50;
SetCenter(this, new Location(Location.Display, x, y, Location.Zoom));
}
}
/// <summary>
/// Changes the zoom level
/// </summary>
public void SetZoomLevel(int zoom)
{
SetCenter(this, new Location(Location.Display, Location.X, Location.Y, zoom));
}
/// <summary>
/// Changes the zoom level
/// </summary>
public void IncreaseZoomLevel(int amount)
{
if (Display.Type == DisplayTypes.Icon) amount *= -1;
SetCenter(this, new Location(Location.Display, Location.X, Location.Y, Location.Zoom + amount));
}
/// <summary>
/// Changes the zoom level
/// </summary>
public void IncreaseZoomLevel(Point location, int amount)
{
if (Display.Type == DisplayTypes.Icon) amount *= -1;
SetCenter(this, new Location(Location.Display, location.X, location.Y, Location.Zoom + amount));
}
/// <summary>
/// Changes the x and y coordinates
/// </summary>
public void SetCenter(Point point)
{
SetCenter(this, new Location(Location.Display, point.X, point.Y, Location.Zoom));
}
/// <summary>
/// Changes center so that all villages are visible
/// </summary>
public void SetCenter(IEnumerable<Village> villages, bool tryStayInCurrentZoom = true)
{
Debug.Assert(villages != null);
Location location = GetSpan(villages, tryStayInCurrentZoom);
SetCenter(location);
}
/// <summary>
/// Calculates the coordinates and zoom level so all villages are visible
/// </summary>
private Location GetSpan(IEnumerable<Village> vils, bool tryStayInCurrentZoom = true)
{
int leftX = 999, topY = 999, rightX = 0, bottomY = 0;
foreach (Village vil in vils)
{
if (vil.X < leftX) leftX = vil.X;
if (vil.X > rightX) rightX = vil.X;
if (vil.Y < topY) topY = vil.Y;
if (vil.Y > bottomY) bottomY = vil.Y;
}
return GetSpan(new Rectangle(leftX, topY, rightX - leftX, bottomY - topY), tryStayInCurrentZoom);
}
/// <summary>
/// Calculates the coordinates and zoom level so all villages are visible
/// </summary>
public Location GetSpan(Rectangle game, bool tryStayInCurrentZoom = true, int villagesExtraVisible = 5)
{
var middle = new Point(
(game.Left + game.Right) / 2,
(game.Top + game.Bottom) / 2);
var maxVillageSize = new Size(
CanvasSize.Width / (game.Width + villagesExtraVisible),
CanvasSize.Height / (game.Height + villagesExtraVisible));
// HACK: Auto switch from Icon to Shape display when using for example Center&Pinpoint
bool couldSatisfy;
int newZoomLevel = Display.GetMinimumZoomLevel(maxVillageSize, tryStayInCurrentZoom, out couldSatisfy);
if (!couldSatisfy && Display.Type == DisplayTypes.Icon)
{
_lastIconZoom = _display.Zoom.Current;
var location = new Location(DisplayTypes.Shape, middle, LastShapeZoom);
Display = new Display(_displaysettings, _isMiniMap, this, ref location);
newZoomLevel = Display.GetMinimumZoomLevel(maxVillageSize, tryStayInCurrentZoom, out couldSatisfy);
return new Location(DisplayTypes.Shape, middle, newZoomLevel);
}
return new Location(Location.Display, middle, newZoomLevel);
}
/// <summary>
/// Changes the x and y coordinates and the zoom level
/// </summary>
public void SetCenter(Point loc, int zoom)
{
SetCenter(this, new Location(Location.Display, loc, zoom));
}
/// <summary>
/// Changes the center of the map
/// </summary>
public void SetCenter(Location loc)
{
SetCenter(this, loc);
}
/// <summary>
/// Changes the center of the map
/// </summary>
private void SetCenter(object sender, Location location)
{
if (location != null)
{
if (Display == null || Display.Type != location.Display || Display.Zoom.Current != location.Zoom)
{
Display = new Display(_displaysettings, _isMiniMap, this, ref location);
}
if (location != Location)
{
Location oldLocation = Location;
Location = location;
Display.UpdateLocation(CanvasSize, oldLocation, location);
EventPublisher.SetMapCenter(sender, new MapLocationEventArgs(location, oldLocation, Display.Zoom));
}
}
else
{
Debug.Assert(false, "setting location to null... let's not go there");
Location = null;
}
}
/// <summary>
/// Center on home location
/// </summary>
public void GoHome()
{
SetCenter(HomeLocation);
}
/// <summary>
/// Save the current location as your home location
/// </summary>
public void SaveHome()
{
HomeLocation = Location;
}
#endregion
#region ContextMenu
public void ShowContextMenu(IContextMenu menu, Point mapLocation)
{
StopTooltip();
_activeContextMenu = menu;
menu.Show(_control, mapLocation);
}
#endregion
#region Tooltip
public void ShowTooltip(string title, string body)
{
var settings = new SuperTipSettings();
settings.HeaderText = title;
settings.Text = body;
ShowTooltip(settings);
}
public void ShowTooltip(SuperTipSettings settings)
{
if (!TooltipAllowed())
{
return;
}
_toolTip.Show(settings, _control);
}
private bool TooltipAllowed()
{
if (_activeContextMenu != null && _activeContextMenu.IsVisible())
{
// No tooltips when there is a contextmenu active
return false;
}
return true;
}
public void StopTooltip()
{
_toolTip.HideActiveToolTip();
}
#endregion
#region Map Cursor
/// <summary>
/// Resets the cursor of the map
/// </summary>
public void SetCursor()
{
_control.Cursor = Cursors.Default;
}
/// <summary>
/// Changes the cursor of the map
/// </summary>
public void SetCursor(Cursor cursor)
{
if (cursor == Cursors.Default)
{
SetCursor();
}
else
{
_control.Cursor = cursor;
}
}
#endregion
#region Other
public void Paint(Graphics g, Rectangle fullMap)
{
var paintArgs = new MapPaintEventArgs(g, fullMap);
Display.Paint(g, fullMap);
Manipulators.Paint(paintArgs);
}
/// <summary>
/// Forces a redraw of the map. If you want the MiniMap
/// to be invalidated aswell, call World.DrawMaps instead
/// </summary>
public void Invalidate(bool resetBackgroundCache = true)
{
if (resetBackgroundCache && Display != null)
{
Display.ResetCache();
}
_control.Invalidate();
}
public void GiveFocus()
{
_control.GiveFocus();
}
/// <summary>
/// Creates a screenshot of the map
/// </summary>
public void Screenshot(string fileName)
{
using (var shot = new Bitmap(CanvasSize.Width, CanvasSize.Height))
{
_control.DrawToBitmap(shot, new Rectangle(new Point(0, 0), CanvasSize));
shot.Save(fileName);
}
}
public override string ToString()
{
return string.Format("ControlName={0}, Loc={1}", _control.Name, Location);
}
#endregion
}
}
| |
// Copyright 2017 Esri.
//
// 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 Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.UI.Controls;
using Foundation;
using System;
using System.Collections.Generic;
using System.Linq;
using UIKit;
namespace ArcGISRuntime.Samples.StatisticalQuery
{
[Register("StatisticalQuery")]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Statistical query",
category: "Data",
description: "Query a table to get aggregated statistics back for a specific field.",
instructions: "Pan and zoom to define the extent for the query. Use the 'Cities in current extent' checkbox to control whether the query only includes features in the visible extent. Use the 'Cities grater than 5M' checkbox to filter the results to only those cities with a population greater than 5 million people. Tap 'Get statistics' to perform the query. The query will return population-based statistics from the combined results of all features matching the query criteria.",
tags: new[] { "analysis", "average", "bounding geometry", "filter", "intersect", "maximum", "mean", "minimum", "query", "spatial query", "standard deviation", "statistics", "sum", "variance" })]
public class StatisticalQuery : UIViewController
{
// Hold references to UI controls.
private MapView _myMapView;
private UIBarButtonItem _queryButton;
// URI for the world cities map service layer.
private readonly Uri _worldCitiesServiceUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/SampleWorldCities/MapServer/0");
// World cities feature table.
private FeatureTable _worldCitiesTable;
public StatisticalQuery()
{
Title = "Statistical query";
}
private void Initialize()
{
// Create a new Map with the world streets vector basemap.
Map myMap = new Map(BasemapStyle.ArcGISStreets);
// Create feature table using the world cities URI.
_worldCitiesTable = new ServiceFeatureTable(_worldCitiesServiceUri);
// Create a new feature layer to display features in the world cities table.
FeatureLayer worldCitiesLayer = new FeatureLayer(_worldCitiesTable);
// Add the world cities layer to the map.
myMap.OperationalLayers.Add(worldCitiesLayer);
// Assign the map to the MapView.
_myMapView.Map = myMap;
}
private void GetStatisticsPressed(object sender, EventArgs e)
{
var alert = UIAlertController.Create("Query statistics", "Get statistics for all cities matching these criteria", UIAlertControllerStyle.ActionSheet);
if (alert.PopoverPresentationController != null)
{
alert.PopoverPresentationController.BarButtonItem = _queryButton;
}
alert.AddAction(UIAlertAction.Create("Cities in extent with pop. > 5M", UIAlertActionStyle.Default, action => QueryStatistics(true, true)));
alert.AddAction(UIAlertAction.Create("Cities with pop. > 5M", UIAlertActionStyle.Default, action => QueryStatistics(false, true)));
alert.AddAction(UIAlertAction.Create("Cities in extent", UIAlertActionStyle.Default, action => QueryStatistics(true, false)));
alert.AddAction(UIAlertAction.Create("All cities", UIAlertActionStyle.Default, action => QueryStatistics(false, false)));
PresentViewController(alert, true, null);
}
private async void QueryStatistics(bool onlyInExtent, bool onlyLargePop)
{
try
{
// Create definitions for each statistic to calculate.
StatisticDefinition statDefinitionAvgPop = new StatisticDefinition("POP", StatisticType.Average, "");
StatisticDefinition statDefinitionMinPop = new StatisticDefinition("POP", StatisticType.Minimum, "");
StatisticDefinition statDefinitionMaxPop = new StatisticDefinition("POP", StatisticType.Maximum, "");
StatisticDefinition statDefinitionSumPop = new StatisticDefinition("POP", StatisticType.Sum, "");
StatisticDefinition statDefinitionStdDevPop = new StatisticDefinition("POP", StatisticType.StandardDeviation, "");
StatisticDefinition statDefinitionVarPop = new StatisticDefinition("POP", StatisticType.Variance, "");
// Create a definition for count that includes an alias for the output.
StatisticDefinition statDefinitionCount = new StatisticDefinition("POP", StatisticType.Count, "CityCount");
// Add the statistics definitions to a list.
List<StatisticDefinition> statDefinitions = new List<StatisticDefinition>
{
statDefinitionAvgPop,
statDefinitionCount,
statDefinitionMinPop,
statDefinitionMaxPop,
statDefinitionSumPop,
statDefinitionStdDevPop,
statDefinitionVarPop
};
// Create the statistics query parameters, pass in the list of definitions.
StatisticsQueryParameters statQueryParams = new StatisticsQueryParameters(statDefinitions);
// If only using features in the current extent, set up the spatial filter for the statistics query parameters.
if (onlyInExtent)
{
// Get the current extent (envelope) from the map view.
Envelope currentExtent = _myMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry as Envelope;
// Set the statistics query parameters geometry with the current extent.
statQueryParams.Geometry = currentExtent;
// Set the spatial relationship to Intersects (which is the default).
statQueryParams.SpatialRelationship = SpatialRelationship.Intersects;
}
// If only evaluating the largest cities (over 5 million in population), set up an attribute filter.
if (onlyLargePop)
{
// Set a where clause to get the largest cities (could also use "POP_CLASS = '5,000,000 and greater'").
statQueryParams.WhereClause = "POP_RANK = 1";
}
// Execute the statistical query with these parameters and await the results.
StatisticsQueryResult statQueryResult = await _worldCitiesTable.QueryStatisticsAsync(statQueryParams);
// Get the first (only) StatisticRecord in the results.
StatisticRecord record = statQueryResult.FirstOrDefault();
// Make sure a record was returned.
if (record == null || record.Statistics.Count == 0)
{
ShowMessage("No result", "No results were returned.");
return;
}
// Display results.
ShowStatsList(record.Statistics);
}
catch (Exception ex)
{
ShowMessage("There was a problem running the query.", ex.Message);
}
}
private void ShowStatsList(IReadOnlyDictionary<string, object> stats)
{
// Create a string for statistics in plain text.
string statsList = "";
// Loop through all key/value pairs in the results.
foreach (KeyValuePair<string, object> kvp in stats)
{
// If the value is null, display "--".
string displayString = "--";
if (kvp.Value != null)
{
displayString = kvp.Value.ToString();
}
// Add the statistics info to the output string.
statsList = $"{statsList}\n{kvp.Key} : {displayString}";
}
// Create a new Alert Controller.
UIAlertController statsAlert = UIAlertController.Create("Statistics", statsList, UIAlertControllerStyle.Alert);
// Add an Action to dismiss the alert.
statsAlert.AddAction(UIAlertAction.Create("Dismiss", UIAlertActionStyle.Cancel, null));
// Display the alert.
PresentViewController(statsAlert, true, null);
}
private void ShowMessage(string title, string message)
{
new UIAlertView(title, message, (IUIAlertViewDelegate)null, "OK", null).Show();
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
Initialize();
}
public override void LoadView()
{
// Create the views.
View = new UIView { BackgroundColor = ApplicationTheme.BackgroundColor };
_myMapView = new MapView();
_myMapView.TranslatesAutoresizingMaskIntoConstraints = false;
_queryButton = new UIBarButtonItem();
_queryButton.Title = "Get statistics";
UIToolbar toolbar = new UIToolbar();
toolbar.TranslatesAutoresizingMaskIntoConstraints = false;
toolbar.Items = new[]
{
new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
_queryButton,
new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace)
};
// Add the views.
View.AddSubviews(_myMapView, toolbar);
// Lay out the views.
NSLayoutConstraint.ActivateConstraints(new[]
{
_myMapView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
_myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
_myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
_myMapView.BottomAnchor.ConstraintEqualTo(toolbar.TopAnchor),
toolbar.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor),
toolbar.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
toolbar.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
});
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
// Subscribe to events.
_queryButton.Clicked += GetStatisticsPressed;
}
public override void ViewDidDisappear(bool animated)
{
base.ViewDidDisappear(animated);
// Unsubscribe from events, per best practice.
_queryButton.Clicked -= GetStatisticsPressed;
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// AsyncWork.cs
//
// Helper class that is used to test the FromAsync method. These classes hold the APM patterns
// and is used by the TaskFromAsyncTest.cs file
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
namespace System.Threading.Tasks.Tests
{
#region AsyncWork (base)
/// <summary>
/// The abstract that defines the work done by the Async method
/// </summary>
public abstract class AsyncWork
{
/// <summary>
/// Defines the amount of time the thread should sleep (to simulate workload)
/// </summary>
private const int DEFAULT_TIME = 15;
private List<object> _inputs;
public AsyncWork()
{
_inputs = new List<object>();
}
protected void AddInput(object o)
{
_inputs.Add(o);
}
protected void InvokeAction(bool throwing)
{
//
// simulate some dummy workload
//
var task = Task.Delay(DEFAULT_TIME);
task.Wait();
if (throwing) //simulates error condition during the execution of user delegate
{
throw new TPLTestException();
}
}
protected ReadOnlyCollection<object> InvokeFunc(bool throwing)
{
//
// simulate some dummy workload
//
var task = Task.Delay(DEFAULT_TIME);
task.Wait();
if (throwing)
{
throw new TPLTestException();
}
return Inputs;
}
protected void CheckState(object o)
{
ObservedState = o;
ObservedTaskScheduler = TaskScheduler.Current;
}
public ReadOnlyCollection<object> Inputs
{
get
{
return new ReadOnlyCollection<object>(_inputs);
}
}
public object ObservedState
{
get;
private set;
}
public object ObservedTaskScheduler
{
get;
private set;
}
}
#endregion
#region AsyncAction
/// <summary>
/// Extends the base class to implement that action form of APM
/// </summary>
public class AsyncAction : AsyncWork
{
private Action _action;
// a general action to take-in inputs upfront rather than delayed until BeginInvoke
// for testing the overload taking IAsyncResult
public AsyncAction(object[] inputs, bool throwing)
: base()
{
_action = () =>
{
foreach (object o in inputs)
{
AddInput(o);
}
InvokeAction(throwing);
};
}
public AsyncAction(bool throwing)
: base()
{
_action = () =>
{
InvokeAction(throwing);
};
}
#region APM
public IAsyncResult BeginInvoke(AsyncCallback cb, object state)
{
Task task = Task.Factory.StartNew(_ => _action(), state, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
task.ContinueWith(_ => cb(task));
return task;
}
public void EndInvoke(IAsyncResult iar)
{
CheckState(iar.AsyncState);
((Task)iar).GetAwaiter().GetResult();
}
#endregion
}
/// <summary>
/// Extends the base class to implement that action form of APM with one parameter
/// </summary>
public class AsyncAction<T> : AsyncWork
{
public delegate void Action<TArg>(TArg obj);
private Action<T> _action;
public AsyncAction(bool throwing)
: base()
{
_action = (o) =>
{
AddInput(o);
InvokeAction(throwing);
};
}
#region APM
public IAsyncResult BeginInvoke(T t, AsyncCallback cb, object state)
{
Task task = Task.Factory.StartNew(_ => _action(t), state, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
task.ContinueWith(_ => cb(task));
return task;
}
public void EndInvoke(IAsyncResult iar)
{
CheckState(iar.AsyncState);
((Task)iar).GetAwaiter().GetResult();
}
#endregion
}
/// <summary>
/// Extends the base class to implement that action form of APM with two parameters
/// </summary>
public class AsyncAction<T1, T2> : AsyncWork
{
private Action<T1, T2> _action;
public AsyncAction(bool throwing)
: base()
{
_action = (o1, o2) =>
{
AddInput(o1);
AddInput(o2);
InvokeAction(throwing);
};
}
#region APM
public IAsyncResult BeginInvoke(T1 t1, T2 t2, AsyncCallback cb, object state)
{
Task task = Task.Factory.StartNew(_ => _action(t1, t2), state, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
task.ContinueWith(_ => cb(task));
return task;
}
public void EndInvoke(IAsyncResult iar)
{
CheckState(iar.AsyncState);
((Task)iar).GetAwaiter().GetResult();
}
#endregion
}
/// <summary>
/// Extends the base class to implement that action form of APM with three parameters
/// </summary>
public class AsyncAction<T1, T2, T3> : AsyncWork
{
private Action<T1, T2, T3> _action;
public AsyncAction(bool throwing)
: base()
{
_action = (o1, o2, o3) =>
{
AddInput(o1);
AddInput(o2);
AddInput(o3);
InvokeAction(throwing);
};
}
#region APM
public IAsyncResult BeginInvoke(T1 t1, T2 t2, T3 t3, AsyncCallback cb, object state)
{
Task task = Task.Factory.StartNew(_ => _action(t1, t2, t3), state, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
task.ContinueWith(_ => cb(task));
return task;
}
public void EndInvoke(IAsyncResult iar)
{
CheckState(iar.AsyncState);
((Task)iar).GetAwaiter().GetResult();
}
#endregion
}
#endregion
#region AsyncFunc
/// <summary>
/// Extends the base class to implement that function form of APM
/// </summary>
public class AsyncFunc : AsyncWork
{
private Func<ReadOnlyCollection<object>> _func;
// a general func to take-in inputs upfront rather than delayed until BeginInvoke
// for testing the overload taking IAsyncResult
public AsyncFunc(object[] inputs, bool throwing)
: base()
{
_func = () =>
{
foreach (object o in inputs)
{
AddInput(o);
}
return InvokeFunc(throwing);
};
}
public AsyncFunc(bool throwing)
: base()
{
_func = () =>
{
return InvokeFunc(throwing);
};
}
#region APM
public IAsyncResult BeginInvoke(AsyncCallback cb, object state)
{
Task<ReadOnlyCollection<object>> task = Task.Factory.StartNew(_ => _func(), state, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
task.ContinueWith(_ => cb(task));
return task;
}
public ReadOnlyCollection<object> EndInvoke(IAsyncResult iar)
{
CheckState(iar.AsyncState);
return ((Task<ReadOnlyCollection<object>>)iar).GetAwaiter().GetResult();
}
#endregion
}
/// <summary>
/// Extends the base class to implement that function form of APM with one parameter
/// </summary>
public class AsyncFunc<T> : AsyncWork
{
private Func<T, ReadOnlyCollection<object>> _func;
public AsyncFunc(bool throwing)
: base()
{
_func = (o) =>
{
AddInput(o);
return InvokeFunc(throwing);
};
}
#region APM
public IAsyncResult BeginInvoke(T t, AsyncCallback cb, object state)
{
Task<ReadOnlyCollection<object>> task = Task.Factory.StartNew(_ => _func(t), state, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
task.ContinueWith(_ => cb(task));
return task;
}
public ReadOnlyCollection<object> EndInvoke(IAsyncResult iar)
{
CheckState(iar.AsyncState);
return ((Task<ReadOnlyCollection<object>>)iar).GetAwaiter().GetResult();
}
#endregion
}
/// <summary>
/// Extends the base class to implement that function form of APM with two parameters
/// </summary>
public class AsyncFunc<T1, T2> : AsyncWork
{
private Func<T1, T2, ReadOnlyCollection<object>> _func;
public AsyncFunc(bool throwing)
: base()
{
_func = (o1, o2) =>
{
AddInput(o1);
AddInput(o2);
return InvokeFunc(throwing);
};
}
#region APM
public IAsyncResult BeginInvoke(T1 t1, T2 t2, AsyncCallback cb, object state)
{
Task<ReadOnlyCollection<object>> task = Task.Factory.StartNew(_ => _func(t1, t2), state, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
task.ContinueWith(_ => cb(task));
return task;
}
public ReadOnlyCollection<object> EndInvoke(IAsyncResult iar)
{
CheckState(iar.AsyncState);
return ((Task<ReadOnlyCollection<object>>)iar).GetAwaiter().GetResult();
}
#endregion
}
/// <summary>
/// Extends the base class to implement that function form of APM with three parameters
/// </summary>
public class AsyncFunc<T1, T2, T3> : AsyncWork
{
private Func<T1, T2, T3, ReadOnlyCollection<object>> _func;
public AsyncFunc(bool throwing)
: base()
{
_func = (o1, o2, o3) =>
{
AddInput(o1);
AddInput(o2);
AddInput(o3);
return InvokeFunc(throwing);
};
}
#region APM
public IAsyncResult BeginInvoke(T1 t1, T2 t2, T3 t3, AsyncCallback cb, object state)
{
Task<ReadOnlyCollection<object>> task = Task.Factory.StartNew(_ => _func(t1, t2, t3), state, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
task.ContinueWith(_ => cb(task));
return task;
}
public ReadOnlyCollection<object> EndInvoke(IAsyncResult iar)
{
CheckState(iar.AsyncState);
return ((Task<ReadOnlyCollection<object>>)iar).GetAwaiter().GetResult();
}
#endregion
}
#endregion
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors.Simulation;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "RemoteSimulationConnectorModule")]
public class RemoteSimulationConnectorModule : ISharedRegionModule, ISimulationService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool initialized = false;
protected bool m_enabled = false;
protected Scene m_aScene;
// RemoteSimulationConnector does not care about local regions; it delegates that to the Local module
protected LocalSimulationConnectorModule m_localBackend;
protected SimulationServiceConnector m_remoteConnector;
protected bool m_safemode;
protected IPAddress m_thisIP;
#region Region Module interface
public virtual void Initialise(IConfigSource configSource)
{
IConfig moduleConfig = configSource.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("SimulationServices", "");
if (name == Name)
{
m_localBackend = new LocalSimulationConnectorModule();
m_localBackend.InitialiseService(configSource);
m_remoteConnector = new SimulationServiceConnector();
m_enabled = true;
m_log.Info("[REMOTE SIMULATION CONNECTOR]: Remote simulation enabled.");
}
}
}
public virtual void PostInitialise()
{
}
public virtual void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_enabled)
return;
if (!initialized)
{
InitOnce(scene);
initialized = true;
}
InitEach(scene);
}
public void RemoveRegion(Scene scene)
{
if (m_enabled)
{
m_localBackend.RemoveScene(scene);
scene.UnregisterModuleInterface<ISimulationService>(this);
}
}
public void RegionLoaded(Scene scene)
{
if (!m_enabled)
return;
}
public Type ReplaceableInterface
{
get { return null; }
}
public virtual string Name
{
get { return "RemoteSimulationConnectorModule"; }
}
protected virtual void InitEach(Scene scene)
{
m_localBackend.Init(scene);
scene.RegisterModuleInterface<ISimulationService>(this);
}
protected virtual void InitOnce(Scene scene)
{
m_aScene = scene;
//m_regionClient = new RegionToRegionClient(m_aScene, m_hyperlinkService);
m_thisIP = Util.GetHostFromDNS(scene.RegionInfo.ExternalHostName);
}
#endregion
#region IInterregionComms
public IScene GetScene(UUID regionId)
{
return m_localBackend.GetScene(regionId);
}
public ISimulationService GetInnerService()
{
return m_localBackend;
}
/**
* Agent-related communications
*/
public bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, out string reason)
{
if (destination == null)
{
reason = "Given destination was null";
m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: CreateAgent was given a null destination");
return false;
}
// Try local first
if (m_localBackend.CreateAgent(destination, aCircuit, teleportFlags, out reason))
return true;
// else do the remote thing
if (!m_localBackend.IsLocalRegion(destination.RegionID))
{
return m_remoteConnector.CreateAgent(destination, aCircuit, teleportFlags, out reason);
}
return false;
}
public bool UpdateAgent(GridRegion destination, AgentData cAgentData)
{
if (destination == null)
return false;
// Try local first
if (m_localBackend.IsLocalRegion(destination.RegionID))
return m_localBackend.UpdateAgent(destination, cAgentData);
return m_remoteConnector.UpdateAgent(destination, cAgentData);
}
public bool UpdateAgent(GridRegion destination, AgentPosition cAgentData)
{
if (destination == null)
return false;
// Try local first
if (m_localBackend.IsLocalRegion(destination.RegionID))
return m_localBackend.UpdateAgent(destination, cAgentData);
return m_remoteConnector.UpdateAgent(destination, cAgentData);
}
public bool QueryAccess(GridRegion destination, UUID id, Vector3 position, out string version, out string reason)
{
reason = "Communications failure";
version = "Unknown";
if (destination == null)
return false;
// Try local first
if (m_localBackend.QueryAccess(destination, id, position, out version, out reason))
return true;
// else do the remote thing
if (!m_localBackend.IsLocalRegion(destination.RegionID))
return m_remoteConnector.QueryAccess(destination, id, position, out version, out reason);
return false;
}
public bool ReleaseAgent(UUID origin, UUID id, string uri)
{
// Try local first
if (m_localBackend.ReleaseAgent(origin, id, uri))
return true;
// else do the remote thing
if (!m_localBackend.IsLocalRegion(origin))
return m_remoteConnector.ReleaseAgent(origin, id, uri);
return false;
}
public bool CloseAgent(GridRegion destination, UUID id, string auth_token)
{
if (destination == null)
return false;
// Try local first
if (m_localBackend.CloseAgent(destination, id, auth_token))
return true;
// else do the remote thing
if (!m_localBackend.IsLocalRegion(destination.RegionID))
return m_remoteConnector.CloseAgent(destination, id, auth_token);
return false;
}
/**
* Object-related communications
*/
public bool CreateObject(GridRegion destination, Vector3 newPosition, ISceneObject sog, bool isLocalCall)
{
if (destination == null)
return false;
// Try local first
if (m_localBackend.CreateObject(destination, newPosition, sog, isLocalCall))
{
//m_log.Debug("[REST COMMS]: LocalBackEnd SendCreateObject succeeded");
return true;
}
// else do the remote thing
if (!m_localBackend.IsLocalRegion(destination.RegionID))
return m_remoteConnector.CreateObject(destination, newPosition, sog, isLocalCall);
return false;
}
#endregion /* IInterregionComms */
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Web;
using System.Web.Http;
using DotNetDesign.Common;
namespace DotNetDesign.Substrate.WebApi
{
public class BaseEntityRepositoryController<TEntityData, TEntity, TEntityRepository, TEntityDataImplementation> :
BaseEntityRepositoryController<TEntityData, TEntity, TEntityRepository, Guid, TEntityDataImplementation>,
IEntityRepositoryController<TEntityData, TEntity, TEntityRepository, TEntityDataImplementation>
where TEntity : class, IEntity<TEntity, TEntityData, TEntityRepository>, TEntityData
where TEntityData : class, IEntityData<TEntityData, TEntity, TEntityRepository>
where TEntityRepository : class, IEntityRepository<TEntityRepository, TEntity, TEntityData>
where TEntityDataImplementation : class, TEntityData
{
public BaseEntityRepositoryController(
Func<IPermissionAuthorizationManager<TEntity, TEntityData, TEntityRepository>> permissionAuthorizationManagerFactory,
Func<TEntityRepository> entityRepositoryFactory,
Func<TEntity> entityFactory,
string rootUri,
params string[] excludedPropertyNames)
: base(permissionAuthorizationManagerFactory, entityRepositoryFactory, entityFactory, rootUri, excludedPropertyNames)
{
}
}
public class BaseEntityRepositoryController<TEntityData, TEntity, TEntityRepository, TId, TEntityDataImplementation> :
ApiController, IEntityRepositoryController<TEntityData, TEntity, TEntityRepository, TId, TEntityDataImplementation>
where TEntity : class, IEntity<TEntity, TId, TEntityData, TEntityRepository>, TEntityData
where TEntityData : class, IEntityData<TEntityData, TEntity, TId, TEntityRepository>
where TEntityRepository : class, IEntityRepository<TEntityRepository, TEntity, TId, TEntityData>
where TEntityDataImplementation : class, TEntityData
{
/// <summary>
/// Property names to excluded when comparing changes by default.
/// </summary>
public static IEnumerable<string> DefaultExcludedPropertyNames
{
get { return new[] {"Id", "CreatedAt", "UpdatedAt", "Version", "VersionId"}; }
}
private readonly IEnumerable<string> _excludedPropertyNames;
protected readonly Func<IPermissionAuthorizationManager<TEntity, TEntityData, TId, TEntityRepository>> PermissionAuthorizationManagerFactory;
protected readonly Func<TEntityRepository> EntityRepositoryFactory;
protected readonly Func<TEntity> EntityFactory;
private readonly string _rootUri;
public BaseEntityRepositoryController(
Func<IPermissionAuthorizationManager<TEntity, TEntityData, TId, TEntityRepository>> permissionAuthorizationManagerFactory,
Func<TEntityRepository> entityRepositoryFactory,
Func<TEntity> entityFactory,
string rootUri,
params string[] excludedPropertyNames)
{
using (Logger.Assembly.Scope())
{
Guard.ArgumentNotNull(permissionAuthorizationManagerFactory, "permissionAuthorizationManagerFactory");
Guard.ArgumentNotNull(entityRepositoryFactory, "entityRepositoryFactory");
Guard.ArgumentNotNull(entityFactory, "entityFactory");
Guard.ArgumentNotNull(rootUri, "rootUri");
PermissionAuthorizationManagerFactory = permissionAuthorizationManagerFactory;
EntityRepositoryFactory = entityRepositoryFactory;
EntityFactory = entityFactory;
_rootUri = rootUri;
var excludedPropertyNamesList = new List<string>(DefaultExcludedPropertyNames);
if (excludedPropertyNames != null)
{
excludedPropertyNamesList.AddRange(excludedPropertyNames);
}
_excludedPropertyNames = excludedPropertyNamesList;
}
}
/// <summary>
/// Gets all entity data.
/// </summary>
/// <returns></returns>
public virtual IQueryable<TEntityDataImplementation> Get()
{
using(Logger.Assembly.Scope())
{
Logger.Assembly.Debug(m => m("Getting all entities of type {0}", typeof(TEntity)));
try
{
Authorize(EntityPermissions.Read);
}
catch (UnauthorizedAccessException ex)
{
Logger.Assembly.Error(m => m("Unauthorized. {0}", ex.Message), ex);
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
}
var entities = EntityRepositoryFactory().GetAll().Select(x => x.EntityData).Cast<TEntityDataImplementation>();
return entities.AsQueryable();
}
}
/// <summary>
/// Gets the entity data by id.
/// </summary>
/// <param name="id">The id.</param>
/// <returns></returns>
public virtual TEntityDataImplementation Get(TId id)
{
using (Logger.Assembly.Scope())
{
Logger.Assembly.Debug(m => m("Getting entity of type {0} by id {1}", typeof(TEntity), id));
try
{
Authorize(EntityPermissions.Read);
}
catch (UnauthorizedAccessException ex)
{
Logger.Assembly.Error(m => m("Unauthorized. {0}", ex.Message), ex);
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
}
var entity = EntityRepositoryFactory().GetById(id);
return (entity == null)
? null
: (entity.EntityData as TEntityDataImplementation);
}
}
/// <summary>
/// Gets the version.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="version">The version.</param>
/// <returns></returns>
public virtual TEntityDataImplementation Get(TId id, int version)
{
using (Logger.Assembly.Scope())
{
Logger.Assembly.Debug(m => m("Getting entity of type {0} by id {1} and version {2}", typeof(TEntity), id, version));
try
{
Authorize(EntityPermissions.Read);
}
catch (UnauthorizedAccessException ex)
{
Logger.Assembly.Error(m => m("Unauthorized. {0}", ex.Message), ex);
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
}
var entity = EntityRepositoryFactory().GetVersion(id, version);
return (entity == null)
? null
: (entity.EntityData as TEntityDataImplementation);
}
}
/// <summary>
/// Creates the specified entity data.
/// </summary>
/// <param name="entityData">The entity data.</param>
/// <returns></returns>
public virtual HttpResponseMessage Post(TEntityDataImplementation entityData)
{
using (Logger.Assembly.Scope())
{
Logger.Assembly.Debug(m => m("Adding the entity {0}", entityData));
if (entityData == null)
{
Logger.Assembly.Info("No data posted.");
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
try
{
Authorize(EntityPermissions.Insert);
}
catch (UnauthorizedAccessException ex)
{
Logger.Assembly.Error(m => m("Unauthorized. {0}", ex.Message), ex);
var unauthorizedResponse = new HttpResponseMessage(HttpStatusCode.Unauthorized);
unauthorizedResponse.Headers.Add(SuppressFormsAuthenticationRedirectModule.SuppressFormsHeaderName, "true");
throw new HttpResponseException(unauthorizedResponse);
}
var existingEntity = EntityRepositoryFactory().GetNew();
ApplyChanges(entityData, existingEntity);
TEntity savedEntity;
if (!existingEntity.Save(out savedEntity))
{
Logger.Assembly.Info("Validation failed.");
return Request.CreateResponse(HttpStatusCode.BadRequest, existingEntity);
}
Logger.Assembly.Info("Save succeeded.");
var response = Request.CreateResponse(HttpStatusCode.Created, savedEntity.EntityData);
response.Headers.Location = new Uri(Request.RequestUri, _rootUri + "/" + savedEntity.Id);
return response;
}
}
/// <summary>
/// Saves the specified entity data.
/// </summary>
/// <param name="id">The entity ID.</param>
/// <param name="entityData">The entity data.</param>
/// <returns></returns>
public virtual HttpResponseMessage Put(TId id, TEntityDataImplementation entityData)
{
using (Logger.Assembly.Scope())
{
Logger.Assembly.Debug(m => m("Saving the entity {0}", entityData));
if (entityData == null)
{
Logger.Assembly.Info("No data posted.");
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
try
{
Authorize(EntityPermissions.Update);
}
catch (UnauthorizedAccessException ex)
{
Logger.Assembly.Error(m => m("Unauthorized. {0}", ex.Message), ex);
var unauthorizedResponse = new HttpResponseMessage(HttpStatusCode.Unauthorized);
unauthorizedResponse.Headers.Add(SuppressFormsAuthenticationRedirectModule.SuppressFormsHeaderName, "true");
throw new HttpResponseException(unauthorizedResponse);
}
var existingEntity = EntityRepositoryFactory().GetById(id);
if (existingEntity == null)
{
Logger.Assembly.Info("Existing entity not found.");
return Request.CreateResponse(HttpStatusCode.NotFound);
}
ApplyChanges(entityData, existingEntity);
TEntity savedEntity;
if (!existingEntity.Save(out savedEntity))
{
Logger.Assembly.Info("Validation failed.");
return Request.CreateResponse(HttpStatusCode.BadRequest, existingEntity);
}
Logger.Assembly.Info("Save succeeded.");
var response = Request.CreateResponse(HttpStatusCode.OK, savedEntity.EntityData);
response.Headers.Location = new Uri(Request.RequestUri, _rootUri + "/" + savedEntity.Id);
return response;
}
}
/// <summary>
/// Deletes the specified id.
/// </summary>
/// <param name="id">The id.</param>
public virtual HttpResponseMessage Delete(TId id)
{
using (Logger.Assembly.Scope())
{
Logger.Assembly.Debug(m => m("Deleting the entity with ID {0}", id));
if (id.Equals(default(TId)))
{
Logger.Assembly.Info("No data posted.");
return
new HttpResponseMessage(HttpStatusCode.BadRequest);
}
try
{
Authorize(EntityPermissions.Delete);
}
catch (UnauthorizedAccessException ex)
{
Logger.Assembly.Error(m => m("Unauthorized. {0}", ex.Message), ex);
var unauthorizedResponse = new HttpResponseMessage(HttpStatusCode.Unauthorized);
unauthorizedResponse.Headers.Add(SuppressFormsAuthenticationRedirectModule.SuppressFormsHeaderName, "true");
throw new HttpResponseException(unauthorizedResponse);
}
var existingEntity = EntityRepositoryFactory().GetById(id);
if (existingEntity == null)
{
Logger.Assembly.Info("Existing entity not found.");
return
new HttpResponseMessage(HttpStatusCode.NotFound);
}
existingEntity.Delete();
return new HttpResponseMessage(HttpStatusCode.NoContent);
}
}
/// <summary>
/// Applies the changes.
/// </summary>
/// <param name="newEntityData">The new entity data.</param>
/// <param name="existingEntityData">The existing entity data.</param>
protected void ApplyChanges(TEntityData newEntityData, TEntityData existingEntityData)
{
using (Logger.Assembly.Scope())
{
foreach (var propertyInfo in typeof (TEntityData).GetProperties().Where(IsPropertyIncluded))
{
propertyInfo.SetValue(existingEntityData, propertyInfo.GetValue(newEntityData, null), null);
}
}
}
/// <summary>
/// Determines whether property is included.
/// </summary>
/// <param name="x">The x.</param>
/// <returns>
/// <c>true</c> if property is included; otherwise, <c>false</c>.
/// </returns>
protected virtual bool IsPropertyIncluded(PropertyInfo x)
{
using (Logger.Assembly.Scope())
{
Guard.ArgumentNotNull(x, "x");
return !_excludedPropertyNames.Contains(x.Name, StringComparer.InvariantCultureIgnoreCase);
}
}
/// <summary>
/// Authorizes the specified required permissions.
/// </summary>
/// <param name="requiredPermissions">The required permissions.</param>
protected virtual void Authorize(EntityPermissions requiredPermissions)
{
using(Logger.Assembly.Scope())
{
var authManager = PermissionAuthorizationManagerFactory();
authManager.Authorize(requiredPermissions);
}
}
}
}
| |
using CoreGraphics;
using CoreMotion;
using Foundation;
using System;
using System.Collections.Generic;
using System.Linq;
using Toggl.Core.UI.Helper;
using Toggl.iOS.Extensions;
using UIKit;
namespace Toggl.iOS.Views
{
[Register(nameof(SpiderOnARopeView))]
public class SpiderOnARopeView : UIView
{
private const int chainLength = 8;
private const double chainWidth = 2;
private const float spiderResistance = 0.85f;
private readonly CGColor ropeColor = ColorAssets.Spider.CGColor;
private double spiderRadius;
private UIDynamicAnimator spiderAnimator;
private UIGravityBehavior gravity;
private UISnapBehavior dragging;
private CMMotionManager motionManager;
private UIAttachmentBehavior spiderAttachment;
private UIImage spiderImage;
private UIView spiderView;
private UIView[] links;
private CGPoint anchorPoint;
public bool IsVisible { get; private set; }
public SpiderOnARopeView()
{
init();
}
public SpiderOnARopeView(IntPtr handle) : base(handle)
{
}
public override void AwakeFromNib()
{
base.AwakeFromNib();
init();
}
private void init()
{
spiderImage = UIImage.FromBundle("icJustSpider");
BackgroundColor = UIColor.Clear;
}
public override void LayoutSubviews()
{
base.LayoutSubviews();
if (IsVisible && anchorPoint.X != Center.X)
{
Show();
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
reset();
}
public override void Draw(CGRect rect)
{
base.Draw(rect);
var ctx = UIGraphics.GetCurrentContext();
if (ctx == null) return;
if (links != null && IsVisible == true)
{
var points = links.Select(links => links.Center).ToArray();
var path = createCurvedPath(anchorPoint, points);
ctx.SetStrokeColor(ropeColor);
ctx.SetLineWidth((nfloat)chainWidth);
ctx.AddPath(path);
ctx.DrawPath(CGPathDrawingMode.Stroke);
}
}
public void Show()
{
reset();
anchorPoint = new CGPoint(Center.X, 0);
spiderView = new UIImageView(spiderImage);
AddSubview(spiderView);
preparePhysics();
IsVisible = true;
}
public void Hide()
{
reset();
}
public override void TouchesBegan(NSSet touches, UIEvent evt)
{
base.TouchesBegan(touches, evt);
snapTo(touches);
}
public override void TouchesMoved(NSSet touches, UIEvent evt)
{
base.TouchesMoved(touches, evt);
snapTo(touches);
}
public override void TouchesEnded(NSSet touches, UIEvent evt)
{
base.TouchesEnded(touches, evt);
releaseSnap();
}
public override void TouchesCancelled(NSSet touches, UIEvent evt)
{
base.TouchesCancelled(touches, evt);
releaseSnap();
}
private void snapTo(NSSet touches)
{
if (spiderView == null) return;
var touch = (UITouch)touches.First();
lock (spiderAnimator)
{
if (dragging != null)
{
spiderAnimator.RemoveBehavior(dragging);
}
var position = touch.LocationInView(this);
dragging = new UISnapBehavior(spiderView, position);
spiderAnimator.RemoveBehavior(gravity);
spiderAnimator.AddBehavior(dragging);
}
}
private void releaseSnap()
{
lock (spiderAnimator)
{
spiderAnimator.RemoveBehavior(dragging);
spiderAnimator.AddBehavior(gravity);
dragging = null;
}
}
private void reset()
{
foreach (var subview in Subviews)
{
subview.RemoveFromSuperview();
}
motionManager?.Dispose();
gravity?.Dispose();
spiderAnimator?.Dispose();
spiderView?.Dispose();
spiderAnimator = null;
motionManager = null;
gravity = null;
spiderView = null;
IsVisible = false;
}
private void preparePhysics()
{
spiderRadius = Math.Sqrt(Math.Pow(spiderImage.Size.Width / 2, 2) + Math.Pow(spiderImage.Size.Height / 2, 2));
double height = (UIScreen.MainScreen.ApplicationFrame.Size.Width / 2) - 1.5 * spiderRadius;
spiderAnimator = new UIDynamicAnimator(this);
var spider = new UIDynamicItemBehavior(spiderView);
spider.Action = () => SetNeedsDisplay();
spider.Resistance = spiderResistance;
spider.AllowsRotation = true;
spiderAnimator.AddBehavior(spider);
links = createRope(height);
gravity = new UIGravityBehavior(links);
spiderAnimator.AddBehavior(gravity);
motionManager?.Dispose();
motionManager = new CMMotionManager();
motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, processAccelerometerData);
}
private UIView[] createRope(double length)
{
double chainLinkHeight = length / chainLength;
var chain = new List<UIView>();
UIView lastLink = null;
for (int i = 0; i < chainLength; i++)
{
var chainLink = createChainLink(i, chainLinkHeight, lastLink);
chain.Add(chainLink);
lastLink = chainLink;
}
spiderView.Center = new CGPoint(Center.X, -length + spiderImage.Size.Height / 2);
spiderAttachment = new UIAttachmentBehavior(lastLink, UIOffset.Zero, spiderView, new UIOffset(0, -spiderImage.Size.Height / 2));
spiderAttachment.Length = 0;
spiderAnimator.AddBehavior(spiderAttachment);
chain.Add(spiderView);
return chain.ToArray();
}
private UIView createChainLink(int n, double chainLinkHeight, UIView lastLink)
{
double y = -n * chainLinkHeight;
var chainLink = new UIView();
chainLink.BackgroundColor = UIColor.Clear;
chainLink.Frame = new CGRect(Center.X, y, chainWidth, chainLinkHeight);
AddSubview(chainLink);
var chainDynamics = new UIDynamicItemBehavior(chainLink);
spiderAnimator.AddBehavior(chainDynamics);
var attachment = lastLink == null
? new UIAttachmentBehavior(chainLink, anchorPoint)
: new UIAttachmentBehavior(chainLink, lastLink);
attachment.Length = (nfloat)chainLinkHeight;
spiderAnimator.AddBehavior(attachment);
return chainLink;
}
private CGPath createCurvedPath(CGPoint anchor, CGPoint[] points)
{
var path = new UIBezierPath();
if (points.Length > 1)
{
var previousPoint = points[0];
var startOfCurve = previousPoint;
path.MoveTo(anchor);
for (int i = 1; i < points.Length; i++)
{
var endOfCurve = points[i];
var nextPoint = i < points.Length - 1 ? points[i + 1] : points[i];
var (controlPointB, controlPointC) = calculateControlPoints(previousPoint, startOfCurve, endOfCurve, nextPoint);
path.AddCurveToPoint(endOfCurve, controlPointB, controlPointC);
previousPoint = startOfCurve;
startOfCurve = endOfCurve;
}
}
return path.CGPath;
}
private (double, double) convertXYCoordinate(double originX, double originY,
UIInterfaceOrientation orientation)
{
switch (orientation)
{
case UIInterfaceOrientation.LandscapeLeft:
return (originY, -originX);
case UIInterfaceOrientation.LandscapeRight:
return (-originY, originX);
case UIInterfaceOrientation.PortraitUpsideDown:
return (-originX, -originY);
default:
return (originX, originY);
}
}
private void processAccelerometerData(CMAccelerometerData data, NSError error)
{
if (spiderView == null) return;
var (ax, ay) = convertXYCoordinate(data.Acceleration.X, data.Acceleration.Y,
UIApplication.SharedApplication.StatusBarOrientation);
var angle = -(nfloat)Math.Atan2(ay, ax);
gravity.Angle = angle;
}
// Catmull-Rom to Cubic Bezier conversion matrix:
// | 0 1 0 0 |
// | -1/6 1 1/6 0 |
// | 0 1/6 1 -1/6 |
// | 0 0 1 0 |
private (CGPoint, CGPoint) calculateControlPoints(CGPoint a, CGPoint b, CGPoint c, CGPoint d)
=> (new CGPoint((-1.0 / 6.0 * a.X) + b.X + (1.0 / 6.0 * c.X), (-1.0 / 6.0 * a.Y) + b.Y + (1.0 / 6.0 * c.Y)),
new CGPoint((1.0 / 6.0 * b.X) + c.X + (-1.0 / 6.0 * d.X), (1.0 / 6.0 * b.Y) + c.Y + (-1.0 / 6.0 * d.Y)));
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Security;
using Microsoft.Win32;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
namespace System.IO
{
public abstract class FileSystemInfo
{
protected String FullPath; // fully qualified path of the file or directory
protected String OriginalPath; // path passed in by the user
private String _displayPath = ""; // path that can be displayed to the user
private IFileSystemObject _fileSystemObject; // backing implementation
[System.Security.SecurityCritical]
protected FileSystemInfo()
{
}
internal FileSystemInfo(IFileSystemObject fileSystemObject)
{
_fileSystemObject = fileSystemObject;
}
// Full path of the directory/file
public virtual String FullName
{
[System.Security.SecuritySafeCritical]
get
{
return FullPath;
}
}
public String Extension
{
get
{
// GetFullPathInternal would have already stripped out the terminating "." if present.
int length = FullPath.Length;
for (int i = length; --i >= 0;)
{
char ch = FullPath[i];
if (ch == '.')
return FullPath.Substring(i, length - i);
if (PathHelpers.IsDirectorySeparator(ch) || ch == Path.VolumeSeparatorChar)
break;
}
return String.Empty;
}
}
// Lazy accessor for backing implementation
internal IFileSystemObject FileSystemObject
{
get
{
if (_fileSystemObject == null)
{
_fileSystemObject = FileSystem.Current.GetFileSystemInfo(FullPath, this is DirectoryInfo);
}
return _fileSystemObject;
}
}
// For files name of the file is returned, for directories the last directory in hierarchy is returned if possible,
// otherwise the fully qualified name s returned
public abstract String Name
{
get;
}
// Whether a file/directory exists
public abstract bool Exists
{
get;
}
// Delete a file/directory
public abstract void Delete();
public DateTime CreationTime
{
get
{
// depends on the security check in get_CreationTimeUtc
return CreationTimeUtc.ToLocalTime();
}
set
{
CreationTimeUtc = value.ToUniversalTime();
}
}
public DateTime CreationTimeUtc
{
[System.Security.SecuritySafeCritical]
get
{
return FileSystemObject.CreationTime.UtcDateTime;
}
set
{
FileSystemObject.CreationTime = File.GetUtcDateTimeOffset(value);
}
}
public DateTime LastAccessTime
{
get
{
// depends on the security check in get_LastAccessTimeUtc
return LastAccessTimeUtc.ToLocalTime();
}
set
{
LastAccessTimeUtc = value.ToUniversalTime();
}
}
public DateTime LastAccessTimeUtc
{
[System.Security.SecuritySafeCritical]
get
{
return FileSystemObject.LastAccessTime.UtcDateTime;
}
set
{
FileSystemObject.LastAccessTime = File.GetUtcDateTimeOffset(value);
}
}
public DateTime LastWriteTime
{
get
{
// depends on the security check in get_LastWriteTimeUtc
return LastWriteTimeUtc.ToLocalTime();
}
set
{
LastWriteTimeUtc = value.ToUniversalTime();
}
}
public DateTime LastWriteTimeUtc
{
[System.Security.SecuritySafeCritical]
get
{
return FileSystemObject.LastWriteTime.UtcDateTime;
}
set
{
FileSystemObject.LastWriteTime = File.GetUtcDateTimeOffset(value);
}
}
public void Refresh()
{
FileSystemObject.Refresh();
}
public FileAttributes Attributes
{
[System.Security.SecuritySafeCritical]
get
{
return FileSystemObject.Attributes;
}
[System.Security.SecurityCritical] // auto-generated
set
{
FileSystemObject.Attributes = value;
}
}
internal String DisplayPath
{
get
{
return _displayPath;
}
set
{
_displayPath = value;
}
}
internal void Invalidate()
{
_fileSystemObject = null;
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using OpenHome.Net.Core;
using OpenHome.Net.ControlPoint;
namespace OpenHome.Net.ControlPoint.Proxies
{
public interface ICpProxyAvOpenhomeOrgSender1 : ICpProxy, IDisposable
{
void SyncPresentationUrl(out String aValue);
void BeginPresentationUrl(CpProxy.CallbackAsyncComplete aCallback);
void EndPresentationUrl(IntPtr aAsyncHandle, out String aValue);
void SyncMetadata(out String aValue);
void BeginMetadata(CpProxy.CallbackAsyncComplete aCallback);
void EndMetadata(IntPtr aAsyncHandle, out String aValue);
void SyncAudio(out bool aValue);
void BeginAudio(CpProxy.CallbackAsyncComplete aCallback);
void EndAudio(IntPtr aAsyncHandle, out bool aValue);
void SyncStatus(out String aValue);
void BeginStatus(CpProxy.CallbackAsyncComplete aCallback);
void EndStatus(IntPtr aAsyncHandle, out String aValue);
void SyncAttributes(out String aValue);
void BeginAttributes(CpProxy.CallbackAsyncComplete aCallback);
void EndAttributes(IntPtr aAsyncHandle, out String aValue);
void SetPropertyPresentationUrlChanged(System.Action aPresentationUrlChanged);
String PropertyPresentationUrl();
void SetPropertyMetadataChanged(System.Action aMetadataChanged);
String PropertyMetadata();
void SetPropertyAudioChanged(System.Action aAudioChanged);
bool PropertyAudio();
void SetPropertyStatusChanged(System.Action aStatusChanged);
String PropertyStatus();
void SetPropertyAttributesChanged(System.Action aAttributesChanged);
String PropertyAttributes();
}
internal class SyncPresentationUrlAvOpenhomeOrgSender1 : SyncProxyAction
{
private CpProxyAvOpenhomeOrgSender1 iService;
private String iValue;
public SyncPresentationUrlAvOpenhomeOrgSender1(CpProxyAvOpenhomeOrgSender1 aProxy)
{
iService = aProxy;
}
public String Value()
{
return iValue;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndPresentationUrl(aAsyncHandle, out iValue);
}
};
internal class SyncMetadataAvOpenhomeOrgSender1 : SyncProxyAction
{
private CpProxyAvOpenhomeOrgSender1 iService;
private String iValue;
public SyncMetadataAvOpenhomeOrgSender1(CpProxyAvOpenhomeOrgSender1 aProxy)
{
iService = aProxy;
}
public String Value()
{
return iValue;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndMetadata(aAsyncHandle, out iValue);
}
};
internal class SyncAudioAvOpenhomeOrgSender1 : SyncProxyAction
{
private CpProxyAvOpenhomeOrgSender1 iService;
private bool iValue;
public SyncAudioAvOpenhomeOrgSender1(CpProxyAvOpenhomeOrgSender1 aProxy)
{
iService = aProxy;
}
public bool Value()
{
return iValue;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndAudio(aAsyncHandle, out iValue);
}
};
internal class SyncStatusAvOpenhomeOrgSender1 : SyncProxyAction
{
private CpProxyAvOpenhomeOrgSender1 iService;
private String iValue;
public SyncStatusAvOpenhomeOrgSender1(CpProxyAvOpenhomeOrgSender1 aProxy)
{
iService = aProxy;
}
public String Value()
{
return iValue;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndStatus(aAsyncHandle, out iValue);
}
};
internal class SyncAttributesAvOpenhomeOrgSender1 : SyncProxyAction
{
private CpProxyAvOpenhomeOrgSender1 iService;
private String iValue;
public SyncAttributesAvOpenhomeOrgSender1(CpProxyAvOpenhomeOrgSender1 aProxy)
{
iService = aProxy;
}
public String Value()
{
return iValue;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndAttributes(aAsyncHandle, out iValue);
}
};
/// <summary>
/// Proxy for the av.openhome.org:Sender:1 UPnP service
/// </summary>
public class CpProxyAvOpenhomeOrgSender1 : CpProxy, IDisposable, ICpProxyAvOpenhomeOrgSender1
{
private OpenHome.Net.Core.Action iActionPresentationUrl;
private OpenHome.Net.Core.Action iActionMetadata;
private OpenHome.Net.Core.Action iActionAudio;
private OpenHome.Net.Core.Action iActionStatus;
private OpenHome.Net.Core.Action iActionAttributes;
private PropertyString iPresentationUrl;
private PropertyString iMetadata;
private PropertyBool iAudio;
private PropertyString iStatus;
private PropertyString iAttributes;
private System.Action iPresentationUrlChanged;
private System.Action iMetadataChanged;
private System.Action iAudioChanged;
private System.Action iStatusChanged;
private System.Action iAttributesChanged;
private Mutex iPropertyLock;
/// <summary>
/// Constructor
/// </summary>
/// <remarks>Use CpProxy::[Un]Subscribe() to enable/disable querying of state variable and reporting of their changes.</remarks>
/// <param name="aDevice">The device to use</param>
public CpProxyAvOpenhomeOrgSender1(CpDevice aDevice)
: base("av-openhome-org", "Sender", 1, aDevice)
{
OpenHome.Net.Core.Parameter param;
List<String> allowedValues = new List<String>();
iActionPresentationUrl = new OpenHome.Net.Core.Action("PresentationUrl");
param = new ParameterString("Value", allowedValues);
iActionPresentationUrl.AddOutputParameter(param);
iActionMetadata = new OpenHome.Net.Core.Action("Metadata");
param = new ParameterString("Value", allowedValues);
iActionMetadata.AddOutputParameter(param);
iActionAudio = new OpenHome.Net.Core.Action("Audio");
param = new ParameterBool("Value");
iActionAudio.AddOutputParameter(param);
iActionStatus = new OpenHome.Net.Core.Action("Status");
allowedValues.Add("Enabled");
allowedValues.Add("Disabled");
allowedValues.Add("Blocked");
param = new ParameterString("Value", allowedValues);
iActionStatus.AddOutputParameter(param);
allowedValues.Clear();
iActionAttributes = new OpenHome.Net.Core.Action("Attributes");
param = new ParameterString("Value", allowedValues);
iActionAttributes.AddOutputParameter(param);
iPresentationUrl = new PropertyString("PresentationUrl", PresentationUrlPropertyChanged);
AddProperty(iPresentationUrl);
iMetadata = new PropertyString("Metadata", MetadataPropertyChanged);
AddProperty(iMetadata);
iAudio = new PropertyBool("Audio", AudioPropertyChanged);
AddProperty(iAudio);
iStatus = new PropertyString("Status", StatusPropertyChanged);
AddProperty(iStatus);
iAttributes = new PropertyString("Attributes", AttributesPropertyChanged);
AddProperty(iAttributes);
iPropertyLock = new Mutex();
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aValue"></param>
public void SyncPresentationUrl(out String aValue)
{
SyncPresentationUrlAvOpenhomeOrgSender1 sync = new SyncPresentationUrlAvOpenhomeOrgSender1(this);
BeginPresentationUrl(sync.AsyncComplete());
sync.Wait();
sync.ReportError();
aValue = sync.Value();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndPresentationUrl().</remarks>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginPresentationUrl(CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionPresentationUrl, aCallback);
int outIndex = 0;
invocation.AddOutput(new ArgumentString((ParameterString)iActionPresentationUrl.OutputParameter(outIndex++)));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
/// <param name="aValue"></param>
public void EndPresentationUrl(IntPtr aAsyncHandle, out String aValue)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
uint index = 0;
aValue = Invocation.OutputString(aAsyncHandle, index++);
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aValue"></param>
public void SyncMetadata(out String aValue)
{
SyncMetadataAvOpenhomeOrgSender1 sync = new SyncMetadataAvOpenhomeOrgSender1(this);
BeginMetadata(sync.AsyncComplete());
sync.Wait();
sync.ReportError();
aValue = sync.Value();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndMetadata().</remarks>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginMetadata(CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionMetadata, aCallback);
int outIndex = 0;
invocation.AddOutput(new ArgumentString((ParameterString)iActionMetadata.OutputParameter(outIndex++)));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
/// <param name="aValue"></param>
public void EndMetadata(IntPtr aAsyncHandle, out String aValue)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
uint index = 0;
aValue = Invocation.OutputString(aAsyncHandle, index++);
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aValue"></param>
public void SyncAudio(out bool aValue)
{
SyncAudioAvOpenhomeOrgSender1 sync = new SyncAudioAvOpenhomeOrgSender1(this);
BeginAudio(sync.AsyncComplete());
sync.Wait();
sync.ReportError();
aValue = sync.Value();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndAudio().</remarks>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginAudio(CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionAudio, aCallback);
int outIndex = 0;
invocation.AddOutput(new ArgumentBool((ParameterBool)iActionAudio.OutputParameter(outIndex++)));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
/// <param name="aValue"></param>
public void EndAudio(IntPtr aAsyncHandle, out bool aValue)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
uint index = 0;
aValue = Invocation.OutputBool(aAsyncHandle, index++);
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aValue"></param>
public void SyncStatus(out String aValue)
{
SyncStatusAvOpenhomeOrgSender1 sync = new SyncStatusAvOpenhomeOrgSender1(this);
BeginStatus(sync.AsyncComplete());
sync.Wait();
sync.ReportError();
aValue = sync.Value();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndStatus().</remarks>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginStatus(CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionStatus, aCallback);
int outIndex = 0;
invocation.AddOutput(new ArgumentString((ParameterString)iActionStatus.OutputParameter(outIndex++)));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
/// <param name="aValue"></param>
public void EndStatus(IntPtr aAsyncHandle, out String aValue)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
uint index = 0;
aValue = Invocation.OutputString(aAsyncHandle, index++);
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aValue"></param>
public void SyncAttributes(out String aValue)
{
SyncAttributesAvOpenhomeOrgSender1 sync = new SyncAttributesAvOpenhomeOrgSender1(this);
BeginAttributes(sync.AsyncComplete());
sync.Wait();
sync.ReportError();
aValue = sync.Value();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndAttributes().</remarks>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginAttributes(CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionAttributes, aCallback);
int outIndex = 0;
invocation.AddOutput(new ArgumentString((ParameterString)iActionAttributes.OutputParameter(outIndex++)));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
/// <param name="aValue"></param>
public void EndAttributes(IntPtr aAsyncHandle, out String aValue)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
uint index = 0;
aValue = Invocation.OutputString(aAsyncHandle, index++);
}
/// <summary>
/// Set a delegate to be run when the PresentationUrl state variable changes.
/// </summary>
/// <remarks>Callbacks may be run in different threads but callbacks for a
/// CpProxyAvOpenhomeOrgSender1 instance will not overlap.</remarks>
/// <param name="aPresentationUrlChanged">The delegate to run when the state variable changes</param>
public void SetPropertyPresentationUrlChanged(System.Action aPresentationUrlChanged)
{
lock (iPropertyLock)
{
iPresentationUrlChanged = aPresentationUrlChanged;
}
}
private void PresentationUrlPropertyChanged()
{
lock (iPropertyLock)
{
ReportEvent(iPresentationUrlChanged);
}
}
/// <summary>
/// Set a delegate to be run when the Metadata state variable changes.
/// </summary>
/// <remarks>Callbacks may be run in different threads but callbacks for a
/// CpProxyAvOpenhomeOrgSender1 instance will not overlap.</remarks>
/// <param name="aMetadataChanged">The delegate to run when the state variable changes</param>
public void SetPropertyMetadataChanged(System.Action aMetadataChanged)
{
lock (iPropertyLock)
{
iMetadataChanged = aMetadataChanged;
}
}
private void MetadataPropertyChanged()
{
lock (iPropertyLock)
{
ReportEvent(iMetadataChanged);
}
}
/// <summary>
/// Set a delegate to be run when the Audio state variable changes.
/// </summary>
/// <remarks>Callbacks may be run in different threads but callbacks for a
/// CpProxyAvOpenhomeOrgSender1 instance will not overlap.</remarks>
/// <param name="aAudioChanged">The delegate to run when the state variable changes</param>
public void SetPropertyAudioChanged(System.Action aAudioChanged)
{
lock (iPropertyLock)
{
iAudioChanged = aAudioChanged;
}
}
private void AudioPropertyChanged()
{
lock (iPropertyLock)
{
ReportEvent(iAudioChanged);
}
}
/// <summary>
/// Set a delegate to be run when the Status state variable changes.
/// </summary>
/// <remarks>Callbacks may be run in different threads but callbacks for a
/// CpProxyAvOpenhomeOrgSender1 instance will not overlap.</remarks>
/// <param name="aStatusChanged">The delegate to run when the state variable changes</param>
public void SetPropertyStatusChanged(System.Action aStatusChanged)
{
lock (iPropertyLock)
{
iStatusChanged = aStatusChanged;
}
}
private void StatusPropertyChanged()
{
lock (iPropertyLock)
{
ReportEvent(iStatusChanged);
}
}
/// <summary>
/// Set a delegate to be run when the Attributes state variable changes.
/// </summary>
/// <remarks>Callbacks may be run in different threads but callbacks for a
/// CpProxyAvOpenhomeOrgSender1 instance will not overlap.</remarks>
/// <param name="aAttributesChanged">The delegate to run when the state variable changes</param>
public void SetPropertyAttributesChanged(System.Action aAttributesChanged)
{
lock (iPropertyLock)
{
iAttributesChanged = aAttributesChanged;
}
}
private void AttributesPropertyChanged()
{
lock (iPropertyLock)
{
ReportEvent(iAttributesChanged);
}
}
/// <summary>
/// Query the value of the PresentationUrl property.
/// </summary>
/// <remarks>This function is threadsafe and can only be called if Subscribe() has been
/// called and a first eventing callback received more recently than any call
/// to Unsubscribe().</remarks>
/// <returns>Value of the PresentationUrl property</returns>
public String PropertyPresentationUrl()
{
PropertyReadLock();
String val;
try
{
val = iPresentationUrl.Value();
}
finally
{
PropertyReadUnlock();
}
return val;
}
/// <summary>
/// Query the value of the Metadata property.
/// </summary>
/// <remarks>This function is threadsafe and can only be called if Subscribe() has been
/// called and a first eventing callback received more recently than any call
/// to Unsubscribe().</remarks>
/// <returns>Value of the Metadata property</returns>
public String PropertyMetadata()
{
PropertyReadLock();
String val;
try
{
val = iMetadata.Value();
}
finally
{
PropertyReadUnlock();
}
return val;
}
/// <summary>
/// Query the value of the Audio property.
/// </summary>
/// <remarks>This function is threadsafe and can only be called if Subscribe() has been
/// called and a first eventing callback received more recently than any call
/// to Unsubscribe().</remarks>
/// <returns>Value of the Audio property</returns>
public bool PropertyAudio()
{
PropertyReadLock();
bool val;
try
{
val = iAudio.Value();
}
finally
{
PropertyReadUnlock();
}
return val;
}
/// <summary>
/// Query the value of the Status property.
/// </summary>
/// <remarks>This function is threadsafe and can only be called if Subscribe() has been
/// called and a first eventing callback received more recently than any call
/// to Unsubscribe().</remarks>
/// <returns>Value of the Status property</returns>
public String PropertyStatus()
{
PropertyReadLock();
String val;
try
{
val = iStatus.Value();
}
finally
{
PropertyReadUnlock();
}
return val;
}
/// <summary>
/// Query the value of the Attributes property.
/// </summary>
/// <remarks>This function is threadsafe and can only be called if Subscribe() has been
/// called and a first eventing callback received more recently than any call
/// to Unsubscribe().</remarks>
/// <returns>Value of the Attributes property</returns>
public String PropertyAttributes()
{
PropertyReadLock();
String val;
try
{
val = iAttributes.Value();
}
finally
{
PropertyReadUnlock();
}
return val;
}
/// <summary>
/// Must be called for each class instance. Must be called before Core.Library.Close().
/// </summary>
public void Dispose()
{
lock (this)
{
if (iHandle == IntPtr.Zero)
return;
DisposeProxy();
iHandle = IntPtr.Zero;
}
iActionPresentationUrl.Dispose();
iActionMetadata.Dispose();
iActionAudio.Dispose();
iActionStatus.Dispose();
iActionAttributes.Dispose();
iPresentationUrl.Dispose();
iMetadata.Dispose();
iAudio.Dispose();
iStatus.Dispose();
iAttributes.Dispose();
}
}
}
| |
#region Licence...
/*
The MIT License (MIT)
Copyright (c) 2014 Oleg Shilo
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.Linq;
using Microsoft.Deployment.WindowsInstaller;
using IO = System.IO;
using System.Diagnostics;
namespace WixSharp
{
/// <summary>
/// Collection of a 'utility' routines.
/// </summary>
public static class Utils
{
/// <summary>
/// Combines two path strings.
/// <para>
/// It is a fix for unexpected behavior of System.IO.Path.Combine: Path.Combine(@"C:\Test", @"\Docs\readme.txt") return @"\Docs\readme.txt";
/// </para>
/// </summary>
/// <param name="path1">The path1.</param>
/// <param name="path2">The path2.</param>
/// <returns></returns>
public static string PathCombine(string path1, string path2)
{
var p1 = (path1 ?? "").ExpandEnvVars();
var p2 = (path2 ?? "").ExpandEnvVars();
if (p2.Length == 0)
{
return p1;
}
else if (p2.Length == 1 && p2[0] == IO.Path.DirectorySeparatorChar)
{
return p1;
}
else if (p2[0] == IO.Path.DirectorySeparatorChar)
{
if (p2[0] != p2[1])
return IO.Path.Combine(p1, p2.Substring(1));
}
return IO.Path.Combine(p1, p2);
}
internal static string MakeRelative(this string filePath, string referencePath)
{
//1 - 'Uri.MakeRelativeUri' doesn't work without *.config file
//2 - Substring doesn't work for paths containing ..\..\
char dirSeparator = IO.Path.DirectorySeparatorChar;
Func<string, string[]> split = path => IO.Path.GetFullPath(path).Trim(dirSeparator).Split(dirSeparator);
string[] absParts = split(filePath);
string[] relParts = split(referencePath);
int commonElementsLength = 0;
do
{
if (string.Compare(absParts[commonElementsLength], relParts[commonElementsLength], true) != 0)
break;
}
while (++commonElementsLength < Math.Min(absParts.Length, relParts.Length));
if (commonElementsLength == 0)
//throw new ArgumentException("The two paths don't have common root.");
return IO.Path.GetFullPath(filePath);
var result = relParts.Skip(commonElementsLength)
.Select(x => "..")
.Concat(absParts.Skip(commonElementsLength))
.ToArray();
return string.Join(dirSeparator.ToString(), result);
}
internal static string[] AllConstStringValues<T>()
{
var fields = typeof(T).GetFields()
.Where(f => f.IsStatic && f.IsPublic && f.IsLiteral && f.FieldType == typeof(string))
.Select(f => f.GetValue(null) as string)
.ToArray();
return fields;
}
internal static string GetTempDirectory()
{
string tempDir = IO.Path.GetTempFileName();
if (IO.File.Exists(tempDir))
IO.File.Exists(tempDir);
if (!IO.Directory.Exists(tempDir))
IO.Directory.CreateDirectory(tempDir);
return tempDir;
}
internal static string OriginalAssemblyFile(string file)
{
//need to do it in a separate domain as we do not want to lock the assembly
return (string)ExecuteInTempDomain<AsmReflector>(asm =>
{
return asm.OriginalAssemblyFile(file);
});
}
internal static void ExecuteInTempDomain<T>(Action<T> action) where T : MarshalByRefObject
{
ExecuteInTempDomain<T>(asm =>
{
action(asm);
return null;
});
}
internal static object ExecuteInTempDomain<T>(Func<T, object> action) where T : MarshalByRefObject
{
var domain = AppDomain.CurrentDomain.Clone();
AppDomain.CurrentDomain.AssemblyResolve += Domain_AssemblyResolve;
domain.AssemblyResolve += Domain_AssemblyResolve;
try
{
var obj = domain.CreateInstanceFromAndUnwrap<T>();
var result = action(obj);
return result;
}
finally
{
domain.AssemblyResolve -= Domain_AssemblyResolve;
AppDomain.CurrentDomain.AssemblyResolve -= Domain_AssemblyResolve;
domain.Unload();
}
}
static System.Reflection.Assembly Domain_AssemblyResolve(object sender, ResolveEventArgs args)
{
if (Compiler.AssemblyResolve != null)
return Compiler.AssemblyResolve(sender, args);
else
return DefaultDomain_AssemblyResolve(sender, args);
}
static System.Reflection.Assembly DefaultDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
//args.Name -> "mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
string asmName = args.Name.Split(',').First() + ".dll";
string wixSharpAsmLocation = IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string potentialAsm = IO.Path.Combine(wixSharpAsmLocation, asmName);
if (IO.File.Exists(potentialAsm))
try
{
return System.Reflection.Assembly.LoadFrom(potentialAsm);
}
catch { }
return null;
}
internal static void Unload(this AppDomain domain)
{
AppDomain.Unload(domain);
}
internal static T CreateInstanceFromAndUnwrap<T>(this AppDomain domain)
{
return (T)domain.CreateInstanceFromAndUnwrap(typeof(T).Assembly.Location, typeof(T).ToString());
}
internal static AppDomain Clone(this AppDomain domain, string name = null)
{
//return AppDomain.CreateDomain(name ?? Guid.NewGuid().ToString(), null, new AppDomainSetup());
var setup = new AppDomainSetup();
setup.ApplicationBase = IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
setup.ShadowCopyFiles = "true";
setup.ShadowCopyDirectories = setup.ApplicationBase;
setup.PrivateBinPath = AppDomain.CurrentDomain.BaseDirectory;
return AppDomain.CreateDomain(name ?? Guid.NewGuid().ToString(), null, setup);
}
internal static void EnsureFileDir(string file)
{
var dir = IO.Path.GetDirectoryName(file);
if (!IO.Directory.Exists(dir))
IO.Directory.CreateDirectory(dir);
}
/// <summary>
/// Gets the program files directory.
/// </summary>
/// <value>
/// The program files directory.
/// </value>
internal static string ProgramFilesDirectory
{
get
{
string programFilesDir = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
if ("".GetType().Assembly.Location.Contains("Framework64"))
programFilesDir += " (x86)"; //for x64 systems
return programFilesDir;
}
}
/// <summary>
/// Returns the hash code for the instance of a string. It uses deterministic hash-code generation algorithm,
/// which produces the same result on x86 and x64 OSs (ebject.GetHashCode doesn't).
/// </summary>
/// <param name="s">The string.</param>
/// <returns></returns>
public static int GetHashCode32(this string s)
{
char[] chars = s.ToCharArray();
int lastCharInd = chars.Length - 1;
int num1 = 0x15051505;
int num2 = num1;
int ind = 0;
while (ind <= lastCharInd)
{
char ch = chars[ind];
char nextCh = ++ind > lastCharInd ? '\0' : chars[ind];
num1 = (((num1 << 5) + num1) + (num1 >> 0x1b)) ^ (nextCh << 16 | ch);
if (++ind > lastCharInd)
break;
ch = chars[ind];
nextCh = ++ind > lastCharInd ? '\0' : chars[ind++];
num2 = (((num2 << 5) + num2) + (num2 >> 0x1b)) ^ (nextCh << 16 | ch);
}
return num1 + num2 * 0x5d588b65;
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using Epi;
using Epi.Data;
using Epi.Data.Services;
using Epi.Windows;
using Epi.Fields;
using Epi.Windows.Dialogs;
using System.Text.RegularExpressions;
namespace Epi.Windows.MakeView.Dialogs
{
public partial class CommentLegalDialog : LegalValuesDialog
{
#region Public Interface
#region Constructors
/// <summary>
/// Default Constructor - Design Mode only
/// </summary>
[Obsolete("Use of default constructor not allowed", true)]
public CommentLegalDialog()
{
InitializeComponent();
}
/// <summary>
/// Constructor for the Comment Legal dialog
/// </summary>
/// <param name="field">The field associated with this comment legal</param>
/// <param name="frm">The main form</param>
/// <param name="name">The name of the field</param>
/// <param name="currentPage">The current page</param>
public CommentLegalDialog(TableBasedDropDownField field, MainForm frm, string name, Page currentPage)
: base(field, frm, name, currentPage)
{
InitializeComponent();
fieldName = name;
page = currentPage;
//dgCodes.CaptionText = "Comment Legal values for: " + name;
}
/// <summary>
/// Constructor for the Comment Legal dialog
/// </summary>
/// <param name="column">The column associated with this comment legal grid column</param>
/// <param name="frm">The main form</param>
/// <param name="name">The name of the column</param>
/// <param name="currentPage">The current page</param>
public CommentLegalDialog(TableBasedDropDownColumn column, MainForm frm, string name, Page currentPage)
: base(column, frm, name, currentPage)
{
InitializeComponent();
fieldName = name;
page = currentPage;
//dgCodes.CaptionText = "Comment Legal values for: " + name;
}
/// <summary>
/// Constructor for the Comment Legal dialog
/// </summary>
/// <param name="field">The comment legal field</param>
/// <param name="currentPage">The current page</param>
public CommentLegalDialog(RenderableField field, Page currentPage)
: base(field, currentPage)
{
InitializeComponent();
page = currentPage;
DDLFieldOfCommentLegal ddlField = (DDLFieldOfCommentLegal)field;
codeTable = ddlField.GetSourceData();
//if (dgCodes.AllowSorting)
//{
// ddlField.ShouldSort = true;
//}
//else
//{
// ddlField.ShouldSort = false;
//}
dgCodes.DataSource = codeTable;
sourceTableName = codeTable.TableName;
textColumnName = fieldName;
//dgCodes.AllowSorting = true;
}
#endregion Constructors
#region Public Enums and Constants
#endregion Public Enums and Constants
#region Public Properties
/// <summary>
/// Returns the source's table name
/// </summary>
public new string SourceTableName
{
get
{
return (sourceTableName);
}
}
/// <summary>
/// Returns the text column name
/// </summary>
public new string TextColumnName
{
get
{
return (textColumnName);
}
}
#endregion Public Properties
#region Public Methods
#endregion Public Methods
#endregion Public Interface
#region Protected Interface
#region Protected Properties
#endregion Protected Properties
#region Protected Methods
/// <summary>
/// Show the field selected for a Use Existing codetable
/// </summary>
/// <param name="tableName">Table name</param>
protected override void ShowFieldSelection(string tableName)
{
string separator = " - ";
if (!tableName.Contains(separator))
{
FieldSelectionDialog fieldSelection = new FieldSelectionDialog(MainForm, page.GetProject(), tableName);
DialogResult result = fieldSelection.ShowDialog();
if (result == DialogResult.OK)
{
textColumnName = fieldSelection.ColumnName;
sourceTableName = tableName;
codeTable = GetProject().GetTableData(tableName, textColumnName);
fieldSelection.Close();
DisplayData();
isExclusiveTable = true;
}
}
else if(DdlField!=null) //using Form table as Datasource
{
string[] view_page = sourceTableName.Replace(separator, "^").Split('^');
string viewName = view_page[0].ToString();
string pageName = view_page[1].ToString();
string filterExpression = string.Empty;
string tableName1 = null;
View targetView = page.GetProject().Metadata.GetViewByFullName(viewName);
if (targetView != null)
{
DataTable targetPages = page.GetProject().Metadata.GetPagesForView(targetView.Id);
DataView dataView = new DataView(targetPages);
filterExpression = string.Format("Name = '{0}'", pageName);
DataRow[] pageArray = targetPages.Select(filterExpression);
if (pageArray.Length > 0)
{
int pageId = (int)pageArray[0]["PageId"];
tableName1 = viewName + pageId;
}
}
if (page.GetProject().CollectedData.TableExists(tableName1))
{
FieldSelectionDialog fieldSelection = new FieldSelectionDialog(MainForm, page.GetProject(), tableName1);
DialogResult result = fieldSelection.ShowDialog();
if (result == DialogResult.OK)
{
textColumnName = fieldSelection.ColumnName;
codeTable = page.GetProject().GetTableData(tableName1, textColumnName, string.Empty);
fieldSelection.Close();
DisplayData();
isExclusiveTable = true;
}
}
}
else
{
FieldSelectionDialog fieldSelection = new FieldSelectionDialog(MainForm, page.GetProject(), tableName);
DialogResult result = fieldSelection.ShowDialog();
if (result == DialogResult.OK)
{
textColumnName = fieldSelection.ColumnName;
sourceTableName = tableName;
codeTable = page.GetProject().GetTableData(tableName, textColumnName, string.Empty);
fieldSelection.Close();
DisplayData();
isExclusiveTable = true;
}
}
}
#endregion Protected Methods
#region Protected Events
/// <summary>
/// Event from when the Create New button is clicked
/// </summary>
/// <param name="sender">Object that fired the event</param>
/// <param name="e">.NET supplied event parameters</param>
protected override void btnCreate_Click(object sender, System.EventArgs e)
{
CreateCommentLegal();
creationMode = CreationMode.CreateNew;
btnCreate.Enabled = false;
btnFromExisting.Enabled = false;
btnUseExisting.Enabled = false;
dgCodes.Visible = true;
btnOK.Enabled = true;
}
/// <summary>
/// Event from clicking the OK button
/// </summary>
/// <param name="sender">Object that fired the event</param>
/// <param name="e">.NET supplied event parameters</param>
protected override void btnOK_Click(object sender, System.EventArgs e)
{
if ((DataTable)dgCodes.DataSource != null)
{
((DataTable)dgCodes.DataSource).AcceptChanges();
}
SaveShouldSort();
if (CheckForHyphens())
{
SaveCodeTableToField();
this.DialogResult = DialogResult.OK;
this.Hide();
}
}
#endregion Protected Events
#endregion Protected Interface
#region Private Members
#region Private Enums and Constants
#endregion Private Enums and Constants
#region Private Properties
private string fieldName = string.Empty;
private DataTable codeTable;
private Page page;
private int oldCurrentRow;
#endregion Private Properties
#region Private Methods
/// <summary>
/// Set ShouldSort based on if the checkbox is checked
/// </summary>
private void SaveShouldSort()
{
if (DdlField != null)
{
DdlField.ShouldSort = !cbxSort.Checked;
}
}
/// <summary>
/// Verify hyphens exist for Comment Legal field
/// </summary>
private bool CheckForHyphens()
{
bool isValidated;
Regex commentLegalCheck = new Regex(@"^[0-9a-zA-Z:. _]+(\s)*(-){1}");
codeTable = (DataTable)dgCodes.DataSource;
if (codeTable != null && string.IsNullOrEmpty(textColumnName))
{
textColumnName = codeTable.Columns[0].ColumnName;
}
if (codeTable != null)
{
isValidated = true;
foreach (DataRow row in codeTable.Rows)
{
#region Validation
if (textColumnName == null)
{
throw new ArgumentNullException("textColumnName");
}
#endregion Input validation
if (((string.IsNullOrEmpty(textColumnName)) || !(commentLegalCheck.IsMatch(row[textColumnName].ToString()))))
{
string msg = SharedStrings.SEPARATE_COMMENT_LEGAL_WITH_HYPEN + ": \n" + row[textColumnName].ToString();
MsgBox.ShowError(msg);
isValidated = false;
}
if (isValidated == false)
{
break;
}
}
}
else
{
isValidated = true;
}
return isValidated;
}
/// <summary>
/// Get the current project
/// </summary>
/// <returns>Current project</returns>
private Project GetProject()
{
return page.GetProject();
}
/// <summary>
/// Set up comment legal
/// </summary>
private void CreateCommentLegal()
{
dgCodes.Visible = true;
btnOK.Visible = true;
DataTable bindingTable = page.GetProject().CodeData.GetCodeTableNamesForProject(page.GetProject());
DataView dataView = bindingTable.DefaultView;
//if (dgCodes.AllowSorting)
{
dataView.Sort = GetDisplayString(page);
}
string cleanedCodeTableName = CleanCodeTableName(fieldName, dataView);
page.GetProject().CreateCodeTable(cleanedCodeTableName, fieldName.ToLowerInvariant());
codeTable = page.GetProject().GetTableData(cleanedCodeTableName);
codeTable.TableName = cleanedCodeTableName;
dgCodes.DataSource = codeTable;
sourceTableName = codeTable.TableName;
textColumnName = fieldName;
dgCodes.Focus(); // Fix to focus the cursor in the data grid when 'Create New' is pressed. Really, this needs to be combined with the Legal Value dialog.
}
//Show the data
private void DisplayData()
{
if (codeTable != null)
{
dgCodes.Visible = true;
btnOK.Enabled = true;
btnOK.Visible = true;
btnCreate.Enabled = false;
btnFromExisting.Enabled = false;
btnUseExisting.Enabled = false;
btnDelete.Enabled = false;
btnDelete.Visible = true;
codeTable.TableName = sourceTableName;
dgCodes.DataSource = codeTable;
//dgCodes.CaptionText = sourceTableName;
if (DdlField != null) cbxSort.Checked = !DdlField.ShouldSort;
}
}
#endregion Private Methods
#region Private Events
/// <summary>
/// Handles the Load event from Comment Legal
/// </summary>
/// <param name="sender">Object that fired the event</param>
/// <param name="e">.NET supplied event parameters</param>
private void CommentLegal_Load(object sender, System.EventArgs e)
{
DisplayData();
dgCodes.Focus();
}
#endregion Private Events
#endregion Private Members
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A book.
/// </summary>
public class Book_Core : TypeCore, ICreativeWork
{
public Book_Core()
{
this._TypeId = 41;
this._Id = "Book";
this._Schema_Org_Url = "http://schema.org/Book";
string label = "";
GetLabel(out label, "Book", typeof(Book_Core));
this._Label = label;
this._Ancestors = new int[]{266,78};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{78};
this._Properties = new int[]{67,108,143,229,0,2,10,12,18,20,24,26,21,50,51,54,57,58,59,61,62,64,70,72,81,97,100,110,115,116,126,138,151,178,179,180,199,211,219,230,231,33,34,107,118,147};
}
/// <summary>
/// The subject matter of the content.
/// </summary>
private About_Core about;
public About_Core About
{
get
{
return about;
}
set
{
about = value;
SetPropertyInstance(about);
}
}
/// <summary>
/// Specifies the Person that is legally accountable for the CreativeWork.
/// </summary>
private AccountablePerson_Core accountablePerson;
public AccountablePerson_Core AccountablePerson
{
get
{
return accountablePerson;
}
set
{
accountablePerson = value;
SetPropertyInstance(accountablePerson);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// A secondary title of the CreativeWork.
/// </summary>
private AlternativeHeadline_Core alternativeHeadline;
public AlternativeHeadline_Core AlternativeHeadline
{
get
{
return alternativeHeadline;
}
set
{
alternativeHeadline = value;
SetPropertyInstance(alternativeHeadline);
}
}
/// <summary>
/// The media objects that encode this creative work. This property is a synonym for encodings.
/// </summary>
private AssociatedMedia_Core associatedMedia;
public AssociatedMedia_Core AssociatedMedia
{
get
{
return associatedMedia;
}
set
{
associatedMedia = value;
SetPropertyInstance(associatedMedia);
}
}
/// <summary>
/// An embedded audio object.
/// </summary>
private Audio_Core audio;
public Audio_Core Audio
{
get
{
return audio;
}
set
{
audio = value;
SetPropertyInstance(audio);
}
}
/// <summary>
/// The author of this content. Please note that author is special in that HTML 5 provides a special mechanism for indicating authorship via the rel tag. That is equivalent to this and may be used interchangabely.
/// </summary>
private Author_Core author;
public Author_Core Author
{
get
{
return author;
}
set
{
author = value;
SetPropertyInstance(author);
}
}
/// <summary>
/// Awards won by this person or for this creative work.
/// </summary>
private Awards_Core awards;
public Awards_Core Awards
{
get
{
return awards;
}
set
{
awards = value;
SetPropertyInstance(awards);
}
}
/// <summary>
/// The edition of the book.
/// </summary>
private BookEdition_Core bookEdition;
public BookEdition_Core BookEdition
{
get
{
return bookEdition;
}
set
{
bookEdition = value;
SetPropertyInstance(bookEdition);
}
}
/// <summary>
/// The format of the book.
/// </summary>
private BookFormat_Core bookFormat;
public BookFormat_Core BookFormat
{
get
{
return bookFormat;
}
set
{
bookFormat = value;
SetPropertyInstance(bookFormat);
}
}
/// <summary>
/// Comments, typically from users, on this CreativeWork.
/// </summary>
private Comment_Core comment;
public Comment_Core Comment
{
get
{
return comment;
}
set
{
comment = value;
SetPropertyInstance(comment);
}
}
/// <summary>
/// The location of the content.
/// </summary>
private ContentLocation_Core contentLocation;
public ContentLocation_Core ContentLocation
{
get
{
return contentLocation;
}
set
{
contentLocation = value;
SetPropertyInstance(contentLocation);
}
}
/// <summary>
/// Official rating of a piece of content\u2014for example,'MPAA PG-13'.
/// </summary>
private ContentRating_Core contentRating;
public ContentRating_Core ContentRating
{
get
{
return contentRating;
}
set
{
contentRating = value;
SetPropertyInstance(contentRating);
}
}
/// <summary>
/// A secondary contributor to the CreativeWork.
/// </summary>
private Contributor_Core contributor;
public Contributor_Core Contributor
{
get
{
return contributor;
}
set
{
contributor = value;
SetPropertyInstance(contributor);
}
}
/// <summary>
/// The party holding the legal copyright to the CreativeWork.
/// </summary>
private CopyrightHolder_Core copyrightHolder;
public CopyrightHolder_Core CopyrightHolder
{
get
{
return copyrightHolder;
}
set
{
copyrightHolder = value;
SetPropertyInstance(copyrightHolder);
}
}
/// <summary>
/// The year during which the claimed copyright for the CreativeWork was first asserted.
/// </summary>
private CopyrightYear_Core copyrightYear;
public CopyrightYear_Core CopyrightYear
{
get
{
return copyrightYear;
}
set
{
copyrightYear = value;
SetPropertyInstance(copyrightYear);
}
}
/// <summary>
/// The creator/author of this CreativeWork or UserComments. This is the same as the Author property for CreativeWork.
/// </summary>
private Creator_Core creator;
public Creator_Core Creator
{
get
{
return creator;
}
set
{
creator = value;
SetPropertyInstance(creator);
}
}
/// <summary>
/// The date on which the CreativeWork was created.
/// </summary>
private DateCreated_Core dateCreated;
public DateCreated_Core DateCreated
{
get
{
return dateCreated;
}
set
{
dateCreated = value;
SetPropertyInstance(dateCreated);
}
}
/// <summary>
/// The date on which the CreativeWork was most recently modified.
/// </summary>
private DateModified_Core dateModified;
public DateModified_Core DateModified
{
get
{
return dateModified;
}
set
{
dateModified = value;
SetPropertyInstance(dateModified);
}
}
/// <summary>
/// Date of first broadcast/publication.
/// </summary>
private DatePublished_Core datePublished;
public DatePublished_Core DatePublished
{
get
{
return datePublished;
}
set
{
datePublished = value;
SetPropertyInstance(datePublished);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// A link to the page containing the comments of the CreativeWork.
/// </summary>
private DiscussionURL_Core discussionURL;
public DiscussionURL_Core DiscussionURL
{
get
{
return discussionURL;
}
set
{
discussionURL = value;
SetPropertyInstance(discussionURL);
}
}
/// <summary>
/// Specifies the Person who edited the CreativeWork.
/// </summary>
private Editor_Core editor;
public Editor_Core Editor
{
get
{
return editor;
}
set
{
editor = value;
SetPropertyInstance(editor);
}
}
/// <summary>
/// The media objects that encode this creative work
/// </summary>
private Encodings_Core encodings;
public Encodings_Core Encodings
{
get
{
return encodings;
}
set
{
encodings = value;
SetPropertyInstance(encodings);
}
}
/// <summary>
/// Genre of the creative work
/// </summary>
private Genre_Core genre;
public Genre_Core Genre
{
get
{
return genre;
}
set
{
genre = value;
SetPropertyInstance(genre);
}
}
/// <summary>
/// Headline of the article
/// </summary>
private Headline_Core headline;
public Headline_Core Headline
{
get
{
return headline;
}
set
{
headline = value;
SetPropertyInstance(headline);
}
}
/// <summary>
/// The illustrator of the book.
/// </summary>
private Illustrator_Core illustrator;
public Illustrator_Core Illustrator
{
get
{
return illustrator;
}
set
{
illustrator = value;
SetPropertyInstance(illustrator);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// The language of the content. please use one of the language codes from the <a href=\http://tools.ietf.org/html/bcp47\>IETF BCP 47 standard.</a>
/// </summary>
private InLanguage_Core inLanguage;
public InLanguage_Core InLanguage
{
get
{
return inLanguage;
}
set
{
inLanguage = value;
SetPropertyInstance(inLanguage);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The ISBN of the book.
/// </summary>
private ISBN_Core iSBN;
public ISBN_Core ISBN
{
get
{
return iSBN;
}
set
{
iSBN = value;
SetPropertyInstance(iSBN);
}
}
/// <summary>
/// Indicates whether this content is family friendly.
/// </summary>
private IsFamilyFriendly_Core isFamilyFriendly;
public IsFamilyFriendly_Core IsFamilyFriendly
{
get
{
return isFamilyFriendly;
}
set
{
isFamilyFriendly = value;
SetPropertyInstance(isFamilyFriendly);
}
}
/// <summary>
/// The keywords/tags used to describe this content.
/// </summary>
private Keywords_Core keywords;
public Keywords_Core Keywords
{
get
{
return keywords;
}
set
{
keywords = value;
SetPropertyInstance(keywords);
}
}
/// <summary>
/// Indicates that the CreativeWork contains a reference to, but is not necessarily about a concept.
/// </summary>
private Mentions_Core mentions;
public Mentions_Core Mentions
{
get
{
return mentions;
}
set
{
mentions = value;
SetPropertyInstance(mentions);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The number of pages in the book.
/// </summary>
private NumberOfPages_Core numberOfPages;
public NumberOfPages_Core NumberOfPages
{
get
{
return numberOfPages;
}
set
{
numberOfPages = value;
SetPropertyInstance(numberOfPages);
}
}
/// <summary>
/// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event.
/// </summary>
private Offers_Core offers;
public Offers_Core Offers
{
get
{
return offers;
}
set
{
offers = value;
SetPropertyInstance(offers);
}
}
/// <summary>
/// Specifies the Person or Organization that distributed the CreativeWork.
/// </summary>
private Provider_Core provider;
public Provider_Core Provider
{
get
{
return provider;
}
set
{
provider = value;
SetPropertyInstance(provider);
}
}
/// <summary>
/// The publisher of the creative work.
/// </summary>
private Publisher_Core publisher;
public Publisher_Core Publisher
{
get
{
return publisher;
}
set
{
publisher = value;
SetPropertyInstance(publisher);
}
}
/// <summary>
/// Link to page describing the editorial principles of the organization primarily responsible for the creation of the CreativeWork.
/// </summary>
private PublishingPrinciples_Core publishingPrinciples;
public PublishingPrinciples_Core PublishingPrinciples
{
get
{
return publishingPrinciples;
}
set
{
publishingPrinciples = value;
SetPropertyInstance(publishingPrinciples);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The Organization on whose behalf the creator was working.
/// </summary>
private SourceOrganization_Core sourceOrganization;
public SourceOrganization_Core SourceOrganization
{
get
{
return sourceOrganization;
}
set
{
sourceOrganization = value;
SetPropertyInstance(sourceOrganization);
}
}
/// <summary>
/// A thumbnail image relevant to the Thing.
/// </summary>
private ThumbnailURL_Core thumbnailURL;
public ThumbnailURL_Core ThumbnailURL
{
get
{
return thumbnailURL;
}
set
{
thumbnailURL = value;
SetPropertyInstance(thumbnailURL);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
/// <summary>
/// The version of the CreativeWork embodied by a specified resource.
/// </summary>
private Version_Core version;
public Version_Core Version
{
get
{
return version;
}
set
{
version = value;
SetPropertyInstance(version);
}
}
/// <summary>
/// An embedded video object.
/// </summary>
private Video_Core video;
public Video_Core Video
{
get
{
return video;
}
set
{
video = value;
SetPropertyInstance(video);
}
}
}
}
| |
//
// Copyright 2014 Matthew Ducker
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Obscur.Core.Cryptography.Ciphers.Stream;
namespace ObscurCore.Tests.Cryptography.Ciphers.Stream
{
internal class Hc256 : StreamCipherTestBase
{
private static readonly string DiscretePlaintext = "00000000000000000000000000000000" +
"00000000000000000000000000000000" +
"00000000000000000000000000000000" +
"00000000000000000000000000000000";
public Hc256 () : base(StreamCipher.Hc256)
{
// Data from ESTREAM verified test vectors
// http://www.ecrypt.eu.org/stream/svn/viewcvs.cgi/ecrypt/trunk/submissions/hc-256/verified.test-vectors?rev=149&view=markup
DiscreteVectorTests.Add (new DiscreteVectorTestCase (
"Set 2, vector# 0",
"00000000000000000000000000000000",
"00000000000000000000000000000000",
DiscretePlaintext,
"5B078985D8F6F30D42C5C02FA6B67951" +
"53F06534801F89F24E74248B720B4818" +
"CD9227ECEBCF4DBF8DBF6977E4AE14FA" +
"E8504C7BC8A9F3EA6C0106F5327E6981"));
DiscreteVectorTests.Add (new DiscreteVectorTestCase (
"Set 2, vector# 9",
"09090909090909090909090909090909",
"00000000000000000000000000000000",
DiscretePlaintext,
"F5C2926651AEED9AF1A9C2F04C03D081" +
"2145B56AEA46EB283A25A4C9E3D8BEB4" +
"821B418F06F2B9DCDF1A85AB8C02CD14" +
"62E1BBCAEC9AB0E99AA6AFF918BA627C"));
DiscreteVectorTests.Add (new DiscreteVectorTestCase (
"Set 2, vector# 135",
"87878787878787878787878787878787",
"00000000000000000000000000000000",
DiscretePlaintext,
"CEC0C3852E3B98233EBCB975C10B1191" +
"3C69F2275EB97A1402EDF16C6FBE19BE" +
"79D65360445BCB63676E6553B609A065" +
"0155C3B22DD1975AC0F3F65063A2E16E"));
DiscreteVectorTests.Add (new DiscreteVectorTestCase (
"Set 6, vector# 1",
"0558ABFE51A4F74A9DF04396E93C8FE2" +
"3588DB2E81D4277ACD2073C6196CBF12",
"167DE44BB21980E74EB51C83EA51B81F" +
"86ED54BB2289F057BE258CF35AC1288F",
DiscretePlaintext,
"C44B5262F2EAD9C018213127686DB742" +
"A72D3F2D61D18F0F4E7DE5B4F7ADABE0" +
"7E0C82033B139F02BAACB4E2F2D0BE30" +
"110C3A8A2B621523756692877C905DD0"));
DiscreteVectorTests.Add (new DiscreteVectorTestCase (
"Set 6, vector# 2",
"0A5DB00356A9FC4FA2F5489BEE4194E7" +
"3A8DE03386D92C7FD22578CB1E71C417",
"1F86ED54BB2289F057BE258CF35AC128" +
"8FF65DC42B92F960C72E95FC63CA3198",
DiscretePlaintext,
"9D13AA06122F4F03AE60D507701F1ED0" +
"63D7530FF35EE76CAEDCBFB01D8A239E" +
"FA4A44B272DE9B4092E2AD56E87C3A60" +
"89F5A074D1F6E5B8FC6FABEE0C936F06"));
DiscreteVectorTests.Add (new DiscreteVectorTestCase (
"Set 6, vector# 3",
"0F62B5085BAE0154A7FA4DA0F34699EC" +
"3F92E5388BDE3184D72A7DD02376C91C",
"288FF65DC42B92F960C72E95FC63CA31" +
"98FF66CD349B0269D0379E056CD33AA1",
DiscretePlaintext,
"C8632038DA61679C4685288B37D3E232" +
"7BC2D28C266B041FE0CA0D3CFEED8FD5" +
"753259BAB757168F85EA96ADABD823CA" +
"4684E918423E091565713FEDDE2CCFE0"));
SegmentedVectorTests.Add (new SegmentedVectorTestCase (
"[K128-IV128] Set 6, vector# 0",
"0053A6F94C9FF24598EB3E91E4378ADD",
"0D74DB42A91077DE45AC137AE148AF16",
new TestVectorSegment[] {
new TestVectorSegment (
"stream[0..63]",
0,
"425A5E6F68EC055F38383ADC5CA9C048" +
"D6455C56A5ACED215E22665185E497EB" +
"3A2F5C0D45057169965EA37FE19F5D83" +
"C95C4BEE11E8FA89545A38DD9D18AD6D"
),
new TestVectorSegment (
"stream[65472..65535]",
65472,
"EFFA27F50B0B4C4AB3C7855CD5DD9EFD" +
"B61783161678C9728B9032C2CB09A0B2" +
"D2578C53BF3C3E67D382BC89D824D63B" +
"20E62F414E4AC36472A16F4992DF4496"
),
new TestVectorSegment (
"stream[65536..65599]",
65536,
"0111EEC218892B446FDFDBA9D0C734DF" +
"C209D35FA86C1BEAC0D266E5DC4B3243" +
"68B4263BA7A3517805D1501B36450FFA" +
"1544812EBC0B9DDED93F5D45C4D83FFC"
),
new TestVectorSegment (
"stream[131008..131071]",
131008,
"D966650E1A27DF3CB71B1E64CD3E7EEC" +
"2D3EEEA2953E2FC5571B4380EA3BAEB5" +
"3F014B4EE071A426E4A518E1AF335BD3" +
"76309236760E0DF6184B3E34BF861458"
)
}
));
SegmentedVectorTests.Add (new SegmentedVectorTestCase (
"[K128-IV256] Set 6, vector# 0",
"0053A6F94C9FF24598EB3E91E4378ADD",
"0D74DB42A91077DE45AC137AE148AF16" +
"7DE44BB21980E74EB51C83EA51B81F86",
new TestVectorSegment[] {
new TestVectorSegment (
"stream[0..63]",
0,
"914AEBA9E4BE90FD07AA58B6E2536B59" +
"0DD63BA810A2B96BAD5DAC1818722BEC" +
"61725C75B9E6194F57D3D2BBFE795E73" +
"90405CA97249262093234239E35ED9E4"
),
new TestVectorSegment (
"stream[65472..65535]",
65472,
"346C1A7D71DBB8FB69EA78F07D60A9A7" +
"20D0ED544149AF102C12678D4AE0C5DF" +
"E3521B7344F91977799085008EA00432" +
"772C0B4ABEC1DB2C47608F9A29CC76EA"
),
new TestVectorSegment (
"stream[65536..65599]",
65536,
"6F3B93E808687BE8E37A635E15B13052" +
"60ED65488A59125D84726219AEE62087" +
"47C6672C585759BA60BFD7F55AB975D4" +
"B61596A506F8763F715F27A36082DB51"
),
new TestVectorSegment (
"stream[131008..131071]",
131008,
"C64CAD1578C28BF19F11B14F3D33C681" +
"A85D28A4B2D547652A7179C31127C306" +
"DC04BE79BC1DA0279C69F9418311E57C" +
"0F13D9E993008796EA10607A63BDC772"
)
}
));
SegmentedVectorTests.Add (new SegmentedVectorTestCase (
"[K256-IV256] Set 6, vector# 0",
"0053A6F94C9FF24598EB3E91E4378ADD" +
"3083D6297CCF2275C81B6EC11467BA0D",
"0D74DB42A91077DE45AC137AE148AF16" +
"7DE44BB21980E74EB51C83EA51B81F86",
new TestVectorSegment[] {
new TestVectorSegment (
"stream[0..63]",
0,
"23D9E70A45EB0127884D66D9F6F23C01" +
"D1F88AFD629270127247256C1FFF91E9" +
"1A797BD98ADD23AE15BEE6EEA3CEFDBF" +
"A3ED6D22D9C4F459DB10C40CDF4F4DFF"
),
new TestVectorSegment (
"stream[65472..65535]",
65472,
"CFF0058C45807C1F4300D118FDFC3B21" +
"370936B39391791C92A821E1C8E8F248" +
"BBBF378679468218FF5F6560B79A6015" +
"82B81315DC19D8583263958B068BEA48"
),
new TestVectorSegment (
"stream[65536..65599]",
65536,
"871A09D393D8888EBEA453F518BD300D" +
"8233E906A31631D29A4A1834E268C3E4" +
"F65F4F65B1B9E55606BDF28A571CA4E7" +
"59BDE4718E1E13731663F5CAF1CB0F1E"
),
new TestVectorSegment (
"stream[131008..131071]",
131008,
"15360407DA7B389DF28C08B2221F5E0D" +
"96B34839325795A70A3F65D9CBB3848D" +
"8C0793A53E8C4D71D8B53B2923A90B37" +
"FE412A4485F0CC741E65743C6F1ECB4A"
)
}
));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Logic
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for WorkflowVersionsOperations.
/// </summary>
public static partial class WorkflowVersionsOperationsExtensions
{
/// <summary>
/// Gets a list of workflow versions.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='workflowName'>
/// The workflow name.
/// </param>
/// <param name='top'>
/// The number of items to be included in the result.
/// </param>
public static IPage<WorkflowVersion> List(this IWorkflowVersionsOperations operations, string resourceGroupName, string workflowName, int? top = default(int?))
{
return operations.ListAsync(resourceGroupName, workflowName, top).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of workflow versions.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='workflowName'>
/// The workflow name.
/// </param>
/// <param name='top'>
/// The number of items to be included in the result.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<WorkflowVersion>> ListAsync(this IWorkflowVersionsOperations operations, string resourceGroupName, string workflowName, int? top = default(int?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, workflowName, top, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a workflow version.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='workflowName'>
/// The workflow name.
/// </param>
/// <param name='versionId'>
/// The workflow versionId.
/// </param>
public static WorkflowVersion Get(this IWorkflowVersionsOperations operations, string resourceGroupName, string workflowName, string versionId)
{
return operations.GetAsync(resourceGroupName, workflowName, versionId).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a workflow version.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='workflowName'>
/// The workflow name.
/// </param>
/// <param name='versionId'>
/// The workflow versionId.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<WorkflowVersion> GetAsync(this IWorkflowVersionsOperations operations, string resourceGroupName, string workflowName, string versionId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, workflowName, versionId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the callback URL for a trigger of a workflow version.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='workflowName'>
/// The workflow name.
/// </param>
/// <param name='versionId'>
/// The workflow versionId.
/// </param>
/// <param name='triggerName'>
/// The workflow trigger name.
/// </param>
/// <param name='parameters'>
/// The callback URL parameters.
/// </param>
public static WorkflowTriggerCallbackUrl ListCallbackUrl(this IWorkflowVersionsOperations operations, string resourceGroupName, string workflowName, string versionId, string triggerName, GetCallbackUrlParameters parameters = default(GetCallbackUrlParameters))
{
return operations.ListCallbackUrlAsync(resourceGroupName, workflowName, versionId, triggerName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the callback URL for a trigger of a workflow version.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='workflowName'>
/// The workflow name.
/// </param>
/// <param name='versionId'>
/// The workflow versionId.
/// </param>
/// <param name='triggerName'>
/// The workflow trigger name.
/// </param>
/// <param name='parameters'>
/// The callback URL parameters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<WorkflowTriggerCallbackUrl> ListCallbackUrlAsync(this IWorkflowVersionsOperations operations, string resourceGroupName, string workflowName, string versionId, string triggerName, GetCallbackUrlParameters parameters = default(GetCallbackUrlParameters), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListCallbackUrlWithHttpMessagesAsync(resourceGroupName, workflowName, versionId, triggerName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a list of workflow versions.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<WorkflowVersion> ListNext(this IWorkflowVersionsOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of workflow versions.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<WorkflowVersion>> ListNextAsync(this IWorkflowVersionsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors;
using OpenSim.Services.Connectors.SimianGrid;
using OpenMetaverse;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGInventoryBroker")]
public class HGInventoryBroker : ISharedRegionModule, IInventoryService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private static bool m_Enabled = false;
private static IInventoryService m_LocalGridInventoryService;
private Dictionary<string, IInventoryService> m_connectors = new Dictionary<string, IInventoryService>();
// A cache of userIDs --> ServiceURLs, for HGBroker only
protected Dictionary<UUID, string> m_InventoryURLs = new Dictionary<UUID,string>();
private List<Scene> m_Scenes = new List<Scene>();
private InventoryCache m_Cache = new InventoryCache();
protected IUserManagement m_UserManagement;
protected IUserManagement UserManagementModule
{
get
{
if (m_UserManagement == null)
{
m_UserManagement = m_Scenes[0].RequestModuleInterface<IUserManagement>();
if (m_UserManagement == null)
m_log.ErrorFormat(
"[HG INVENTORY CONNECTOR]: Could not retrieve IUserManagement module from {0}",
m_Scenes[0].RegionInfo.RegionName);
}
return m_UserManagement;
}
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "HGInventoryBroker"; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("InventoryServices", "");
if (name == Name)
{
IConfig inventoryConfig = source.Configs["InventoryService"];
if (inventoryConfig == null)
{
m_log.Error("[HG INVENTORY CONNECTOR]: InventoryService missing from OpenSim.ini");
return;
}
string localDll = inventoryConfig.GetString("LocalGridInventoryService",
String.Empty);
//string HGDll = inventoryConfig.GetString("HypergridInventoryService",
// String.Empty);
if (localDll == String.Empty)
{
m_log.Error("[HG INVENTORY CONNECTOR]: No LocalGridInventoryService named in section InventoryService");
//return;
throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's");
}
Object[] args = new Object[] { source };
m_LocalGridInventoryService =
ServerUtils.LoadPlugin<IInventoryService>(localDll,
args);
if (m_LocalGridInventoryService == null)
{
m_log.Error("[HG INVENTORY CONNECTOR]: Can't load local inventory service");
return;
}
m_Enabled = true;
m_log.InfoFormat("[HG INVENTORY CONNECTOR]: HG inventory broker enabled with inner connector of type {0}", m_LocalGridInventoryService.GetType());
}
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
m_Scenes.Add(scene);
scene.RegisterModuleInterface<IInventoryService>(this);
if (m_Scenes.Count == 1)
{
// FIXME: The local connector needs the scene to extract the UserManager. However, it's not enabled so
// we can't just add the region. But this approach is super-messy.
if (m_LocalGridInventoryService is RemoteXInventoryServicesConnector)
{
m_log.DebugFormat(
"[HG INVENTORY BROKER]: Manually setting scene in RemoteXInventoryServicesConnector to {0}",
scene.RegionInfo.RegionName);
((RemoteXInventoryServicesConnector)m_LocalGridInventoryService).Scene = scene;
}
else if (m_LocalGridInventoryService is LocalInventoryServicesConnector)
{
m_log.DebugFormat(
"[HG INVENTORY BROKER]: Manually setting scene in LocalInventoryServicesConnector to {0}",
scene.RegionInfo.RegionName);
((LocalInventoryServicesConnector)m_LocalGridInventoryService).Scene = scene;
}
scene.EventManager.OnClientClosed += OnClientClosed;
}
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
m_Scenes.Remove(scene);
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
m_log.InfoFormat("[HG INVENTORY CONNECTOR]: Enabled HG inventory for region {0}", scene.RegionInfo.RegionName);
}
#region URL Cache
void OnClientClosed(UUID clientID, Scene scene)
{
if (m_InventoryURLs.ContainsKey(clientID)) // if it's in cache
{
ScenePresence sp = null;
foreach (Scene s in m_Scenes)
{
s.TryGetScenePresence(clientID, out sp);
if ((sp != null) && !sp.IsChildAgent && (s != scene))
{
m_log.DebugFormat("[INVENTORY CACHE]: OnClientClosed in {0}, but user {1} still in sim. Keeping inventoryURL in cache",
scene.RegionInfo.RegionName, clientID);
return;
}
}
DropInventoryServiceURL(clientID);
}
}
/// <summary>
/// Gets the user's inventory URL from its serviceURLs, if the user is foreign,
/// and sticks it in the cache
/// </summary>
/// <param name="userID"></param>
private void CacheInventoryServiceURL(UUID userID)
{
if (UserManagementModule != null && !UserManagementModule.IsLocalGridUser(userID))
{
// The user is not local; let's cache its service URL
string inventoryURL = string.Empty;
ScenePresence sp = null;
foreach (Scene scene in m_Scenes)
{
scene.TryGetScenePresence(userID, out sp);
if (sp != null)
{
AgentCircuitData aCircuit = scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
if (aCircuit.ServiceURLs.ContainsKey("InventoryServerURI"))
{
inventoryURL = aCircuit.ServiceURLs["InventoryServerURI"].ToString();
if (inventoryURL != null && inventoryURL != string.Empty)
{
inventoryURL = inventoryURL.Trim(new char[] { '/' });
m_InventoryURLs.Add(userID, inventoryURL);
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Added {0} to the cache of inventory URLs", inventoryURL);
return;
}
}
// else
// {
// m_log.DebugFormat("[HG INVENTORY CONNECTOR]: User {0} does not have InventoryServerURI. OH NOES!", userID);
// return;
// }
}
}
if (sp == null)
{
inventoryURL = UserManagementModule.GetUserServerURL(userID, "InventoryServerURI");
if (inventoryURL != null && inventoryURL != string.Empty)
{
inventoryURL = inventoryURL.Trim(new char[] { '/' });
m_InventoryURLs.Add(userID, inventoryURL);
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Added {0} to the cache of inventory URLs", inventoryURL);
}
}
}
}
private void DropInventoryServiceURL(UUID userID)
{
lock (m_InventoryURLs)
if (m_InventoryURLs.ContainsKey(userID))
{
string url = m_InventoryURLs[userID];
m_InventoryURLs.Remove(userID);
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Removed {0} from the cache of inventory URLs", url);
}
}
public string GetInventoryServiceURL(UUID userID)
{
if (m_InventoryURLs.ContainsKey(userID))
return m_InventoryURLs[userID];
CacheInventoryServiceURL(userID);
if (m_InventoryURLs.ContainsKey(userID))
return m_InventoryURLs[userID];
return null; //it means that the methods should forward to local grid's inventory
}
#endregion
#region IInventoryService
public bool CreateUserInventory(UUID userID)
{
return m_LocalGridInventoryService.CreateUserInventory(userID);
}
public List<InventoryFolderBase> GetInventorySkeleton(UUID userID)
{
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetInventorySkeleton(userID);
IInventoryService connector = GetConnector(invURL);
return connector.GetInventorySkeleton(userID);
}
public InventoryCollection GetUserInventory(UUID userID)
{
string invURL = GetInventoryServiceURL(userID);
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetUserInventory for {0} {1}", userID, invURL);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetUserInventory(userID);
InventoryCollection c = m_Cache.GetUserInventory(userID);
if (c != null)
return c;
IInventoryService connector = GetConnector(invURL);
c = connector.GetUserInventory(userID);
m_Cache.Cache(userID, c);
return c;
}
public void GetUserInventory(UUID userID, InventoryReceiptCallback callback)
{
}
public InventoryFolderBase GetRootFolder(UUID userID)
{
//m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetRootFolder for {0}", userID);
InventoryFolderBase root = m_Cache.GetRootFolder(userID);
if (root != null)
return root;
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetRootFolder(userID);
IInventoryService connector = GetConnector(invURL);
root = connector.GetRootFolder(userID);
m_Cache.Cache(userID, root);
return root;
}
public InventoryFolderBase GetFolderForType(UUID userID, AssetType type)
{
//m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetFolderForType {0} type {1}", userID, type);
InventoryFolderBase f = m_Cache.GetFolderForType(userID, type);
if (f != null)
return f;
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetFolderForType(userID, type);
IInventoryService connector = GetConnector(invURL);
f = connector.GetFolderForType(userID, type);
m_Cache.Cache(userID, type, f);
return f;
}
public InventoryCollection GetFolderContent(UUID userID, UUID folderID)
{
//m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderContent " + folderID);
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetFolderContent(userID, folderID);
InventoryCollection c = m_Cache.GetFolderContent(userID, folderID);
if (c != null)
{
m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderContent found content in cache " + folderID);
return c;
}
IInventoryService connector = GetConnector(invURL);
return connector.GetFolderContent(userID, folderID);
}
public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID)
{
//m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderItems " + folderID);
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetFolderItems(userID, folderID);
List<InventoryItemBase> items = m_Cache.GetFolderItems(userID, folderID);
if (items != null)
{
m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderItems found items in cache " + folderID);
return items;
}
IInventoryService connector = GetConnector(invURL);
return connector.GetFolderItems(userID, folderID);
}
public bool AddFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: AddFolder " + folder.ID);
string invURL = GetInventoryServiceURL(folder.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.AddFolder(folder);
IInventoryService connector = GetConnector(invURL);
return connector.AddFolder(folder);
}
public bool UpdateFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: UpdateFolder " + folder.ID);
string invURL = GetInventoryServiceURL(folder.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.UpdateFolder(folder);
IInventoryService connector = GetConnector(invURL);
return connector.UpdateFolder(folder);
}
public bool DeleteFolders(UUID ownerID, List<UUID> folderIDs)
{
if (folderIDs == null)
return false;
if (folderIDs.Count == 0)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: DeleteFolders for " + ownerID);
string invURL = GetInventoryServiceURL(ownerID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.DeleteFolders(ownerID, folderIDs);
IInventoryService connector = GetConnector(invURL);
return connector.DeleteFolders(ownerID, folderIDs);
}
public bool MoveFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: MoveFolder for " + folder.Owner);
string invURL = GetInventoryServiceURL(folder.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.MoveFolder(folder);
IInventoryService connector = GetConnector(invURL);
return connector.MoveFolder(folder);
}
public bool PurgeFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: PurgeFolder for " + folder.Owner);
string invURL = GetInventoryServiceURL(folder.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.PurgeFolder(folder);
IInventoryService connector = GetConnector(invURL);
return connector.PurgeFolder(folder);
}
public bool AddItem(InventoryItemBase item)
{
if (item == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: AddItem " + item.ID);
string invURL = GetInventoryServiceURL(item.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.AddItem(item);
IInventoryService connector = GetConnector(invURL);
return connector.AddItem(item);
}
public bool UpdateItem(InventoryItemBase item)
{
if (item == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: UpdateItem " + item.ID);
string invURL = GetInventoryServiceURL(item.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.UpdateItem(item);
IInventoryService connector = GetConnector(invURL);
return connector.UpdateItem(item);
}
public bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
{
if (items == null)
return false;
if (items.Count == 0)
return true;
//m_log.Debug("[HG INVENTORY CONNECTOR]: MoveItems for " + ownerID);
string invURL = GetInventoryServiceURL(ownerID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.MoveItems(ownerID, items);
IInventoryService connector = GetConnector(invURL);
return connector.MoveItems(ownerID, items);
}
public bool DeleteItems(UUID ownerID, List<UUID> itemIDs)
{
//m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Delete {0} items for user {1}", itemIDs.Count, ownerID);
if (itemIDs == null)
return false;
if (itemIDs.Count == 0)
return true;
string invURL = GetInventoryServiceURL(ownerID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.DeleteItems(ownerID, itemIDs);
IInventoryService connector = GetConnector(invURL);
return connector.DeleteItems(ownerID, itemIDs);
}
public InventoryItemBase GetItem(InventoryItemBase item)
{
if (item == null)
return null;
//m_log.Debug("[HG INVENTORY CONNECTOR]: GetItem " + item.ID);
string invURL = GetInventoryServiceURL(item.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetItem(item);
IInventoryService connector = GetConnector(invURL);
return connector.GetItem(item);
}
public InventoryFolderBase GetFolder(InventoryFolderBase folder)
{
if (folder == null)
return null;
//m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolder " + folder.ID);
string invURL = GetInventoryServiceURL(folder.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetFolder(folder);
IInventoryService connector = GetConnector(invURL);
return connector.GetFolder(folder);
}
public bool HasInventoryForUser(UUID userID)
{
return false;
}
public List<InventoryItemBase> GetActiveGestures(UUID userId)
{
return new List<InventoryItemBase>();
}
public int GetAssetPermissions(UUID userID, UUID assetID)
{
//m_log.Debug("[HG INVENTORY CONNECTOR]: GetAssetPermissions " + assetID);
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetAssetPermissions(userID, assetID);
IInventoryService connector = GetConnector(invURL);
return connector.GetAssetPermissions(userID, assetID);
}
#endregion
private IInventoryService GetConnector(string url)
{
IInventoryService connector = null;
lock (m_connectors)
{
if (m_connectors.ContainsKey(url))
{
connector = m_connectors[url];
}
else
{
// Still not as flexible as I would like this to be,
// but good enough for now
string connectorType = new HeloServicesConnector(url).Helo();
m_log.DebugFormat("[HG INVENTORY SERVICE]: HELO returned {0}", connectorType);
if (connectorType == "opensim-simian")
{
connector = new SimianInventoryServiceConnector(url);
}
else
{
RemoteXInventoryServicesConnector rxisc = new RemoteXInventoryServicesConnector(url);
rxisc.Scene = m_Scenes[0];
connector = rxisc;
}
m_connectors.Add(url, connector);
}
}
return connector;
}
}
}
| |
using System;
using System.Linq;
using System.Security.Claims;
using System.Web;
using Fluid;
using Fluid.Values;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using OrchardCore.Admin;
using OrchardCore.Data.Migration;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.Handlers;
using OrchardCore.DisplayManagement.Theming;
using OrchardCore.Environment.Commands;
using OrchardCore.Environment.Shell;
using OrchardCore.Environment.Shell.Configuration;
using OrchardCore.Environment.Shell.Scope;
using OrchardCore.Liquid;
using OrchardCore.Modules;
using OrchardCore.Mvc.Core.Utilities;
using OrchardCore.Navigation;
using OrchardCore.Recipes.Services;
using OrchardCore.Security;
using OrchardCore.Security.Permissions;
using OrchardCore.Settings;
using OrchardCore.Settings.Deployment;
using OrchardCore.Setup.Events;
using OrchardCore.Users.Commands;
using OrchardCore.Users.Controllers;
using OrchardCore.Users.Drivers;
using OrchardCore.Users.Handlers;
using OrchardCore.Users.Indexes;
using OrchardCore.Users.Liquid;
using OrchardCore.Users.Models;
using OrchardCore.Users.Services;
using OrchardCore.Users.ViewModels;
using YesSql.Filters.Query;
using YesSql.Indexes;
namespace OrchardCore.Users
{
public class Startup : StartupBase
{
private readonly AdminOptions _adminOptions;
private readonly string _tenantName;
public Startup(IOptions<AdminOptions> adminOptions, ShellSettings shellSettings)
{
_adminOptions = adminOptions.Value;
_tenantName = shellSettings.Name;
}
public override void Configure(IApplicationBuilder builder, IEndpointRouteBuilder routes, IServiceProvider serviceProvider)
{
var userOptions = serviceProvider.GetRequiredService<IOptions<UserOptions>>().Value;
var accountControllerName = typeof(AccountController).ControllerName();
routes.MapAreaControllerRoute(
name: "Login",
areaName: "OrchardCore.Users",
pattern: userOptions.LoginPath,
defaults: new { controller = accountControllerName, action = nameof(AccountController.Login) }
);
routes.MapAreaControllerRoute(
name: "ChangePassword",
areaName: "OrchardCore.Users",
pattern: userOptions.ChangePasswordUrl,
defaults: new { controller = accountControllerName, action = nameof(AccountController.ChangePassword) }
);
routes.MapAreaControllerRoute(
name: "UsersLogOff",
areaName: "OrchardCore.Users",
pattern: userOptions.LogoffPath,
defaults: new { controller = accountControllerName, action = nameof(AccountController.LogOff) }
);
routes.MapAreaControllerRoute(
name: "ExternalLogins",
areaName: "OrchardCore.Users",
pattern: userOptions.ExternalLoginsUrl,
defaults: new { controller = accountControllerName, action = nameof(AccountController.ExternalLogins) }
);
var adminControllerName = typeof(AdminController).ControllerName();
routes.MapAreaControllerRoute(
name: "UsersIndex",
areaName: "OrchardCore.Users",
pattern: _adminOptions.AdminUrlPrefix + "/Users/Index",
defaults: new { controller = adminControllerName, action = nameof(AdminController.Index) }
);
routes.MapAreaControllerRoute(
name: "UsersCreate",
areaName: "OrchardCore.Users",
pattern: _adminOptions.AdminUrlPrefix + "/Users/Create",
defaults: new { controller = adminControllerName, action = nameof(AdminController.Create) }
);
routes.MapAreaControllerRoute(
name: "UsersDelete",
areaName: "OrchardCore.Users",
pattern: _adminOptions.AdminUrlPrefix + "/Users/Delete/{id}",
defaults: new { controller = adminControllerName, action = nameof(AdminController.Delete) }
);
routes.MapAreaControllerRoute(
name: "UsersEdit",
areaName: "OrchardCore.Users",
pattern: _adminOptions.AdminUrlPrefix + "/Users/Edit/{id?}",
defaults: new { controller = adminControllerName, action = nameof(AdminController.Edit) }
);
routes.MapAreaControllerRoute(
name: "UsersEditPassword",
areaName: "OrchardCore.Users",
pattern: _adminOptions.AdminUrlPrefix + "/Users/EditPassword/{id}",
defaults: new { controller = adminControllerName, action = nameof(AdminController.EditPassword) }
);
routes.MapAreaControllerRoute(
name: "UsersUnlock",
areaName: "OrchardCore.Users",
pattern: _adminOptions.AdminUrlPrefix + "/Users/Unlock/{id}",
defaults: new { controller = adminControllerName, action = nameof(AdminController.Unlock) }
);
builder.UseAuthorization();
}
public override void ConfigureServices(IServiceCollection services)
{
services.Configure<UserOptions>(userOptions =>
{
var configuration = ShellScope.Services.GetRequiredService<IShellConfiguration>();
configuration.GetSection("OrchardCore_Users").Bind(userOptions);
});
// Add ILookupNormalizer as Singleton because it is needed by UserIndexProvider
services.TryAddSingleton<ILookupNormalizer, UpperInvariantLookupNormalizer>();
// Adds the default token providers used to generate tokens for reset passwords, change email
// and change telephone number operations, and for two factor authentication token generation.
services.AddIdentity<IUser, IRole>(options =>
{
// Specify OrchardCore User requirements.
// A user name cannot include an @ symbol, i.e. be an email address
// An email address must be provided, and be unique.
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._+";
options.User.RequireUniqueEmail = true;
})
.AddDefaultTokenProviders();
// Configure the authentication options to use the application cookie scheme as the default sign-out handler.
// This is required for security modules like the OpenID module (that uses SignOutAsync()) to work correctly.
services.AddAuthentication(options => options.DefaultSignOutScheme = IdentityConstants.ApplicationScheme);
services.TryAddScoped<UserStore>();
services.TryAddScoped<IUserStore<IUser>>(sp => sp.GetRequiredService<UserStore>());
services.TryAddScoped<IUserRoleStore<IUser>>(sp => sp.GetRequiredService<UserStore>());
services.TryAddScoped<IUserPasswordStore<IUser>>(sp => sp.GetRequiredService<UserStore>());
services.TryAddScoped<IUserEmailStore<IUser>>(sp => sp.GetRequiredService<UserStore>());
services.TryAddScoped<IUserSecurityStampStore<IUser>>(sp => sp.GetRequiredService<UserStore>());
services.TryAddScoped<IUserLoginStore<IUser>>(sp => sp.GetRequiredService<UserStore>());
services.TryAddScoped<IUserClaimStore<IUser>>(sp => sp.GetRequiredService<UserStore>());
services.TryAddScoped<IUserAuthenticationTokenStore<IUser>>(sp => sp.GetRequiredService<UserStore>());
services.ConfigureApplicationCookie(options =>
{
var userOptions = ShellScope.Services.GetRequiredService<IOptions<UserOptions>>();
options.Cookie.Name = "orchauth_" + HttpUtility.UrlEncode(_tenantName);
// Don't set the cookie builder 'Path' so that it uses the 'IAuthenticationFeature' value
// set by the pipeline and comming from the request 'PathBase' which already ends with the
// tenant prefix but may also start by a path related e.g to a virtual folder.
options.LoginPath = "/" + userOptions.Value.LoginPath;
options.LogoutPath = "/" + userOptions.Value.LogoffPath;
options.AccessDeniedPath = "/Error/403";
});
services.AddSingleton<IIndexProvider, UserIndexProvider>();
services.AddSingleton<IIndexProvider, UserByRoleNameIndexProvider>();
services.AddSingleton<IIndexProvider, UserByLoginInfoIndexProvider>();
services.AddSingleton<IIndexProvider, UserByClaimIndexProvider>();
services.AddScoped<IDataMigration, Migrations>();
services.AddScoped<IUserService, UserService>();
services.AddScoped<IUserClaimsPrincipalFactory<IUser>, DefaultUserClaimsPrincipalProviderFactory>();
services.AddScoped<IUserClaimsProvider, EmailClaimsProvider>();
services.AddSingleton<IUserIdGenerator, DefaultUserIdGenerator>();
services.AddScoped<IAuthorizationHandler, UserAuthorizationHandler>();
services.AddScoped<IMembershipService, MembershipService>();
services.AddScoped<ISetupEventHandler, SetupEventHandler>();
services.AddScoped<ICommandHandler, UserCommands>();
services.AddScoped<IRoleRemovedEventHandler, UserRoleRemovedEventHandler>();
services.AddScoped<IExternalLoginEventHandler, ScriptExternalLoginEventHandler>();
services.AddScoped<IPermissionProvider, Permissions>();
services.AddScoped<INavigationProvider, AdminMenu>();
services.AddScoped<IDisplayDriver<ISite>, LoginSettingsDisplayDriver>();
services.AddScoped<IDisplayManager<User>, DisplayManager<User>>();
services.AddScoped<IDisplayDriver<User>, UserDisplayDriver>();
services.AddScoped<IDisplayDriver<User>, UserRoleDisplayDriver>();
services.AddScoped<IDisplayDriver<User>, UserInformationDisplayDriver>();
services.AddScoped<IDisplayDriver<User>, UserButtonsDisplayDriver>();
services.AddScoped<IThemeSelector, UsersThemeSelector>();
services.AddScoped<IRecipeEnvironmentProvider, RecipeEnvironmentSuperUserProvider>();
services.AddScoped<IUsersAdminListQueryService, DefaultUsersAdminListQueryService>();
services.AddScoped<IDisplayManager<UserIndexOptions>, DisplayManager<UserIndexOptions>>();
services.AddScoped<IDisplayDriver<UserIndexOptions>, UserOptionsDisplayDriver>();
services.AddSingleton<IUsersAdminListFilterParser>(sp =>
{
var filterProviders = sp.GetServices<IUsersAdminListFilterProvider>();
var builder = new QueryEngineBuilder<User>();
foreach (var provider in filterProviders)
{
provider.Build(builder);
}
var parser = builder.Build();
return new DefaultUsersAdminListFilterParser(parser);
});
services.AddTransient<IUsersAdminListFilterProvider, DefaultUsersAdminListFilterProvider>();
}
}
[RequireFeatures("OrchardCore.Liquid")]
public class LiquidStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.Configure<TemplateOptions>(o =>
{
o.Filters.AddFilter("has_claim", UserFilters.HasClaim);
o.Filters.AddFilter("user_id", UserFilters.UserId);
o.MemberAccessStrategy.Register<ClaimsPrincipal>();
o.MemberAccessStrategy.Register<ClaimsIdentity>();
o.Scope.SetValue("User", new ObjectValue(new LiquidUserAccessor()));
o.MemberAccessStrategy.Register<LiquidUserAccessor, FluidValue>((obj, name, ctx) =>
{
var user = ((LiquidTemplateContext)ctx).Services.GetRequiredService<IHttpContextAccessor>().HttpContext?.User;
if (user != null)
{
return name switch
{
nameof(ClaimsPrincipal.Identity) => new ObjectValue(user.Identity),
_ => NilValue.Instance
};
}
return NilValue.Instance;
});
o.MemberAccessStrategy.Register<User, FluidValue>((user, name, context) =>
{
return name switch
{
nameof(User.UserId) => new StringValue(user.UserId),
nameof(User.UserName) => new StringValue(user.UserName),
nameof(User.NormalizedUserName) => new StringValue(user.NormalizedUserName),
nameof(User.Email) => new StringValue(user.Email),
nameof(User.NormalizedEmail) => new StringValue(user.NormalizedEmail),
nameof(User.EmailConfirmed) => user.EmailConfirmed ? BooleanValue.True : BooleanValue.False,
nameof(User.IsEnabled) => user.IsEnabled ? BooleanValue.True : BooleanValue.False,
nameof(User.RoleNames) => new ArrayValue(user.RoleNames.Select(x => new StringValue(x))),
nameof(User.Properties) => new ObjectValue(user.Properties),
_ => NilValue.Instance
};
});
})
.AddLiquidFilter<UsersByIdFilter>("users_by_id")
.AddLiquidFilter<HasPermissionFilter>("has_permission")
.AddLiquidFilter<IsInRoleFilter>("is_in_role")
.AddLiquidFilter<UserEmailFilter>("user_email");
}
}
[RequireFeatures("OrchardCore.Deployment")]
public class LoginDeploymentStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddSiteSettingsPropertyDeploymentStep<LoginSettings, LoginDeploymentStartup>(S => S["Login settings"], S => S["Exports the Login settings."]);
}
}
[Feature("OrchardCore.Users.ChangeEmail")]
public class ChangeEmailStartup : StartupBase
{
private const string ChangeEmailPath = "ChangeEmail";
private const string ChangeEmailConfirmationPath = "ChangeEmailConfirmation";
public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider)
{
routes.MapAreaControllerRoute(
name: "ChangeEmail",
areaName: "OrchardCore.Users",
pattern: ChangeEmailPath,
defaults: new { controller = "ChangeEmail", action = "Index" }
);
routes.MapAreaControllerRoute(
name: "ChangeEmailConfirmation",
areaName: "OrchardCore.Users",
pattern: ChangeEmailConfirmationPath,
defaults: new { controller = "ChangeEmail", action = "ChangeEmailConfirmation" }
);
}
public override void ConfigureServices(IServiceCollection services)
{
services.Configure<TemplateOptions>(o =>
{
o.MemberAccessStrategy.Register<ChangeEmailViewModel>();
});
services.AddScoped<INavigationProvider, ChangeEmailAdminMenu>();
services.AddScoped<IDisplayDriver<ISite>, ChangeEmailSettingsDisplayDriver>();
}
}
[Feature("OrchardCore.Users.ChangeEmail")]
[RequireFeatures("OrchardCore.Deployment")]
public class ChangeEmailDeploymentStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddSiteSettingsPropertyDeploymentStep<ChangeEmailDeploymentStartup, ChangeEmailDeploymentStartup>(S => S["Change Email settings"], S => S["Exports the Change Email settings."]);
}
}
[Feature("OrchardCore.Users.Registration")]
public class RegistrationStartup : StartupBase
{
private const string RegisterPath = nameof(RegistrationController.Register);
private const string ConfirmEmailSent = nameof(RegistrationController.ConfirmEmailSent);
private const string RegistrationPending = nameof(RegistrationController.RegistrationPending);
public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider)
{
routes.MapAreaControllerRoute(
name: RegisterPath,
areaName: "OrchardCore.Users",
pattern: RegisterPath,
defaults: new { controller = "Registration", action = RegisterPath }
);
routes.MapAreaControllerRoute(
name: ConfirmEmailSent,
areaName: "OrchardCore.Users",
pattern: ConfirmEmailSent,
defaults: new { controller = "Registration", action = ConfirmEmailSent }
);
routes.MapAreaControllerRoute(
name: RegistrationPending,
areaName: "OrchardCore.Users",
pattern: RegistrationPending,
defaults: new { controller = "Registration", action = RegistrationPending }
);
}
public override void ConfigureServices(IServiceCollection services)
{
services.Configure<TemplateOptions>(o =>
{
o.MemberAccessStrategy.Register<ConfirmEmailViewModel>();
});
services.AddScoped<INavigationProvider, RegistrationAdminMenu>();
services.AddScoped<IDisplayDriver<ISite>, RegistrationSettingsDisplayDriver>();
}
}
[Feature("OrchardCore.Users.Registration")]
[RequireFeatures("OrchardCore.Deployment")]
public class RegistrationDeploymentStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddSiteSettingsPropertyDeploymentStep<RegistrationSettings, RegistrationDeploymentStartup>(S => S["Registration settings"], S => S["Exports the Registration settings."]);
}
}
[Feature("OrchardCore.Users.ResetPassword")]
public class ResetPasswordStartup : StartupBase
{
private const string ForgotPasswordPath = "ForgotPassword";
private const string ForgotPasswordConfirmationPath = "ForgotPasswordConfirmation";
private const string ResetPasswordPath = "ResetPassword";
private const string ResetPasswordConfirmationPath = "ResetPasswordConfirmation";
public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider)
{
routes.MapAreaControllerRoute(
name: "ForgotPassword",
areaName: "OrchardCore.Users",
pattern: ForgotPasswordPath,
defaults: new { controller = "ResetPassword", action = "ForgotPassword" }
);
routes.MapAreaControllerRoute(
name: "ForgotPasswordConfirmation",
areaName: "OrchardCore.Users",
pattern: ForgotPasswordConfirmationPath,
defaults: new { controller = "ResetPassword", action = "ForgotPasswordConfirmation" }
);
routes.MapAreaControllerRoute(
name: "ResetPassword",
areaName: "OrchardCore.Users",
pattern: ResetPasswordPath,
defaults: new { controller = "ResetPassword", action = "ResetPassword" }
);
routes.MapAreaControllerRoute(
name: "ResetPasswordConfirmation",
areaName: "OrchardCore.Users",
pattern: ResetPasswordConfirmationPath,
defaults: new { controller = "ResetPassword", action = "ResetPasswordConfirmation" }
);
}
public override void ConfigureServices(IServiceCollection services)
{
services.Configure<TemplateOptions>(o =>
{
o.MemberAccessStrategy.Register<LostPasswordViewModel>();
});
services.AddScoped<INavigationProvider, ResetPasswordAdminMenu>();
services.AddScoped<IDisplayDriver<ISite>, ResetPasswordSettingsDisplayDriver>();
}
}
[Feature("OrchardCore.Users.ResetPassword")]
[RequireFeatures("OrchardCore.Deployment")]
public class ResetPasswordDeploymentStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddSiteSettingsPropertyDeploymentStep<ResetPasswordSettings, ResetPasswordDeploymentStartup>(S => S["Reset Password settings"], S => S["Exports the Reset Password settings."]);
}
}
[Feature("OrchardCore.Users.CustomUserSettings")]
public class CustomUserSettingsStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IDisplayDriver<User>, CustomUserSettingsDisplayDriver>();
services.AddScoped<IPermissionProvider, CustomUserSettingsPermissions>();
}
}
}
| |
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;
// ERROR: Not supported in C#: OptionDeclaration
using Microsoft.VisualBasic.PowerPacks;
namespace _4PosBackOffice.NET
{
internal partial class frmItemItem : System.Windows.Forms.Form
{
List<Button> cmdClear = new List<Button>();
List<Button> cmdStockItem = new List<Button>();
List<Label> lblItem = new List<Label>();
private void loadLanguage()
{
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2390;
//Compare Stock Item to Stock Item|Checked
if (modRecordSet.rsLang.RecordCount){My.MyProject.Forms.frmItem.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;My.MyProject.Forms.frmItem.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2391;
//Select Stock Items|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//cmdClear(1) = No Code [Clear]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then cmdClear(1).Caption = rsLang("LanguageLayoutLnk_Description"): cmdClear(1).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//cmdClear(2) = No Code [Clear]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then cmdClear(2).Caption = rsLang("LanguageLayoutLnk_Description"): cmdClear(2).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//cmdClear(3) = No Code [Clear]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then cmdClear(3).Caption = rsLang("LanguageLayoutLnk_Description"): cmdClear(3).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//cmdClear(4) = No Code [Clear]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then cmdClear(4).Caption = rsLang("LanguageLayoutLnk_Description"): cmdClear(4).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//cmdClear(5) = No Code [Clear]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then cmdClear(5).Caption = rsLang("LanguageLayoutLnk_Description"): cmdClear(5).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//cmdClear(6) = No Code [Clear]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then cmdClear(6).Caption = rsLang("LanguageLayoutLnk_Description"): cmdClear(6).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//cmdClear(7) = No Code [Clear]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then cmdClear(7).Caption = rsLang("LanguageLayoutLnk_Description"): cmdClear(7).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//cmdClear(8) = No Code [Clear]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then cmdClear(8).Caption = rsLang("LanguageLayoutLnk_Description"): cmdClear(8).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//cmdClear(9) = No Code [Clear]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then cmdClear(9).Caption = rsLang("LanguageLayoutLnk_Description"): cmdClear(9).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//cmdClear(10) = No Code [Clear]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then cmdClear(10).Caption = rsLang("LanguageLayoutLnk_Description"): cmdClear(10).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|Checked
if (modRecordSet.rsLang.RecordCount){cmdExit.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdExit.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2382;
//Sales Quantity|Checked
if (modRecordSet.rsLang.RecordCount){_optDataType_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_optDataType_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2382;
//Sales Value|Checked
if (modRecordSet.rsLang.RecordCount){_optDataType_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_optDataType_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1269;
//Load Report|Checked
if (modRecordSet.rsLang.RecordCount){cmdLoad.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdLoad.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmItemItem.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
//Handles cmdClear.Click
private void cmdClear_Click(System.Object eventSender, System.EventArgs eventArgs)
{
Button btn = new Button();
btn = (Button)eventSender;
int Index = GetIndex.GetIndexer(ref btn, ref cmdClear);
modReport.cnnDBreport.Execute("UPDATE Link SET Link.Link_Name = '', Link.Link_SQL = '' WHERE (((Link.LinkID)=" + Index + ") AND ((Link.Link_SectionID)=3) AND ((Link.Link_PersonID)=" + modRecordSet.gPersonID + "));");
modReport.cnnDBreport.Execute("DELETE LinkDataItem.* From LinkDataItem WHERE (((LinkDataItem.LinkDataItem_LinkID)=" + Index + ") AND ((LinkDataItem.LinkDataItem_SectionID)=3) AND ((LinkDataItem.LinkDataItem_PersonID)=" + modRecordSet.gPersonID + "));");
modReport.cnnDBreport.Execute("DELETE LinkData.LinkData_LinkID, LinkData.LinkData_SectionID, LinkData.LinkData_PersonID, LinkData.* From LinkData WHERE (((LinkData.LinkData_LinkID)=" + Index + ") AND ((LinkData.LinkData_SectionID)=3) AND ((LinkData.LinkData_PersonID)=" + modRecordSet.gPersonID + "));");
lblItem[Index].Text = "";
}
private void cmdExit_Click(System.Object eventSender, System.EventArgs eventArgs)
{
this.Close();
}
//Handles cmdStockItem.Click
private void cmdStockItem_Click(System.Object eventSender, System.EventArgs eventArgs)
{
Button btn = new Button();
btn = (Button)eventSender;
int Index = GetIndex.GetIndexer(ref btn, ref cmdStockItem);
ADODB.Recordset rs = default(ADODB.Recordset);
int lID = 0;
modReport.cnnDBreport.Execute("DELETE aftDataItem.* From aftDataItem WHERE (((aftDataItem.ftDataItem_PersonID)=" + modRecordSet.gPersonID + "));");
modReport.cnnDBreport.Execute("DELETE aftData.* From aftData WHERE (((aftData.ftData_PersonID)=" + modRecordSet.gPersonID + "));");
modReport.cnnDBreport.Execute("INSERT INTO aftData ( ftData_PersonID, ftData_FieldName, ftData_SQL, ftData_Heading ) SELECT LinkData.LinkData_PersonID, LinkData.LinkData_FieldName, LinkData.LinkData_SQL, LinkData.LinkData_Heading From LinkData WHERE (((LinkData.LinkData_LinkID)=1) AND ((LinkData.LinkData_SectionID)=1) AND ((LinkData.LinkData_PersonID)=" + modRecordSet.gPersonID + "));");
modReport.cnnDBreport.Execute("INSERT INTO aftDataItem ( ftDataItem_PersonID, ftDataItem_FieldName, ftDataItem_ID ) SELECT LinkDataItem.LinkDataItem_PersonID, LinkDataItem.LinkDataItem_FieldName, LinkDataItem.LinkDataItem_ID From LinkDataItem WHERE (((LinkDataItem.LinkDataItem_LinkID)=1) AND ((LinkDataItem.LinkDataItem_SectionID)=1) AND ((LinkDataItem.LinkDataItem_PersonID)=" + modRecordSet.gPersonID + "));");
My.MyProject.Forms.frmFilter.buildCriteria(ref "StockItem");
My.MyProject.Forms.frmFilter.Close();
lID = My.MyProject.Forms.frmStockList.getItem();
if (lID) {
My.MyProject.Forms.frmFilter.buildCriteria(ref "StockItem");
rs = modReport.getRSreport(ref "SELECT Link.Link_SQL, Link.Link_SectionID From Link WHERE (((Link.Link_SQL)='StockItemID=" + lID + "') AND ((Link.Link_SectionID)=3));");
if (rs.RecordCount) {
} else {
rs.Close();
rs = modRecordSet.getRS(ref "SELECT * FROM StockItem WHERE StockItemID=" + lID);
modReport.cnnDBreport.Execute("UPDATE Link SET Link.Link_Name = ' " + Strings.Replace(rs.Fields("StockItem_Name").Value, "'", "''") + "', Link.Link_SQL = 'StockItemID=" + lID + "' WHERE (((Link.LinkID)=" + Index + ") AND ((Link.Link_SectionID)=3) AND ((Link.Link_PersonID)=" + modRecordSet.gPersonID + "));");
modReport.cnnDBreport.Execute("DELETE LinkDataItem.* From LinkDataItem WHERE (((LinkDataItem.LinkDataItem_LinkID)=" + Index + ") AND ((LinkDataItem.LinkDataItem_SectionID)=3) AND ((LinkDataItem.LinkDataItem_PersonID)=" + modRecordSet.gPersonID + "));");
modReport.cnnDBreport.Execute("DELETE LinkData.LinkData_LinkID, LinkData.LinkData_SectionID, LinkData.LinkData_PersonID, LinkData.* From LinkData WHERE (((LinkData.LinkData_LinkID)=" + Index + ") AND ((LinkData.LinkData_SectionID)=3) AND ((LinkData.LinkData_PersonID)=" + modRecordSet.gPersonID + "));");
modReport.cnnDBreport.Execute("INSERT INTO LinkData ( LinkData_LinkID, LinkData_SectionID, LinkData_PersonID, LinkData_FieldName, LinkData_SQL, LinkData_Heading ) SELECT " + Index + ", 3, aftData.ftData_PersonID, aftData.ftData_FieldName, aftData.ftData_SQL, aftData.ftData_Heading From aftData WHERE (((aftData.ftData_PersonID)=" + modRecordSet.gPersonID + "));");
modReport.cnnDBreport.Execute("INSERT INTO LinkDataItem ( LinkDataItem_LinkID, LinkDataItem_SectionID, LinkDataItem_PersonID, LinkDataItem_FieldName, LinkDataItem_ID ) SELECT " + Index + ", 3, aftDataItem.ftDataItem_PersonID, aftDataItem.ftDataItem_FieldName, aftDataItem.ftDataItem_ID From aftDataItem WHERE (((aftDataItem.ftDataItem_PersonID)=" + modRecordSet.gPersonID + "));");
lblItem[Index].Text = rs.Fields("StockItem_Name").Value;
}
}
}
private void setup()
{
ADODB.Recordset rs = default(ADODB.Recordset);
short x = 0;
rs = modReport.getRSreport(ref "SELECT Link.Link_PersonID From Link WHERE (((Link.Link_PersonID)=" + modRecordSet.gPersonID + "));");
if (rs.BOF | rs.EOF) {
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 1, 1, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 2, 1, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 1, 2, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 2, 2, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 1, 3, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 2, 3, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 3, 3, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 4, 3, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 5, 3, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 6, 3, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 7, 3, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 8, 3, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 9, 3, " + modRecordSet.gPersonID + ", '', '';");
modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 10, 3, " + modRecordSet.gPersonID + ", '', '';");
}
rs = modReport.getRSreport(ref "SELECT Link.LinkID, Link.Link_Name From Link WHERE (((Link.Link_SectionID)=3) AND ((Link.Link_PersonID)=" + modRecordSet.gPersonID + "));");
while (!(rs.EOF)) {
lblItem[rs.Fields("LinkID").Value].Text = rs.Fields("Link_Name").Value;
rs.moveNext();
}
}
private void loadQTY()
{
ADODB.Recordset rs = default(ADODB.Recordset);
ADODB.Recordset rsData = default(ADODB.Recordset);
//Dim Report As New cryItemItemCompareQty
//ReportNone.Load("cryNoRecords.rpt")
CrystalDecisions.CrystalReports.Engine.ReportDocument Report = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
CrystalDecisions.CrystalReports.Engine.ReportDocument ReportNone = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
Report.Load("cryItemItemCompareQty.rpt");
ReportNone.Load("cryNoRecords.rpt");
modReport.cnnDBreport.Execute("DELETE LinkItem.* FROM LinkItem;");
rs = modReport.getRSreport(ref "SELECT * FROM Link Where Link_SectionID=3");
while (!(rs.EOF)) {
if (!string.IsNullOrEmpty(rs.Fields("Link_SQL").Value)) {
modReport.cnnDBreport.Execute("INSERT INTO LinkItem ( LinkItem_LinkID, LinkItem_DayEndID, LinkItem_Value ) SELECT " + rs.Fields("LinkID").Value + ", DayEndStockItemLnk.DayEndStockItemLnk_DayEndID, DayEndStockItemLnk.DayEndStockItemLnk_QuantitySales FROM DayEndStockItemLnk INNER JOIN aStockItem ON DayEndStockItemLnk.DayEndStockItemLnk_StockItemID = aStockItem.StockItemID WHERE " + rs.Fields("Link_SQL").Value + ";");
}
rs.moveNext();
}
modReport.cnnDBreport.Execute("INSERT INTO LinkItem ( LinkItem_LinkID, LinkItem_DayEndID, LinkItem_Value ) SELECT theJoin.LinkID, theJoin.DayEndID, 0 FROM LinkItem RIGHT JOIN [SELECT Link.LinkID, DayEnd.DayEndID From Link, DayEnd WHERE (((Link.Link_SQL)<>'') AND ((Link.Link_SectionID)=3))]. AS theJoin ON (LinkItem.LinkItem_DayEndID = theJoin.DayEndID) AND (LinkItem.LinkItem_LinkID = theJoin.LinkID) WHERE (((LinkItem.LinkItem_LinkID) Is Null));");
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
rs = modReport.getRSreport(ref "SELECT Report.Report_Heading, aCompany.Company_Name FROM aCompany, Report;");
Report.SetParameterValue("txtCompanyName", rs.Fields("Company_Name"));
Report.SetParameterValue("txtDayEnd", rs.Fields("Report_Heading"));
rs.Close();
rs = modReport.getRSreport(ref "SELECT [Link].[LinkID], [Link].[Link_Name], Sum([LinkItem].[LinkItem_Value]) AS SumOfLinkItem_Value FROM Link INNER JOIN LinkItem ON [Link].[LinkID]=[LinkItem].[LinkItem_LinkID] WHERE ((([Link].[Link_SQL])<>'') And (([Link].[Link_SectionID])=3)) GROUP BY [Link].[LinkID], [Link].[Link_Name] ORDER BY [Link].[LinkID];");
if (rs.BOF | rs.EOF) {
ReportNone.SetParameterValue("txtCompanyName", Report.ParameterFields("txtCompanyName").ToString);
ReportNone.SetParameterValue("txtTitle", Report.ParameterFields("txtTitle").ToString);
My.MyProject.Forms.frmReportShow.Text = ReportNone.ParameterFields("txtTitle").ToString;
My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = ReportNone;
My.MyProject.Forms.frmReportShow.mReport = ReportNone;
My.MyProject.Forms.frmReportShow.sMode = "0";
My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
My.MyProject.Forms.frmReportShow.ShowDialog();
return;
}
rsData = modReport.getRSreport(ref "SELECT LinkItem.*, Format([DayEnd_Date],'yyyy mm dd ddd') AS dateName, DayEnd.DayEnd_Date FROM DayEnd INNER JOIN LinkItem ON DayEnd.DayEndID = LinkItem.LinkItem_DayEndID ORDER BY DayEnd.DayEnd_Date;");
if (rsData.BOF | rsData.EOF) {
ReportNone.SetParameterValue("txtCompanyName", Report.ParameterFields("txtCompanyName").ToString);
ReportNone.SetParameterValue("txtTitle", Report.ParameterFields("txtTitle").ToString);
My.MyProject.Forms.frmReportShow.Text = ReportNone.ParameterFields("txtTitle").ToString;
My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = ReportNone;
My.MyProject.Forms.frmReportShow.mReport = ReportNone;
My.MyProject.Forms.frmReportShow.sMode = "0";
My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
//UPGRADE_WARNING: Screen property Screen.MousePointer has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6BA9B8D2-2A32-4B6E-8D36-44949974A5B4"'
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
My.MyProject.Forms.frmReportShow.ShowDialog();
return;
}
Report.Database.Tables(1).SetDataSource(rs);
Report.Database.Tables(2).SetDataSource(rsData);
System.Windows.Forms.Application.DoEvents();
//Report.VerifyOnEveryPrint = True
System.Windows.Forms.Application.DoEvents();
My.MyProject.Forms.frmReportShow.Text = Report.ParameterFields("txtTitle").ToString;
My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = Report;
My.MyProject.Forms.frmReportShow.mReport = Report;
My.MyProject.Forms.frmReportShow.sMode = "0";
My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
My.MyProject.Forms.frmReportShow.ShowDialog();
}
private void loadValue()
{
ADODB.Recordset rs = default(ADODB.Recordset);
ADODB.Recordset rsData = default(ADODB.Recordset);
//Dim Report As New cryItemItemCompareValue
//ReportNone.Load("cryNoRecords.rpt")
CrystalDecisions.CrystalReports.Engine.ReportDocument Report = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
CrystalDecisions.CrystalReports.Engine.ReportDocument ReportNone = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
Report.Load("cryItemItemCompareValue.rpt");
ReportNone.Load("cryNoRecords.rpt");
modReport.cnnDBreport.Execute("DELETE LinkItem.* FROM LinkItem;");
rs = modReport.getRSreport(ref "SELECT * FROM Link Where Link_SectionID=3");
while (!(rs.EOF)) {
if (!string.IsNullOrEmpty(rs.Fields("Link_SQL").Value)) {
modReport.cnnDBreport.Execute("INSERT INTO LinkItem ( LinkItem_LinkID, LinkItem_DayEndID, LinkItem_Value ) SELECT " + rs.Fields("LinkID").Value + ", Sale.Sale_DayEndID, Sum([SaleItem_Quantity]*[SaleItem_Price]) FROM (SaleItem INNER JOIN aStockItem ON SaleItem.SaleItem_StockItemID = aStockItem.StockItemID) INNER JOIN Sale ON SaleItem.SaleItem_SaleID = Sale.SaleID Where " + rs.Fields("Link_SQL").Value + " GROUP BY Sale.Sale_DayEndID;");
}
rs.moveNext();
}
modReport.cnnDBreport.Execute("INSERT INTO LinkItem ( LinkItem_LinkID, LinkItem_DayEndID, LinkItem_Value ) SELECT theJoin.LinkID, theJoin.DayEndID, 0 FROM LinkItem RIGHT JOIN [SELECT Link.LinkID, DayEnd.DayEndID From Link, DayEnd WHERE (((Link.Link_SQL)<>'') AND ((Link.Link_SectionID)=3))]. AS theJoin ON (LinkItem.LinkItem_DayEndID = theJoin.DayEndID) AND (LinkItem.LinkItem_LinkID = theJoin.LinkID) WHERE (((LinkItem.LinkItem_LinkID) Is Null));");
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
rs = modReport.getRSreport(ref "SELECT Report.Report_Heading, aCompany.Company_Name FROM aCompany, Report;");
Report.SetParameterValue("txtCompanyName", rs.Fields("Company_Name"));
Report.SetParameterValue("txtDayEnd", rs.Fields("Report_Heading"));
rs.Close();
rs = modReport.getRSreport(ref "SELECT [Link].[LinkID], [Link].[Link_Name], Sum([LinkItem].[LinkItem_Value]) AS SumOfLinkItem_Value FROM Link INNER JOIN LinkItem ON [Link].[LinkID]=[LinkItem].[LinkItem_LinkID] WHERE ((([Link].[Link_SQL])<>'') And (([Link].[Link_SectionID])=3)) GROUP BY [Link].[LinkID], [Link].[Link_Name] ORDER BY [Link].[LinkID];");
if (rs.BOF | rs.EOF) {
ReportNone.SetParameterValue("txtCompanyName", Report.ParameterFields("txtCompanyName").ToString);
ReportNone.SetParameterValue("txtTitle", Report.ParameterFields("txtTitle").ToString);
My.MyProject.Forms.frmReportShow.Text = ReportNone.ParameterFields("txtTitle").ToString;
My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = ReportNone;
My.MyProject.Forms.frmReportShow.mReport = ReportNone;
My.MyProject.Forms.frmReportShow.sMode = "0";
My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
My.MyProject.Forms.frmReportShow.ShowDialog();
return;
}
rsData = modReport.getRSreport(ref "SELECT LinkItem.*, Format([DayEnd_Date],'yyyy mm dd ddd') AS dateName, DayEnd.DayEnd_Date FROM DayEnd INNER JOIN LinkItem ON DayEnd.DayEndID = LinkItem.LinkItem_DayEndID ORDER BY DayEnd.DayEnd_Date;");
if (rsData.BOF | rsData.EOF) {
ReportNone.SetParameterValue("txtCompanyName", Report.ParameterFields("txtCompanyName").ToString);
ReportNone.SetParameterValue("txtTitle", Report.ParameterFields("txtTitle").ToString);
My.MyProject.Forms.frmReportShow.Text = ReportNone.ParameterFields("txtTitle").ToString;
My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = ReportNone;
My.MyProject.Forms.frmReportShow.mReport = ReportNone;
My.MyProject.Forms.frmReportShow.sMode = "0";
My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
My.MyProject.Forms.frmReportShow.ShowDialog();
return;
}
Report.Database.Tables(1).SetDataSource(rs);
Report.Database.Tables(2).SetDataSource(rsData);
System.Windows.Forms.Application.DoEvents();
//Report.VerifyOnEveryPrint = True
System.Windows.Forms.Application.DoEvents();
My.MyProject.Forms.frmReportShow.Text = Report.ParameterFields("txtTitle").ToString;
My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = Report;
My.MyProject.Forms.frmReportShow.mReport = Report;
My.MyProject.Forms.frmReportShow.sMode = "0";
My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
My.MyProject.Forms.frmReportShow.ShowDialog();
}
private void cmdLoad_Click(System.Object eventSender, System.EventArgs eventArgs)
{
if (_optDataType_0.Checked) {
loadQTY();
} else {
loadValue();
}
}
private void frmItemItem_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
if (KeyAscii == 27) {
KeyAscii = 0;
this.Close();
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void frmItemItem_Load(System.Object eventSender, System.EventArgs eventArgs)
{
cmdClear.AddRange(new Button[] {
_cmdClear_1,
_cmdClear_2,
_cmdClear_3,
_cmdClear_4,
_cmdClear_5,
_cmdClear_6,
_cmdClear_7,
_cmdClear_8,
_cmdClear_9,
_cmdClear_10
});
cmdStockItem.AddRange(new Button[] {
_cmdStockItem_1,
_cmdStockItem_2,
_cmdStockItem_3,
_cmdStockItem_4,
_cmdStockItem_5,
_cmdStockItem_6,
_cmdStockItem_7,
_cmdStockItem_8,
_cmdStockItem_9,
_cmdStockItem_10
});
lblItem.AddRange(new Label[] {
_lblItem_1,
_lblItem_2,
_lblItem_3,
_lblItem_4,
_lblItem_5,
_lblItem_6,
_lblItem_7,
_lblItem_8,
_lblItem_9,
_lblItem_10
});
Button bt = new Button();
foreach (Button bt_loopVariable in cmdClear) {
bt = bt_loopVariable;
bt.Click += cmdClear_Click;
}
foreach (Button bt_loopVariable in cmdStockItem) {
bt = bt_loopVariable;
bt.Click += cmdStockItem_Click;
}
modRecordSet.openConnection();
modReport.openConnectionReport();
loadLanguage();
setup();
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_OXWSFOLD
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// The base class of scenario class.
/// </summary>
[TestClass]
public class TestSuiteBase : TestClassBase
{
#region Fields
/// <summary>
/// Specify if a permission authorized user can create subfolder.
/// </summary>
private bool canCreateSubFolder;
/// <summary>
/// Specify if a permission authorized user can read subfolder.
/// </summary>
private bool canReadSubFolder;
/// <summary>
/// Specify if a permission authorized user can edit subfolder.
/// </summary>
private bool canEditSubFolder;
/// <summary>
/// Specify if a permission authorized user can delete subfolder.
/// </summary>
private bool canDeleteSubFolder;
/// <summary>
/// Specify if a permission authorized user can create item.
/// </summary>
private bool canCreateItem;
/// <summary>
/// Specify if a permission authorized user can read items which is created by the user.
/// </summary>
private bool canReadOwnedItem;
/// <summary>
/// Specify if a permission authorized user can edit items which is created by the user.
/// </summary>
private bool canEditOwnedItem;
/// <summary>
/// Specify if a permission authorized user can delete items which is created by the user.
/// </summary>
private bool canDeleteOwnedItem;
/// <summary>
/// Specify if a permission authorized user can read items which isn't created by the user.
/// </summary>
private bool canReadNotOwnedItem;
/// <summary>
/// Specify if a permission authorized user can edit items which isn't created by the user.
/// </summary>
private bool canEditNotOwnedItem;
/// <summary>
/// Specify if a permission authorized user can delete items which isn't created by the user.
/// </summary>
private bool canDeleteNotOwnedItem;
/// <summary>
/// Variable to save the new created folder's folder Ids.
/// </summary>
private Collection<FolderIdType> newCreatedFolderIds;
/// <summary>
/// Variable to save the new created items' Ids.
/// </summary>
private Collection<ItemIdType> newCreatedItemIds;
#endregion
#region Properties
/// <summary>
/// Gets the MS-OXWSFOLD SUT Control Adapter.
/// </summary>
protected IMS_OXWSFOLDSUTControlAdapter FOLDSUTControlAdapter { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether a subfolder can be created..
/// </summary>
protected bool CanCreateSubFolder
{
get { return this.canCreateSubFolder; }
set { this.canCreateSubFolder = value; }
}
/// <summary>
/// Gets or sets a value indicating whether a subfolder can be read.
/// </summary>
protected bool CanReadSubFolder
{
get { return this.canReadSubFolder; }
set { this.canReadSubFolder = value; }
}
/// <summary>
/// Gets or sets a value indicating whether a subfolder can be edited.
/// </summary>
protected bool CanEditSubFolder
{
get { return this.canEditSubFolder; }
set { this.canEditSubFolder = value; }
}
/// <summary>
/// Gets or sets a value indicating whether a subfolder can be deleted.
/// </summary>
protected bool CanDeleteSubFolder
{
get { return this.canDeleteSubFolder; }
set { this.canDeleteSubFolder = value; }
}
/// <summary>
/// Gets or sets a value indicating whether an item can be created.
/// </summary>
protected bool CanCreateItem
{
get { return this.canCreateItem; }
set { this.canCreateItem = value; }
}
/// <summary>
/// Gets or sets a value indicating whether an item owned by a user can be read.
/// </summary>
protected bool CanReadOwnedItem
{
get { return this.canReadOwnedItem; }
set { this.canReadOwnedItem = value; }
}
/// <summary>
/// Gets or sets a value indicating whether an item owned by a user can be edited.
/// </summary>
protected bool CanEditOwnedItem
{
get { return this.canEditOwnedItem; }
set { this.canEditOwnedItem = value; }
}
/// <summary>
/// Gets or sets a value indicating whether an item owned by a user can be deleted.
/// </summary>
protected bool CanDeleteOwnedItem
{
get { return this.canDeleteOwnedItem; }
set { this.canDeleteOwnedItem = value; }
}
/// <summary>
/// Gets or sets a value indicating whether an item not owned by a user can be read.
/// </summary>
protected bool CanReadNotOwnedItem
{
get { return this.canReadNotOwnedItem; }
set { this.canReadNotOwnedItem = value; }
}
/// <summary>
/// Gets or sets a value indicating whether an item not owned by a user can be edited.
/// </summary>
protected bool CanEditNotOwnedItem
{
get { return this.canEditNotOwnedItem; }
set { this.canEditNotOwnedItem = value; }
}
/// <summary>
/// Gets or sets a value indicating whether an item not owned by a user can be deleted.
/// </summary>
protected bool CanDeleteNotOwnedItem
{
get { return this.canDeleteNotOwnedItem; }
set { this.canDeleteNotOwnedItem = value; }
}
/// <summary>
/// Gets newCreatedFolderIds which contains created folder ids.
/// </summary>
protected Collection<FolderIdType> NewCreatedFolderIds
{
get { return this.newCreatedFolderIds; }
}
/// <summary>
/// Gets newCreatedItemIds which contains created folder ids.
/// </summary>
protected Collection<ItemIdType> NewCreatedItemIds
{
get { return this.newCreatedItemIds; }
}
/// <summary>
/// Gets MS-OXWSFOLD protocol adapter.
/// </summary>
protected IMS_OXWSFOLDAdapter FOLDAdapter { get; private set; }
/// <summary>
/// Gets MS-OXWSCORE protocol adapter.
/// </summary>
protected IMS_OXWSCOREAdapter COREAdapter { get; private set; }
/// <summary>
/// Gets MS-OXWSSRCH protocol adapter.
/// </summary>
protected IMS_OXWSSRCHAdapter SRCHAdapter { get; private set; }
#endregion
#region Test case initialize and clean up
/// <summary>
/// Initialize the Test suite.
/// </summary>
protected override void TestInitialize()
{
// Following codes shall be run before every test case execution.
base.TestInitialize();
this.newCreatedFolderIds = new Collection<FolderIdType>();
this.newCreatedItemIds = new Collection<ItemIdType>();
this.FOLDAdapter = Site.GetAdapter<IMS_OXWSFOLDAdapter>();
this.FOLDSUTControlAdapter = this.Site.GetAdapter<IMS_OXWSFOLDSUTControlAdapter>();
this.COREAdapter = Site.GetAdapter<IMS_OXWSCOREAdapter>();
this.SRCHAdapter = Site.GetAdapter<IMS_OXWSSRCHAdapter>();
this.InitialPermissionVariables();
}
/// <summary>
/// Clean up the environment.
/// </summary>
protected override void TestCleanup()
{
// Ensure use the right user to clean up.
#region Switch user
this.SwitchUser(Common.GetConfigurationPropertyValue("User1Name", this.Site), Common.GetConfigurationPropertyValue("User1Password", this.Site), Common.GetConfigurationPropertyValue("Domain", this.Site));
#endregion
// Following codes shall be run after every test case execution.
#region Delete the new created folder to make sure each case run at the same environment.
// Clean up all created folders.
if (this.newCreatedFolderIds.Count > 0)
{
for (int temp = 0; temp < this.newCreatedFolderIds.Count; temp++)
{
// Delete folder request.
DeleteFolderType deleteFolderRequest = new DeleteFolderType();
// Specify the delete type.
deleteFolderRequest.DeleteType = DisposalType.HardDelete;
// Set the deleteFolderRequest's folderId type.
deleteFolderRequest.FolderIds = new BaseFolderIdType[1];
deleteFolderRequest.FolderIds[0] = this.newCreatedFolderIds[temp];
// Delete the specified folder.
this.FOLDAdapter.DeleteFolder(deleteFolderRequest);
}
}
// Clean up all created items.
if (this.newCreatedItemIds.Count > 0)
{
for (int temp = 0; temp < this.newCreatedItemIds.Count; temp++)
{
this.DeleteItem(this.newCreatedItemIds[temp]);
}
}
#endregion
}
#endregion
#region Test case base methods
/// <summary>
/// Create item within a specific folder.
/// </summary>
/// <param name="toAddress">To address of created item</param>
/// <param name="folderId">Parent folder id of the created item.</param>
/// <param name="subject">Subject of the item.</param>
/// <returns>Id of created item.</returns>
protected ItemIdType CreateItem(string toAddress, string folderId, string subject)
{
CreateItemType createItemRequest = new CreateItemType();
createItemRequest.MessageDispositionSpecified = true;
createItemRequest.MessageDisposition = MessageDispositionType.SaveOnly;
createItemRequest.SendMeetingInvitations = CalendarItemCreateOrDeleteOperationType.SendToAllAndSaveCopy;
createItemRequest.SendMeetingInvitationsSpecified = true;
createItemRequest.SavedItemFolderId = new TargetFolderIdType();
DistinguishedFolderIdType distinguishedFolderId = new DistinguishedFolderIdType();
DistinguishedFolderIdNameType distinguishedFolderIdName = new DistinguishedFolderIdNameType();
bool isSuccess = Enum.TryParse<DistinguishedFolderIdNameType>(folderId, true, out distinguishedFolderIdName);
if (isSuccess)
{
distinguishedFolderId.Id = distinguishedFolderIdName;
createItemRequest.SavedItemFolderId.Item = distinguishedFolderId;
}
else
{
FolderIdType id = new FolderIdType();
id.Id = folderId;
createItemRequest.SavedItemFolderId.Item = id;
}
MessageType message = new MessageType();
message.Subject = subject;
EmailAddressType address = new EmailAddressType();
address.EmailAddress = toAddress;
// Set this message to unread.
message.IsRead = false;
message.IsReadSpecified = true;
message.ToRecipients = new EmailAddressType[1];
message.ToRecipients[0] = address;
BodyType body = new BodyType();
body.Value = Common.GenerateResourceName(this.Site, "Test Mail Body");
message.Body = body;
createItemRequest.Items = new NonEmptyArrayOfAllItemsType();
createItemRequest.Items.Items = new ItemType[1];
createItemRequest.Items.Items[0] = message;
CreateItemResponseType createItemResponse = this.COREAdapter.CreateItem(createItemRequest);
ItemInfoResponseMessageType itemInfo = (ItemInfoResponseMessageType)createItemResponse.ResponseMessages.Items[0];
// Return item id.
if (itemInfo.Items.Items != null)
{
return itemInfo.Items.Items[0].ItemId;
}
else
{
return null;
}
}
/// <summary>
/// Find item within a specific folder.
/// </summary>
/// <param name="folderName">The name of the folder to search item.</param>
/// <param name="itemSubject">The subject of the item to be searched.</param>
/// <returns>Id of found item.</returns>
protected ItemIdType FindItem(string folderName, string itemSubject)
{
// Create the request and specify the parent folder ID.
FindItemType findItemRequest = new FindItemType();
findItemRequest.ParentFolderIds = new BaseFolderIdType[1];
DistinguishedFolderIdType parentFolder = new DistinguishedFolderIdType();
parentFolder.Id = (DistinguishedFolderIdNameType)Enum.Parse(typeof(DistinguishedFolderIdNameType), folderName, true);
findItemRequest.ParentFolderIds[0] = parentFolder;
// Get properties that are defined as the default for the items.
findItemRequest.ItemShape = new ItemResponseShapeType();
findItemRequest.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;
// Await the item created properly.
int sleepTime = Convert.ToInt32(Common.GetConfigurationPropertyValue("WaitTime", this.Site));
int retryCount = Convert.ToInt32(Common.GetConfigurationPropertyValue("RetryCount", this.Site));
int timesOfSleep = 0;
ItemIdType itemId = null;
do
{
Thread.Sleep(sleepTime);
// Invoke the FindItem operation.
FindItemResponseType findItemResponse = this.SRCHAdapter.FindItem(findItemRequest);
if (findItemResponse != null)
{
// Get the found items from the response.
FindItemResponseMessageType findItemMessage = findItemResponse.ResponseMessages.Items[0] as FindItemResponseMessageType;
ArrayOfRealItemsType itemArray = findItemMessage.RootFolder.Item as ArrayOfRealItemsType;
ItemType[] items = itemArray.Items;
if (items != null)
{
foreach (ItemType item in items)
{
if (item.Subject == itemSubject)
{
itemId = item.ItemId;
return itemId;
}
}
}
timesOfSleep++;
}
}
while (itemId == null && timesOfSleep <= retryCount);
return null;
}
/// <summary>
/// Find if item within a specific folder is deleted.
/// </summary>
/// <param name="folderName">The name of the folder to search item.</param>
/// <param name="itemSubject">The subject of the item to be searched.</param>
/// <returns>If item has been deleted.</returns>
protected bool IfItemDeleted(string folderName, string itemSubject)
{
// Create the request and specify the parent folder ID.
FindItemType findItemRequest = new FindItemType();
findItemRequest.ParentFolderIds = new BaseFolderIdType[1];
DistinguishedFolderIdType parentFolder = new DistinguishedFolderIdType();
parentFolder.Id = (DistinguishedFolderIdNameType)Enum.Parse(typeof(DistinguishedFolderIdNameType), folderName, true);
findItemRequest.ParentFolderIds[0] = parentFolder;
// Get properties that are defined as the default for the items.
findItemRequest.ItemShape = new ItemResponseShapeType();
findItemRequest.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;
// Await the item created properly.
int sleepTime = Convert.ToInt32(Common.GetConfigurationPropertyValue("WaitTime", this.Site));
int retryCount = Convert.ToInt32(Common.GetConfigurationPropertyValue("RetryCount", this.Site));
int timesOfSleep = 0;
bool itemDeleted = true;
do
{
itemDeleted = true;
Thread.Sleep(sleepTime);
// Invoke the FindItem operation.
FindItemResponseType findItemResponse = this.SRCHAdapter.FindItem(findItemRequest);
if (findItemResponse != null)
{
// Get the found items from the response.
FindItemResponseMessageType findItemMessage = findItemResponse.ResponseMessages.Items[0] as FindItemResponseMessageType;
ArrayOfRealItemsType itemArray = findItemMessage.RootFolder.Item as ArrayOfRealItemsType;
ItemType[] items = itemArray.Items;
if (items != null)
{
foreach (ItemType item in items)
{
if (item.Subject == itemSubject)
{
itemDeleted = false;
break;
}
}
}
timesOfSleep++;
}
}
while (!itemDeleted && timesOfSleep <= retryCount);
return itemDeleted;
}
/// <summary>
/// Update subject of specific items.
/// </summary>
/// <param name="itemIds">An array of folder identifiers.</param>
/// <returns>If item updated successfully.</returns>
protected bool UpdateItemSubject(params ItemIdType[] itemIds)
{
UpdateItemType updateRequest = new UpdateItemType();
ItemChangeType[] itemChanges = new ItemChangeType[itemIds.Length];
for (int index = 0; index < itemIds.Length; index++)
{
itemChanges[index] = new ItemChangeType();
itemChanges[index].Item = itemIds[index];
itemChanges[index].Updates = new ItemChangeDescriptionType[1];
SetItemFieldType setItem = new SetItemFieldType();
setItem.Item = new PathToUnindexedFieldType()
{
FieldURI = UnindexedFieldURIType.itemSubject
};
setItem.Item1 = new ContactItemType()
{
Subject = Common.GenerateResourceName(this.Site, "ItemSubjectUpdated", (uint)index),
};
itemChanges[index].Updates[0] = setItem;
}
updateRequest.ItemChanges = itemChanges;
updateRequest.MessageDispositionSpecified = true;
updateRequest.MessageDisposition = MessageDispositionType.SaveOnly;
updateRequest.SendMeetingInvitationsOrCancellations = CalendarItemUpdateOperationType.SendToAllAndSaveCopy;
updateRequest.SendMeetingInvitationsOrCancellationsSpecified = true;
UpdateItemResponseType updateItemResponse = this.COREAdapter.UpdateItem(updateRequest);
// A Boolean indicates whether the response is a success.
bool isSuccess = new bool();
for (int index = 0; index < itemIds.Length; index++)
{
isSuccess = ResponseClassType.Success == updateItemResponse.ResponseMessages.Items[index].ResponseClass;
if (isSuccess)
{
continue;
}
else
{
break;
}
}
return isSuccess;
}
/// <summary>
/// Get information of specific items.
/// </summary>
/// <param name="itemIds">An array of folder identifiers.</param>
/// <returns>If item information returned successfully.</returns>
protected bool GetItem(params ItemIdType[] itemIds)
{
GetItemType getItemRequest = new GetItemType();
// The Items properties returned
getItemRequest.ItemShape = new ItemResponseShapeType();
getItemRequest.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;
// The items to get
getItemRequest.ItemIds = itemIds;
GetItemResponseType getItemResponse = this.COREAdapter.GetItem(getItemRequest);
return ResponseClassType.Success == getItemResponse.ResponseMessages.Items[0].ResponseClass;
}
/// <summary>
/// Delete specific item.
/// </summary>
/// <param name="itemId">Id of specific item.</param>
/// <returns>If specific item deleted successfully.</returns>
protected bool DeleteItem(ItemIdType itemId)
{
// If id is null return false.
if (itemId == null)
{
return false;
}
DeleteItemType deleteItemRequest = new DeleteItemType();
deleteItemRequest.AffectedTaskOccurrences = AffectedTaskOccurrencesType.AllOccurrences;
deleteItemRequest.AffectedTaskOccurrencesSpecified = true;
deleteItemRequest.SendMeetingCancellations = CalendarItemCreateOrDeleteOperationType.SendToNone;
deleteItemRequest.SendMeetingCancellationsSpecified = true;
// Serialize item ids and change keys to ItemIdType arrays.
ItemIdType[] itemIdTypes = new ItemIdType[1];
itemIdTypes[0] = itemId;
deleteItemRequest.ItemIds = itemIdTypes;
deleteItemRequest.DeleteType = DisposalType.HardDelete;
DeleteItemResponseType deleteItemResponse = this.COREAdapter.DeleteItem(deleteItemRequest);
return deleteItemResponse.ResponseMessages.Items[0].ResponseCode == ResponseCodeType.NoError;
}
/// <summary>
/// Set related folder properties of create folder request
/// </summary>
/// <param name="displayNames">Display names of folders that will be set into create folder request.</param>
/// <param name="folderClasses">Folder class values of folders that will be set into create folder request.</param>
/// <param name="folderPermissions">Folder permission values of folders that will be set into create folder request. </param>
/// <param name="createFolderRequest">Create folder request instance that needs to set property values.</param>
/// <returns>Create folder request instance that have folder property value configured.</returns>
protected CreateFolderType ConfigureFolderProperty(string[] displayNames, string[] folderClasses, PermissionSetType[] folderPermissions, CreateFolderType createFolderRequest)
{
Site.Assert.IsNotNull(displayNames, "Display names should not be null!");
Site.Assert.IsNotNull(folderClasses, "Folder classes should not be null!");
Site.Assert.AreEqual<int>(displayNames.Length, folderClasses.Length, "Folder names count should equals to folder class value count!");
if (folderPermissions != null)
{
Site.Assert.AreEqual<int>(displayNames.Length, folderPermissions.Length, "Folder names count should equals to folder permission value count!");
}
int folderCount = displayNames.Length;
createFolderRequest.Folders = new BaseFolderType[folderCount];
for (int folderPropertyIndex = 0; folderPropertyIndex < folderCount; folderPropertyIndex++)
{
string folderResourceName = Common.GenerateResourceName(this.Site, displayNames[folderPropertyIndex]);
if (folderClasses[folderPropertyIndex] == "IPF.Appointment")
{
CalendarFolderType calendarFolder = new CalendarFolderType();
calendarFolder.DisplayName = folderResourceName;
createFolderRequest.Folders[folderPropertyIndex] = calendarFolder;
}
else if (folderClasses[folderPropertyIndex] == "IPF.Contact")
{
ContactsFolderType contactFolder = new ContactsFolderType();
contactFolder.DisplayName = folderResourceName;
if (folderPermissions != null)
{
contactFolder.PermissionSet = folderPermissions[folderPropertyIndex];
}
createFolderRequest.Folders[folderPropertyIndex] = contactFolder;
}
else if (folderClasses[folderPropertyIndex] == "IPF.Task")
{
TasksFolderType taskFolder = new TasksFolderType();
taskFolder.DisplayName = folderResourceName;
if (folderPermissions != null)
{
taskFolder.PermissionSet = folderPermissions[folderPropertyIndex];
}
createFolderRequest.Folders[folderPropertyIndex] = taskFolder;
}
else if (folderClasses[folderPropertyIndex] == "IPF.Search")
{
SearchFolderType searchFolder = new SearchFolderType();
searchFolder.DisplayName = folderResourceName;
// Set search parameters.
searchFolder.SearchParameters = new SearchParametersType();
searchFolder.SearchParameters.Traversal = SearchFolderTraversalType.Deep;
searchFolder.SearchParameters.TraversalSpecified = true;
searchFolder.SearchParameters.BaseFolderIds = new DistinguishedFolderIdType[1];
DistinguishedFolderIdType inboxType = new DistinguishedFolderIdType();
inboxType.Id = new DistinguishedFolderIdNameType();
inboxType.Id = DistinguishedFolderIdNameType.inbox;
searchFolder.SearchParameters.BaseFolderIds[0] = inboxType;
// Use the following search filter
searchFolder.SearchParameters.Restriction = new RestrictionType();
PathToUnindexedFieldType path = new PathToUnindexedFieldType();
path.FieldURI = UnindexedFieldURIType.itemSubject;
RestrictionType restriction = new RestrictionType();
ExistsType isEqual = new ExistsType();
isEqual.Item = path;
restriction.Item = isEqual;
searchFolder.SearchParameters.Restriction = restriction;
if (folderPermissions != null)
{
searchFolder.PermissionSet = folderPermissions[folderPropertyIndex];
}
createFolderRequest.Folders[folderPropertyIndex] = searchFolder;
}
else
{
// Set Display Name and Folder Class for the folder to be created.
FolderType folder = new FolderType();
folder.DisplayName = folderResourceName;
folder.FolderClass = folderClasses[folderPropertyIndex];
if (folderPermissions != null)
{
folder.PermissionSet = folderPermissions[folderPropertyIndex];
}
createFolderRequest.Folders[folderPropertyIndex] = folder;
}
}
return createFolderRequest;
}
/// <summary>
/// Generate the request message for operation "CreateFolder".
/// </summary>
/// <param name="parentFolderId">The folder identifier for the parent folder.</param>
/// <param name="folderNames">An array of display name of the folders to be created.</param>
/// <param name="folderClasses">An array of folder class value of the folders to be created.</param>
/// <param name="permissionSet">An array of permission set value of the folder.</param>
/// <returns>Create folder request instance that will send to server.</returns>
protected CreateFolderType GetCreateFolderRequest(string parentFolderId, string[] folderNames, string[] folderClasses, PermissionSetType[] permissionSet)
{
CreateFolderType createFolderRequest = new CreateFolderType();
createFolderRequest.ParentFolderId = new TargetFolderIdType();
DistinguishedFolderIdType distinguishedFolderId = new DistinguishedFolderIdType();
DistinguishedFolderIdNameType distinguishedFolderIdName = new DistinguishedFolderIdNameType();
bool isSuccess = Enum.TryParse<DistinguishedFolderIdNameType>(parentFolderId, true, out distinguishedFolderIdName);
if (isSuccess)
{
distinguishedFolderId.Id = distinguishedFolderIdName;
createFolderRequest.ParentFolderId.Item = distinguishedFolderId;
}
else
{
FolderIdType id = new FolderIdType();
id.Id = parentFolderId;
createFolderRequest.ParentFolderId.Item = id;
}
createFolderRequest = this.ConfigureFolderProperty(folderNames, folderClasses, permissionSet, createFolderRequest);
return createFolderRequest;
}
/// <summary>
/// Generate the request message for operation "GetFolder".
/// </summary>
/// <param name="shapeName">The properties to include in the response.</param>
/// <param name="folderIds">An array of folder identifiers.</param>
/// <returns>Get folder request instance that will send to server.</returns>
protected GetFolderType GetGetFolderRequest(DefaultShapeNamesType shapeName, params BaseFolderIdType[] folderIds)
{
Site.Assert.IsNotNull(folderIds, "Folders id should not be null!");
Site.Assert.AreNotEqual<int>(0, folderIds.Length, "Folders id should contains at least one Id!");
GetFolderType getFolderRequest = new GetFolderType();
// Specify how many folders need to be gotten.
int folderCount = folderIds.Length;
// Set the request's folderId.
getFolderRequest.FolderIds = new BaseFolderIdType[folderCount];
for (int folderIdIndex = 0; folderIdIndex < folderCount; folderIdIndex++)
{
getFolderRequest.FolderIds[folderIdIndex] = folderIds[folderIdIndex];
}
// Set folder shape.
getFolderRequest.FolderShape = new FolderResponseShapeType();
getFolderRequest.FolderShape.BaseShape = shapeName;
return getFolderRequest;
}
/// <summary>
/// Generate the request message for operation "DeleteFolder".
/// </summary>
/// <param name="deleteType">How folders are to be deleted.</param>
/// <param name="folderIds">An array of folder identifier of the folders need to be deleted</param>
/// <returns>Delete folder request instance that will send to server.</returns>
protected DeleteFolderType GetDeleteFolderRequest(DisposalType deleteType, params BaseFolderIdType[] folderIds)
{
Site.Assert.IsNotNull(folderIds, "Folders id should not be null!");
Site.Assert.AreNotEqual<int>(0, folderIds.Length, "Folders id should contains at least one Id!");
DeleteFolderType deleteFolderRequest = new DeleteFolderType();
// Specify the delete type.
deleteFolderRequest.DeleteType = deleteType;
int folderCount = folderIds.Length;
// Set the request's folderId field.
deleteFolderRequest.FolderIds = new BaseFolderIdType[folderCount];
for (int folderIdIndex = 0; folderIdIndex < folderCount; folderIdIndex++)
{
deleteFolderRequest.FolderIds[folderIdIndex] = folderIds[folderIdIndex];
}
return deleteFolderRequest;
}
/// <summary>
/// Generate the request message for operation "CreateManagedFolder".
/// </summary>
/// <param name="folderNames">An array of names of managed folder.</param>
/// <returns>Create managed folder request instance that will send to server.</returns>
protected CreateManagedFolderRequestType GetCreateManagedFolderRequest(params string[] folderNames)
{
Site.Assert.IsNotNull(folderNames, "Folder names should not be null!");
Site.Assert.AreNotEqual<int>(0, folderNames.Length, "Folder names should contains at least one name!");
CreateManagedFolderRequestType createManagedFolderRequest = new CreateManagedFolderRequestType();
int folderCount = folderNames.Length;
// Set the new managed folder's name.
createManagedFolderRequest.FolderNames = new string[folderCount];
for (int folderNameIndex = 0; folderNameIndex < folderCount; folderNameIndex++)
{
createManagedFolderRequest.FolderNames[folderNameIndex] = folderNames[folderNameIndex];
}
return createManagedFolderRequest;
}
/// <summary>
/// Empty a specific folder.
/// </summary>
/// <param name="folderId">The folder identifier of the folder need to be emptied.</param>
/// <param name="deleteType">How an item is deleted.</param>
/// <param name="deleteSubfolder">Indicates whether the subfolders are also to be deleted. </param>
/// <returns>Empty folder response instance that will send to server.</returns>
protected EmptyFolderResponseType CallEmptyFolderOperation(BaseFolderIdType folderId, DisposalType deleteType, bool deleteSubfolder)
{
// EmptyFolder request.
EmptyFolderType emptyFolderRequest = new EmptyFolderType();
// Specify the delete type.
emptyFolderRequest.DeleteType = deleteType;
// Specify which folder will be emptied.
emptyFolderRequest.FolderIds = new BaseFolderIdType[1];
emptyFolderRequest.FolderIds[0] = folderId;
emptyFolderRequest.DeleteSubFolders = deleteSubfolder;
// Empty the specific folder
EmptyFolderResponseType emptyFolderResponse = this.FOLDAdapter.EmptyFolder(emptyFolderRequest);
return emptyFolderResponse;
}
/// <summary>
/// Generate the request message for operation "CopyFolder".
/// </summary>
/// <param name="toFolderId">A target folder for operations that copy folders.</param>
/// <param name="folderIds">An array of folder identifier of the folders need to be copied.</param>
/// <returns>Copy folder request instance that will send to server.</returns>
protected CopyFolderType GetCopyFolderRequest(string toFolderId, params BaseFolderIdType[] folderIds)
{
Site.Assert.IsNotNull(folderIds, "Folders id should not be null!");
Site.Assert.AreNotEqual<int>(0, folderIds.Length, "Folders id should contains at least one id!");
// CopyFolder request.
CopyFolderType copyFolderRequest = new CopyFolderType();
int folderCount = folderIds.Length;
// Identify the folders to be copied.
copyFolderRequest.FolderIds = new BaseFolderIdType[folderCount];
for (int folderIdIndex = 0; folderIdIndex < folderCount; folderIdIndex++)
{
copyFolderRequest.FolderIds[folderIdIndex] = folderIds[folderIdIndex];
}
// Identify the destination folder.
copyFolderRequest.ToFolderId = new TargetFolderIdType();
DistinguishedFolderIdType distinguishedFolderId = new DistinguishedFolderIdType();
DistinguishedFolderIdNameType distinguishedFolderIdName = new DistinguishedFolderIdNameType();
bool isSuccess = Enum.TryParse<DistinguishedFolderIdNameType>(toFolderId, true, out distinguishedFolderIdName);
if (isSuccess)
{
distinguishedFolderId.Id = distinguishedFolderIdName;
copyFolderRequest.ToFolderId.Item = distinguishedFolderId;
}
else
{
FolderIdType id = new FolderIdType();
id.Id = toFolderId;
copyFolderRequest.ToFolderId.Item = id;
}
return copyFolderRequest;
}
/// <summary>
/// Generate the request message for operation "UpdateFolder".
/// </summary>
/// <param name="folderType">An array of folder types.</param>
/// <param name="updateType">An array of update folder types.</param>
/// <param name="folderIds">An array of folder Ids.</param>
/// <returns>Update folder request instance that will send to server.</returns>
protected UpdateFolderType GetUpdateFolderRequest(string[] folderType, string[] updateType, FolderIdType[] folderIds)
{
Site.Assert.AreEqual<int>(folderType.Length, folderIds.Length, "Folder type count should equal to folder id count!");
Site.Assert.AreEqual<int>(folderType.Length, updateType.Length, "Folder type count should equal to update type count!");
// UpdateFolder request.
UpdateFolderType updateFolderRequest = new UpdateFolderType();
int folderCount = folderIds.Length;
// Set the request's folder id field to Custom Folder's folder id.
updateFolderRequest.FolderChanges = new FolderChangeType[folderCount];
for (int folderIndex = 0; folderIndex < folderCount; folderIndex++)
{
updateFolderRequest.FolderChanges[folderIndex] = new FolderChangeType();
updateFolderRequest.FolderChanges[folderIndex].Item = folderIds[folderIndex];
// Add the array of changes; in this case, a single element array.
updateFolderRequest.FolderChanges[folderIndex].Updates = new FolderChangeDescriptionType[1];
switch (updateType[folderIndex])
{
case "SetFolderField":
{
// Set the new folder name of the specific folder.
SetFolderFieldType setFolderField = new SetFolderFieldType();
PathToUnindexedFieldType displayNameProp = new PathToUnindexedFieldType();
displayNameProp.FieldURI = UnindexedFieldURIType.folderDisplayName;
switch (folderType[folderIndex])
{
case "Folder":
FolderType updatedFolder = new FolderType();
updatedFolder.DisplayName = Common.GenerateResourceName(this.Site, "UpdatedFolder" + folderIndex);
setFolderField.Item1 = updatedFolder;
break;
case "CalendarFolder":
CalendarFolderType updatedCalendarFolder = new CalendarFolderType();
updatedCalendarFolder.DisplayName = Common.GenerateResourceName(this.Site, "UpdatedFolder" + folderIndex);
setFolderField.Item1 = updatedCalendarFolder;
break;
case "ContactsFolder":
CalendarFolderType updatedContactFolder = new CalendarFolderType();
updatedContactFolder.DisplayName = Common.GenerateResourceName(this.Site, "UpdatedFolder" + folderIndex);
setFolderField.Item1 = updatedContactFolder;
break;
case "SearchFolder":
CalendarFolderType updatedSearchFolder = new CalendarFolderType();
updatedSearchFolder.DisplayName = Common.GenerateResourceName(this.Site, "UpdatedFolder" + folderIndex);
setFolderField.Item1 = updatedSearchFolder;
break;
case "TasksFolder":
CalendarFolderType updatedTaskFolder = new CalendarFolderType();
updatedTaskFolder.DisplayName = Common.GenerateResourceName(this.Site, "UpdatedFolder" + folderIndex);
setFolderField.Item1 = updatedTaskFolder;
break;
default:
FolderType generalFolder = new FolderType();
generalFolder.DisplayName = Common.GenerateResourceName(this.Site, "UpdatedFolder" + folderIndex);
setFolderField.Item1 = generalFolder;
break;
}
setFolderField.Item = displayNameProp;
updateFolderRequest.FolderChanges[folderIndex].Updates[0] = setFolderField;
}
break;
case "DeleteFolderField":
{
// Use DeleteFolderFieldType.
DeleteFolderFieldType delFolder = new DeleteFolderFieldType();
PathToUnindexedFieldType delProp = new PathToUnindexedFieldType();
delProp.FieldURI = UnindexedFieldURIType.folderPermissionSet;
delFolder.Item = delProp;
updateFolderRequest.FolderChanges[folderIndex].Updates[0] = delFolder;
}
break;
case "AppendToFolderField":
{
// Use AppendToFolderFieldType.
AppendToFolderFieldType appendToFolderField = new AppendToFolderFieldType();
PathToUnindexedFieldType displayNameAppendTo = new PathToUnindexedFieldType();
displayNameAppendTo.FieldURI = UnindexedFieldURIType.calendarAdjacentMeetings;
appendToFolderField.Item = displayNameAppendTo;
FolderType folderAppendTo = new FolderType();
folderAppendTo.FolderId = folderIds[folderIndex];
appendToFolderField.Item1 = folderAppendTo;
updateFolderRequest.FolderChanges[folderIndex].Updates[0] = appendToFolderField;
}
break;
}
}
return updateFolderRequest;
}
/// <summary>
/// Generate the request message for operation "UpdateFolder".
/// </summary>
/// <param name="folderType">Identifies type of the folder.</param>
/// <param name="updateType">Identifies update type of the folder.</param>
/// <param name="folderId">The folder identifier of the folder need to be updated.</param>
/// <returns>Update folder request instance that will send to server.</returns>
protected UpdateFolderType GetUpdateFolderRequest(string folderType, string updateType, FolderIdType folderId)
{
UpdateFolderType updateFolderRequest = this.GetUpdateFolderRequest(new string[] { folderType }, new string[] { updateType }, new FolderIdType[] { folderId });
return updateFolderRequest;
}
/// <summary>
/// Switch from current user to a different user logon to mail box.
/// </summary>
/// <param name="logonUser">Name of the user that is about to logon to mail box.</param>
/// <param name="password">Password of the user that is about to logon to mail box.</param>
/// <param name="domainValue">Domain of the user that is about to logon to mail box..</param>
protected void SwitchUser(string logonUser, string password, string domainValue)
{
this.FOLDAdapter.SwitchUser(logonUser, password, domainValue);
this.COREAdapter.SwitchUser(logonUser, password, domainValue);
}
/// <summary>
/// Initialize folder permission related variables.
/// </summary>
protected void InitialPermissionVariables()
{
this.CanCreateSubFolder = false;
this.CanReadSubFolder = false;
this.CanEditSubFolder = false;
this.CanDeleteSubFolder = false;
this.CanCreateItem = false;
this.CanReadOwnedItem = false;
this.CanEditOwnedItem = false;
this.CanDeleteOwnedItem = false;
this.CanReadNotOwnedItem = false;
this.CanEditNotOwnedItem = false;
this.CanDeleteNotOwnedItem = false;
}
/// <summary>
/// Configure the SOAP header before calling operations.
/// </summary>
protected void ConfigureSOAPHeader()
{
// Set the value of MailboxCulture.
MailboxCultureType mailboxCulture = new MailboxCultureType();
string culture = Common.GetConfigurationPropertyValue("MailboxCulture", this.Site);
mailboxCulture.Value = culture;
// Set the value of ExchangeImpersonation.
ExchangeImpersonationType impersonation = new ExchangeImpersonationType();
impersonation.ConnectingSID = new ConnectingSIDType();
PrimarySmtpAddressType address = new PrimarySmtpAddressType();
address.Value = Common.GetConfigurationPropertyValue("User1Name", this.Site) + "@" + Common.GetConfigurationPropertyValue("Domain", this.Site);
impersonation.ConnectingSID.Item = address;
// Set time zone value.
TimeZoneDefinitionType timezoneDefin = new TimeZoneDefinitionType();
timezoneDefin.Id = "Eastern Standard Time";
TimeZoneContextType timezoneContext = new TimeZoneContextType();
timezoneContext.TimeZoneDefinition = timezoneDefin;
Dictionary<string, object> headerValues = new Dictionary<string, object>();
headerValues.Add("MailboxCulture", mailboxCulture);
headerValues.Add("ExchangeImpersonation", impersonation);
headerValues.Add("TimeZoneContext", timezoneContext);
this.FOLDAdapter.ConfigureSOAPHeader(headerValues);
}
/// <summary>
/// Validate if User has related permissions according to the permission level set on folder.
/// </summary>
/// <param name="permissionLevel">Permission level value.</param>
protected void ValidateFolderPermissionLevel(PermissionLevelType permissionLevel)
{
#region Create a folder in the User1's inbox folder, and set permission level value for User2
// Configure permission set.
PermissionSetType permissionSet = new PermissionSetType();
permissionSet.Permissions = new PermissionType[1];
permissionSet.Permissions[0] = new PermissionType();
permissionSet.Permissions[0].PermissionLevel = permissionLevel;
permissionSet.Permissions[0].UserId = new UserIdType();
permissionSet.Permissions[0].UserId.PrimarySmtpAddress = Common.GetConfigurationPropertyValue("User2Name", this.Site) + "@" + Common.GetConfigurationPropertyValue("Domain", this.Site);
// CreateFolder request.
CreateFolderType createFolderRequest = this.GetCreateFolderRequest(DistinguishedFolderIdNameType.inbox.ToString(), new string[] { "Custom Folder" }, new string[] { "IPF.MyCustomFolderClass" }, new PermissionSetType[] { permissionSet });
// Create a new folder.
CreateFolderResponseType createFolderResponse = this.FOLDAdapter.CreateFolder(createFolderRequest);
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, createFolderResponse.ResponseMessages.Items[0].ResponseClass, "Fold should be created successfully!");
// Save the new created folder's folder id.
FolderIdType newFolderId = ((FolderInfoResponseMessageType)createFolderResponse.ResponseMessages.Items[0]).Folders[0].FolderId;
this.NewCreatedFolderIds.Add(newFolderId);
#endregion
#region Create an item in the folder created in step 1 with User1's credential
string itemNameNotOwned = Common.GenerateResourceName(this.Site, "Test Mail");
// Create an item in the new created folder.
ItemIdType itemIdNotOwned = this.CreateItem(Common.GetConfigurationPropertyValue("User1Name", Site) + "@" + Common.GetConfigurationPropertyValue("Domain", Site), newFolderId.Id, itemNameNotOwned);
Site.Assert.IsNotNull(itemIdNotOwned, "Item should be created successfully!");
#endregion
#region Switch to User2
this.SwitchUser(Common.GetConfigurationPropertyValue("User2Name", this.Site), Common.GetConfigurationPropertyValue("User2Password", this.Site), Common.GetConfigurationPropertyValue("Domain", this.Site));
#endregion
#region Create a subfolder under the folder created in step 1 with User2's credential
// CreateFolder request.
CreateFolderType createFolderInSharedMailboxRequest = this.GetCreateFolderRequest(newFolderId.Id, new string[] { "Custom Folder" }, new string[] { "IPF.MyCustomFolderClass" }, null);
// Create a new folder.
CreateFolderResponseType createFolderInSharedMailboxResponse = this.FOLDAdapter.CreateFolder(createFolderInSharedMailboxRequest);
this.CanCreateSubFolder = ResponseClassType.Success == createFolderInSharedMailboxResponse.ResponseMessages.Items[0].ResponseClass;
#endregion
#region Edit items that User2 doesn't own with User2's credential
this.CanEditNotOwnedItem = this.UpdateItemSubject(itemIdNotOwned);
this.CanReadNotOwnedItem = this.GetItem(itemIdNotOwned);
this.CanDeleteNotOwnedItem = this.DeleteItem(itemIdNotOwned);
#endregion
#region Edit items that User2 owns with User2's credential
string itemNameOwned = Common.GenerateResourceName(this.Site, "Test Mail");
string user1MailBox = Common.GetConfigurationPropertyValue("User1Name", Site) + "@" + Common.GetConfigurationPropertyValue("Domain", Site);
ItemIdType itemIdOwned = this.CreateItem(user1MailBox, newFolderId.Id, itemNameOwned);
// If user can create items.
this.CanCreateItem = itemIdOwned != null;
if (this.CanCreateItem)
{
this.CanEditOwnedItem = this.UpdateItemSubject(itemIdOwned);
this.CanReadOwnedItem = this.GetItem(itemIdOwned);
this.CanDeleteOwnedItem = this.DeleteItem(itemIdOwned);
}
#endregion
#region Switch to User1
this.SwitchUser(Common.GetConfigurationPropertyValue("User1Name", this.Site), Common.GetConfigurationPropertyValue("User1Password", this.Site), Common.GetConfigurationPropertyValue("Domain", this.Site));
#endregion
}
#endregion
}
}
| |
/**
* Copyright 2015-2016 GetSocial B.V.
*
* 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 UnityEngine;
using System.IO;
using UnityEditor.iOS.Xcode.GetSocial;
using GetSocialSdk.Core;
using System.Linq;
using UnityEditor;
namespace GetSocialSdk.Editor
{
public static class GetSocialPostprocessIOS
{
private const int MinimumIosVersionRequirnment = 8;
public static void UpdateXcodeProject(string projectPath)
{
CheckIosVersion();
#if !UNITY_CLOUD_BUILD
Debug.Log(string.Format("GetSocial: Xcode postprocessing started for project '{0}'", projectPath));
#endif
PBXProjectUtils.ModifyPbxProject(projectPath, (project, target) =>
{
AddOtherLinkerFlags(project, target);
SetupDeepLinking(project, projectPath, target);
#if !UNITY_2018_3_OR_NEWER
EmbedFrameworks(project, target);
#endif
AddStripFrameworksScriptBuildPhase(project, projectPath, target);
if (GetSocialSettings.IsRichPushNotificationsEnabled && GetSocialSettings.IsIosPushEnabled)
{
AddNotificationExtension(project, projectPath);
}
project.CheckRuntimeSearchPath();
});
PBXProjectUtils.ModifyPlist(projectPath, (plistDocument) =>
{
WhitelistApps(plistDocument);
SetUiBackgroundModes(plistDocument);
DisableViewControllerBasedStatusBar(plistDocument);
});
}
static void AddNotificationExtension(PBXProject project, string projectPath)
{
#if UNITY_2018_1_OR_NEWER
const string extensionName = "/GetSocialNotificationExtension";
if (!Directory.Exists(projectPath + extensionName))
{
Directory.CreateDirectory(projectPath + extensionName);
}
var pluginDir = GetSocialSettings.GetPluginPath();
PlistDocument notificationServicePlist = new PlistDocument();
notificationServicePlist.ReadFromFile (pluginDir + "/Editor/iOS/Helpers/NotificationService/Info.plist");
notificationServicePlist.root.SetString ("CFBundleShortVersionString", PlayerSettings.bundleVersion);
notificationServicePlist.root.SetString ("CFBundleVersion", PlayerSettings.iOS.buildNumber);
notificationServicePlist.WriteToFile(projectPath + "/GetSocialNotificationExtension/Info.plist");
var extensionServiceSourceHeaderFile = pluginDir + "/Editor/iOS/Helpers/NotificationService/GetSocialNotificationService.h";
var extensionServiceSourceImpFile = pluginDir + "/Editor/iOS/Helpers/NotificationService/GetSocialNotificationService.m";
var extensionServiceTargetHeaderFile = "GetSocialNotificationExtension/GetSocialNotificationService.h";
var extensionServiceTargetImpFile = "GetSocialNotificationExtension/GetSocialNotificationService.m";
File.Copy(extensionServiceSourceHeaderFile, projectPath + "/" + extensionServiceTargetHeaderFile, true);
File.Copy(extensionServiceSourceImpFile, projectPath + "/" + extensionServiceTargetImpFile, true);
var mainTarget = project.TargetGuidByName(PBXProject.GetUnityTargetName());
var appExtensionTarget = project.AddAppExtension(mainTarget, "GetSocialNotificationExtension", projectPath + "/GetSocialNotificationExtension/Info.plist");
project.AddFileToBuild(appExtensionTarget, project.AddFile(extensionServiceTargetHeaderFile, extensionServiceTargetHeaderFile));
project.AddFileToBuild(appExtensionTarget, project.AddFile(extensionServiceTargetImpFile, extensionServiceTargetImpFile));
var frameworksPath =
GetSocialSettings.GetPluginPath().Substring(GetSocialSettings.GetPluginPath().IndexOf("/") + 1);
var relativeExtensionFrameworkPath = "Frameworks/" + frameworksPath + "/Plugins/iOS/GetSocialNotificationExtension.framework";
project.AddFileToBuild(appExtensionTarget, project.FindFileGuidByProjectPath(relativeExtensionFrameworkPath));
var deviceFamily = "";
switch (PlayerSettings.iOS.targetDevice)
{
case iOSTargetDevice.iPhoneOnly:
deviceFamily = "1";
break;
case iOSTargetDevice.iPadOnly:
deviceFamily = "2";
break;
case iOSTargetDevice.iPhoneAndiPad:
deviceFamily = "1,2";
break;
}
project.SetBuildProperty(appExtensionTarget, "TARGETED_DEVICE_FAMILY", deviceFamily);
if (double.Parse(PlayerSettings.iOS.targetOSVersionString) > 10)
{
project.SetBuildProperty(appExtensionTarget, "IPHONEOS_DEPLOYMENT_TARGET", PlayerSettings.iOS.targetOSVersionString.ToString());
} else
{
project.SetBuildProperty(appExtensionTarget, "IPHONEOS_DEPLOYMENT_TARGET", "10.0");
}
project.SetBuildProperty(appExtensionTarget, "DEVELOPMENT_TEAM", PlayerSettings.iOS.appleDeveloperTeamID);
project.SetBuildProperty(appExtensionTarget, "PRODUCT_BUNDLE_IDENTIFIER", GetSocialSettings.ExtensionBundleId);
project.SetBuildProperty(appExtensionTarget, "CODE_SIGN_STYLE", PlayerSettings.iOS.appleEnableAutomaticSigning ? "Automatic" : "Manual");
if (!PlayerSettings.iOS.appleEnableAutomaticSigning)
{
if (GetSocialSettings.ExtensionProvisioningProfile.Length == 0)
{
Debug.LogError("Notification Extension Provisioning Profile must be specified.");
}
else
{
project.SetBuildProperty(appExtensionTarget, "PROVISIONING_PROFILE", GetSocialSettings.ExtensionProvisioningProfile);
project.SetBuildProperty(appExtensionTarget, "PROVISIONING_PROFILE_SPECIFIER", GetSocialSettings.ExtensionProvisioningProfile);
}
}
project.AddFrameworkToProject(mainTarget, "UserNotifications.framework", false);
AddExtensionEntitlements(projectPath, project, appExtensionTarget);
#endif
}
static void AddExtensionEntitlements(string projectPath, PBXProject project, string target)
{
var entitlementsSetting = "extension.entitlements";
project.AddFileToBuild(target,
project.AddFile("extension.entitlements", entitlementsSetting, PBXSourceTree.Source));
project.AddBuildProperty(target, "CODE_SIGN_ENTITLEMENTS", entitlementsSetting);
var entitlementsFilePath = Path.Combine(projectPath, entitlementsSetting);
var entitlements = new PlistDocument();
if (File.Exists(entitlementsFilePath))
{
entitlements.ReadFromFile(entitlementsFilePath);
}
ConfigureAppGroups(entitlements);
entitlements.WriteToFile(entitlementsFilePath);
}
static void AddOtherLinkerFlags(PBXProject project, string target)
{
project.UpdateBuildProperty(target, "OTHER_LDFLAGS", new[]
{
"-ObjC",
"-licucore"
}, new string[] { });
project.SetBuildProperty(target, "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES", "YES");
}
static void AddStripFrameworksScriptBuildPhase(PBXProject project, string projectPath, string target)
{
// remove previous script versions
project.RemoveShellScript(target, "GetSocial.framework/strip_frameworks.sh");
}
static void EmbedFrameworks(PBXProject project, string target)
{
const string coreFrameworkName = "GetSocialSDK.framework";
const string uiFrameworkName = "GetSocialUI.framework";
const string extensionFrameworkName = "GetSocialNotificationExtension.framework";
var frameworksPath =
GetSocialSettings.GetPluginPath().Substring(GetSocialSettings.GetPluginPath().IndexOf("/") + 1);
var defaultLocationInProj = "Frameworks/" + frameworksPath + "/Plugins/iOS/";
var relativeCoreFrameworkPath = defaultLocationInProj + coreFrameworkName;
var relativeExtensionFrameworkPath = defaultLocationInProj + extensionFrameworkName;
var relativeUiFrameworkPath = defaultLocationInProj + uiFrameworkName;
project.AddDynamicFrameworkToProject(target, relativeCoreFrameworkPath);
project.AddDynamicFrameworkToProject(target, relativeExtensionFrameworkPath);
project.AddDynamicFrameworkToProject(target, relativeUiFrameworkPath);
#if !UNITY_CLOUD_BUILD
Debug.Log("GetSocial: GetSocial Dynamic Frameworks added to Embedded binaries.");
#endif
}
#region deep_linking
static void SetupDeepLinking(PBXProject project, string projectPath, string target)
{
#if !UNITY_CLOUD_BUILD
Debug.Log(
"[GetSocial] Setting up deep linking...\n\tFor universal links setup please refer to https://docs.getsocial.im/guides/smart-links/receive-smart-links/unity/");
#endif
// URL Schemes (iOS <= 8)
AddGetSocialUrlScheme(projectPath);
// App links (iOS >=9 )
AddAppEntitlements(projectPath, project, target);
}
static void AddGetSocialUrlScheme(string projectPath)
{
#if !UNITY_CLOUD_BUILD
Debug.Log(string.Format("[GetSocial] Setting up GetSocial deep linking for iOS <= 8 for '{0}'", projectPath));
#endif
PBXProjectUtils.ModifyPlist(projectPath, AddGetSocialUrlSchemeToPlist,
"Failed to set up GetSocial deep linking for iOS <= 8.");
}
static void AddGetSocialUrlSchemeToPlist(PlistDocument plistInfoFile)
{
const string CFBundleURLTypes = "CFBundleURLTypes";
const string CFBundleURLSchemes = "CFBundleURLSchemes";
if (!plistInfoFile.ContainsKey(CFBundleURLTypes))
{
plistInfoFile.root.CreateArray(CFBundleURLTypes);
}
var cFBundleURLTypesElem = plistInfoFile.root.values[CFBundleURLTypes] as PlistElementArray;
var getSocialUrlSchemesArray = new PlistElementArray();
getSocialUrlSchemesArray.AddString(string.Format("getsocial-{0}", GetSocialSettings.AppId));
if (cFBundleURLTypesElem != null)
{
var getSocialSchemeElem = cFBundleURLTypesElem.AddDict();
getSocialSchemeElem.values[CFBundleURLSchemes] = getSocialUrlSchemesArray;
}
}
static void AddAppEntitlements(string projectPath, PBXProject project, string target)
{
var toCreate = false;
var existingEntitlementsFiles = project.GetBuildPropertyValues(target, "CODE_SIGN_ENTITLEMENTS");
if (existingEntitlementsFiles.Count == 0)
{
project.AddFileToBuild(target,
project.AddFile("app.entitlements", "app.entitlements", PBXSourceTree.Source));
project.AddBuildProperty(target, "CODE_SIGN_ENTITLEMENTS", "app.entitlements");
existingEntitlementsFiles.Add("app.entitlements");
toCreate = true;
}
foreach (var entitlementsSetting in existingEntitlementsFiles)
{
var entitlementsParts = entitlementsSetting.Split(' ');
foreach (var entitlementsPart in entitlementsParts)
{
var entitlementsFilePath = Path.Combine(projectPath, entitlementsSetting);
if (!File.Exists(entitlementsFilePath) && !toCreate)
{
if (File.Exists(entitlementsSetting))
{
entitlementsFilePath = entitlementsSetting;
} else {
continue;
}
}
var entitlements = new PlistDocument();
if (File.Exists(entitlementsFilePath))
{
entitlements.ReadFromFile(entitlementsFilePath);
}
if (GetSocialSettings.IsRichPushNotificationsEnabled && GetSocialSettings.IsIosPushEnabled)
{
ConfigureAppGroups(entitlements);
}
ConfigureAssociatedDomains(entitlements);
ConfigurePushNotifications(entitlements);
entitlements.WriteToFile(entitlementsFilePath);
}
}
}
private static void ConfigureAppGroups(PlistDocument entitlements)
{
var appGroupsNode = entitlements.root["com.apple.security.application-groups"] != null
? entitlements.root["com.apple.security.application-groups"].AsArray()
: entitlements.root.CreateArray("com.apple.security.application-groups");
appGroupsNode.AddString(string.Format("group.{0}.getsocial_extension", Application.identifier));
}
public static void ConfigureAssociatedDomains(PlistDocument entitlements)
{
// Universal Links
var associatedDomainsNode = entitlements.root["com.apple.developer.associated-domains"] != null
? entitlements.root["com.apple.developer.associated-domains"].AsArray()
: entitlements.root.CreateArray("com.apple.developer.associated-domains");
GetSocialSettings.DeeplinkingDomains.ForEach(domain =>
{
var valueToAdd = string.Format("applinks:{0}", domain);
var addValue = associatedDomainsNode.values.All(existingValue => !existingValue.AsString().Equals(valueToAdd));
if (addValue)
{
associatedDomainsNode.AddString(valueToAdd);
}
});
}
public static void ConfigurePushNotifications(PlistDocument entitlements)
{
// Push Environment
if (!GetSocialSettings.IsIosPushEnabled) return;
// read current value
var currentPushSettings = entitlements.ContainsKey("aps-environment")
? entitlements.root["aps-environment"].AsString()
: null;
if (currentPushSettings != null && !GetSocialSettings.IosPushEnvironment.Equals(currentPushSettings))
{
// show warning
Debug.LogWarning("[GetSocial] Push notification settings are different, check the settings in the GetSocial Dashboard at http://dashboard.getsocial.im .");
}
if (currentPushSettings == null)
{
entitlements.root.SetString("aps-environment", GetSocialSettings.IosPushEnvironment);
}
}
#endregion
private static void DisableViewControllerBasedStatusBar(PlistDocument plistDocument)
{
plistDocument.root.SetString("UIViewControllerBasedStatusBarAppearance", "NO");
}
static void WhitelistApps(PlistDocument plistInfoFile)
{
const string LSApplicationQueriesSchemes = "LSApplicationQueriesSchemes";
string[] fbApps =
{
"fbapi",
"fbapi20130214",
"fbapi20130410",
"fbapi20130702",
"fbapi20131010",
"fbapi20131219",
"fbapi20140410",
"fbapi20140116",
"fbapi20150313",
"fbapi20150629",
"fbauth",
"fbauth2",
"fb-messenger-api20140430",
"fb-messenger-api",
"fb-messenger-share-api",
"fbshareextension"
};
string[] otherApps =
{
"kik-share",
"kakaolink",
"line",
"whatsapp",
"viber",
"tg",
"instagram-stories",
"facebook-stories"
};
PlistElementArray existingSchemes = plistInfoFile.root[LSApplicationQueriesSchemes] as PlistElementArray;
if (existingSchemes == null)
{
existingSchemes = plistInfoFile.root.CreateArray(LSApplicationQueriesSchemes);
}
MergePlistArrays(existingSchemes, fbApps);
MergePlistArrays(existingSchemes, otherApps);
}
private static void MergePlistArrays(PlistElementArray originalArray, string[] newArray)
{
newArray.ToList().ForEach((entry) => {
var contains = false;
originalArray.values.ForEach((plistElement) => {
if (plistElement.AsString().Equals(entry))
{
contains = true;
}
});
if (!contains)
{
originalArray.AddString(entry);
}
});
}
private static void SetUiBackgroundModes(PlistDocument plistDocument)
{
var backgroundModesArray = plistDocument.root.CreateArray("UIBackgroundModes");
backgroundModesArray.AddString("remote-notification");
}
private static void CheckIosVersion()
{
var targetIosVersion = PlayerSettings.iOS.targetOSVersionString;
try
{
var iosMajorVersionString = targetIosVersion.Split('.')[0];
if (int.Parse(iosMajorVersionString) < MinimumIosVersionRequirnment)
{
Debug.LogWarning(string.Format(
"GetSocial: Target iOS version {0} is not supported. GetSocial SDK requires iOS {1}+",
targetIosVersion, MinimumIosVersionRequirnment));
}
}
catch (Exception)
{
Debug.LogWarning(string.Format(
"GetSocial: failed to parse target iOS version.. GetSocial SDK requires iOS {0}+", MinimumIosVersionRequirnment));
}
}
}
}
| |
/*
* 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 cloudfront-2015-07-27.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.CloudFront.Model
{
/// <summary>
/// A summary of the information for an Amazon CloudFront distribution.
/// </summary>
public partial class DistributionSummary
{
private Aliases _aliases;
private CacheBehaviors _cacheBehaviors;
private string _comment;
private CustomErrorResponses _customErrorResponses;
private DefaultCacheBehavior _defaultCacheBehavior;
private string _domainName;
private bool? _enabled;
private string _id;
private DateTime? _lastModifiedTime;
private Origins _origins;
private PriceClass _priceClass;
private Restrictions _restrictions;
private string _status;
private ViewerCertificate _viewerCertificate;
private string _webACLId;
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public DistributionSummary() { }
/// <summary>
/// Gets and sets the property Aliases. A complex type that contains information about
/// CNAMEs (alternate domain names), if any, for this distribution.
/// </summary>
public Aliases Aliases
{
get { return this._aliases; }
set { this._aliases = value; }
}
// Check to see if Aliases property is set
internal bool IsSetAliases()
{
return this._aliases != null;
}
/// <summary>
/// Gets and sets the property CacheBehaviors. A complex type that contains zero or more
/// CacheBehavior elements.
/// </summary>
public CacheBehaviors CacheBehaviors
{
get { return this._cacheBehaviors; }
set { this._cacheBehaviors = value; }
}
// Check to see if CacheBehaviors property is set
internal bool IsSetCacheBehaviors()
{
return this._cacheBehaviors != null;
}
/// <summary>
/// Gets and sets the property Comment. The comment originally specified when this distribution
/// was created.
/// </summary>
public string Comment
{
get { return this._comment; }
set { this._comment = value; }
}
// Check to see if Comment property is set
internal bool IsSetComment()
{
return this._comment != null;
}
/// <summary>
/// Gets and sets the property CustomErrorResponses. A complex type that contains zero
/// or more CustomErrorResponses elements.
/// </summary>
public CustomErrorResponses CustomErrorResponses
{
get { return this._customErrorResponses; }
set { this._customErrorResponses = value; }
}
// Check to see if CustomErrorResponses property is set
internal bool IsSetCustomErrorResponses()
{
return this._customErrorResponses != null;
}
/// <summary>
/// Gets and sets the property DefaultCacheBehavior. A complex type that describes the
/// default cache behavior if you do not specify a CacheBehavior element or if files don't
/// match any of the values of PathPattern in CacheBehavior elements.You must create exactly
/// one default cache behavior.
/// </summary>
public DefaultCacheBehavior DefaultCacheBehavior
{
get { return this._defaultCacheBehavior; }
set { this._defaultCacheBehavior = value; }
}
// Check to see if DefaultCacheBehavior property is set
internal bool IsSetDefaultCacheBehavior()
{
return this._defaultCacheBehavior != null;
}
/// <summary>
/// Gets and sets the property DomainName. The domain name corresponding to the distribution.
/// For example: d604721fxaaqy9.cloudfront.net.
/// </summary>
public string DomainName
{
get { return this._domainName; }
set { this._domainName = value; }
}
// Check to see if DomainName property is set
internal bool IsSetDomainName()
{
return this._domainName != null;
}
/// <summary>
/// Gets and sets the property Enabled. Whether the distribution is enabled to accept
/// end user requests for content.
/// </summary>
public bool Enabled
{
get { return this._enabled.GetValueOrDefault(); }
set { this._enabled = value; }
}
// Check to see if Enabled property is set
internal bool IsSetEnabled()
{
return this._enabled.HasValue;
}
/// <summary>
/// Gets and sets the property Id. The identifier for the distribution. For example: EDFDVBD632BHDS5.
/// </summary>
public string Id
{
get { return this._id; }
set { this._id = value; }
}
// Check to see if Id property is set
internal bool IsSetId()
{
return this._id != null;
}
/// <summary>
/// Gets and sets the property LastModifiedTime. The date and time the distribution was
/// last modified.
/// </summary>
public DateTime LastModifiedTime
{
get { return this._lastModifiedTime.GetValueOrDefault(); }
set { this._lastModifiedTime = value; }
}
// Check to see if LastModifiedTime property is set
internal bool IsSetLastModifiedTime()
{
return this._lastModifiedTime.HasValue;
}
/// <summary>
/// Gets and sets the property Origins. A complex type that contains information about
/// origins for this distribution.
/// </summary>
public Origins Origins
{
get { return this._origins; }
set { this._origins = value; }
}
// Check to see if Origins property is set
internal bool IsSetOrigins()
{
return this._origins != null;
}
/// <summary>
/// Gets and sets the property PriceClass.
/// </summary>
public PriceClass PriceClass
{
get { return this._priceClass; }
set { this._priceClass = value; }
}
// Check to see if PriceClass property is set
internal bool IsSetPriceClass()
{
return this._priceClass != null;
}
/// <summary>
/// Gets and sets the property Restrictions.
/// </summary>
public Restrictions Restrictions
{
get { return this._restrictions; }
set { this._restrictions = value; }
}
// Check to see if Restrictions property is set
internal bool IsSetRestrictions()
{
return this._restrictions != null;
}
/// <summary>
/// Gets and sets the property Status. This response element indicates the current status
/// of the distribution. When the status is Deployed, the distribution's information is
/// fully propagated throughout the Amazon CloudFront system.
/// </summary>
public string Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
/// <summary>
/// Gets and sets the property ViewerCertificate.
/// </summary>
public ViewerCertificate ViewerCertificate
{
get { return this._viewerCertificate; }
set { this._viewerCertificate = value; }
}
// Check to see if ViewerCertificate property is set
internal bool IsSetViewerCertificate()
{
return this._viewerCertificate != null;
}
/// <summary>
/// Gets and sets the property WebACLId. The Web ACL Id (if any) associated with the distribution.
/// </summary>
public string WebACLId
{
get { return this._webACLId; }
set { this._webACLId = value; }
}
// Check to see if WebACLId property is set
internal bool IsSetWebACLId()
{
return this._webACLId != null;
}
}
}
| |
using Anycmd.Xacml.Context;
using System;
using System.Reflection;
using con = Anycmd.Xacml.Context;
namespace Anycmd.Xacml.ControlCenter.ContextCustomControls
{
/// <summary>
/// Summary description for Attribute.
/// </summary>
public class Attribute : CustomControls.BaseControl
{
private System.Windows.Forms.Button btnAdd;
private System.Windows.Forms.Button btnRemove;
private con.AttributeElementReadWrite _attribute;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtId;
private System.Windows.Forms.GroupBox grpAttribute;
private System.Windows.Forms.ComboBox cmbDataType;
private System.Windows.Forms.TextBox txtIssuer;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.GroupBox grpAttributeValue;
private System.Windows.Forms.ListBox lstAttributeValue;
private System.Windows.Forms.TextBox txtValue;
private System.Windows.Forms.Label label5;
private System.ComponentModel.Container components = null;
private int index = -1;
/// <summary>
///
/// </summary>
/// <param name="attribute"></param>
public Attribute( con.AttributeElementReadWrite attribute )
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
LoadingData = true;
_attribute = attribute;
foreach( FieldInfo field in typeof(Consts.Schema1.InternalDataTypes).GetFields() )
{
cmbDataType.Items.Add( field.GetValue( null ) );
}
this.lstAttributeValue.DisplayMember = "Value";
foreach( con.AttributeValueElementReadWrite attr in _attribute.AttributeValues )
{
lstAttributeValue.Items.Add( attr );
}
if( _attribute.AttributeValues.Count != 0 )
{
lstAttributeValue.SelectedIndex = 0;
}
txtId.Text = _attribute.AttributeId;
txtId.DataBindings.Add( "Text", _attribute, "AttributeId" );
txtIssuer.Text = _attribute.Issuer;
//txtIssuer.DataBindings.Add( "Text", _attribute, "Issuer" );
cmbDataType.SelectedIndex = cmbDataType.FindStringExact( _attribute.DataType);
cmbDataType.DataBindings.Add( "SelectedItem", _attribute, "DataType" );
LoadingData = false;
}
/// <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 Component 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.grpAttributeValue = new System.Windows.Forms.GroupBox();
this.lstAttributeValue = new System.Windows.Forms.ListBox();
this.btnRemove = new System.Windows.Forms.Button();
this.btnAdd = new System.Windows.Forms.Button();
this.txtValue = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.grpAttribute = new System.Windows.Forms.GroupBox();
this.txtIssuer = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.cmbDataType = new System.Windows.Forms.ComboBox();
this.txtId = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.grpAttributeValue.SuspendLayout();
this.grpAttribute.SuspendLayout();
this.SuspendLayout();
//
// grpAttributeValue
//
this.grpAttributeValue.Controls.Add(this.lstAttributeValue);
this.grpAttributeValue.Controls.Add(this.btnRemove);
this.grpAttributeValue.Controls.Add(this.btnAdd);
this.grpAttributeValue.Controls.Add(this.txtValue);
this.grpAttributeValue.Controls.Add(this.label5);
this.grpAttributeValue.Location = new System.Drawing.Point(8, 160);
this.grpAttributeValue.Name = "grpAttributeValue";
this.grpAttributeValue.Size = new System.Drawing.Size(576, 152);
this.grpAttributeValue.TabIndex = 2;
this.grpAttributeValue.TabStop = false;
this.grpAttributeValue.Text = "Attribute value";
//
// lstAttributeValue
//
this.lstAttributeValue.Location = new System.Drawing.Point(8, 16);
this.lstAttributeValue.Name = "lstAttributeValue";
this.lstAttributeValue.Size = new System.Drawing.Size(472, 82);
this.lstAttributeValue.TabIndex = 5;
this.lstAttributeValue.SelectedIndexChanged += new System.EventHandler(this.lstAttributeValue_SelectedIndexChanged);
//
// btnRemove
//
this.btnRemove.Location = new System.Drawing.Point(488, 56);
this.btnRemove.Name = "btnRemove";
this.btnRemove.TabIndex = 2;
this.btnRemove.Text = "Remove";
this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click);
//
// btnAdd
//
this.btnAdd.Location = new System.Drawing.Point(488, 24);
this.btnAdd.Name = "btnAdd";
this.btnAdd.TabIndex = 1;
this.btnAdd.Text = "Add";
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
//
// txtValue
//
this.txtValue.Location = new System.Drawing.Point(80, 120);
this.txtValue.Name = "txtValue";
this.txtValue.Size = new System.Drawing.Size(488, 20);
this.txtValue.TabIndex = 9;
this.txtValue.Text = "";
//
// label5
//
this.label5.Location = new System.Drawing.Point(8, 120);
this.label5.Name = "label5";
this.label5.TabIndex = 8;
this.label5.Text = "Value:";
//
// grpAttribute
//
this.grpAttribute.Controls.Add(this.txtIssuer);
this.grpAttribute.Controls.Add(this.label3);
this.grpAttribute.Controls.Add(this.cmbDataType);
this.grpAttribute.Controls.Add(this.txtId);
this.grpAttribute.Controls.Add(this.label2);
this.grpAttribute.Controls.Add(this.label1);
this.grpAttribute.Location = new System.Drawing.Point(8, 8);
this.grpAttribute.Name = "grpAttribute";
this.grpAttribute.Size = new System.Drawing.Size(576, 128);
this.grpAttribute.TabIndex = 3;
this.grpAttribute.TabStop = false;
this.grpAttribute.Text = "Attribute";
//
// txtIssuer
//
this.txtIssuer.Location = new System.Drawing.Point(80, 80);
this.txtIssuer.Name = "txtIssuer";
this.txtIssuer.Size = new System.Drawing.Size(488, 20);
this.txtIssuer.TabIndex = 5;
this.txtIssuer.Text = "";
//
// label3
//
this.label3.Location = new System.Drawing.Point(8, 80);
this.label3.Name = "label3";
this.label3.TabIndex = 4;
this.label3.Text = "Issuer:";
//
// cmbDataType
//
this.cmbDataType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbDataType.Location = new System.Drawing.Point(80, 48);
this.cmbDataType.Name = "cmbDataType";
this.cmbDataType.Size = new System.Drawing.Size(488, 21);
this.cmbDataType.TabIndex = 3;
this.cmbDataType.SelectedIndexChanged += cmbDataType_SelectedIndexChanged;
//
// txtId
//
this.txtId.Location = new System.Drawing.Point(80, 16);
this.txtId.Name = "txtId";
this.txtId.Size = new System.Drawing.Size(488, 20);
this.txtId.TabIndex = 2;
this.txtId.Text = "";
this.txtId.TextChanged += txtId_TextChanged;
//
// label2
//
this.label2.Location = new System.Drawing.Point(8, 48);
this.label2.Name = "label2";
this.label2.TabIndex = 1;
this.label2.Text = "Data type:";
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 16);
this.label1.Name = "label1";
this.label1.TabIndex = 0;
this.label1.Text = "Attribute id:";
//
// Attribute
//
this.Controls.Add(this.grpAttribute);
this.Controls.Add(this.grpAttributeValue);
this.Name = "Attribute";
this.Size = new System.Drawing.Size(592, 328);
this.grpAttributeValue.ResumeLayout(false);
this.grpAttribute.ResumeLayout(false);
this.ResumeLayout(false);
}
private void txtId_TextChanged(object sender, EventArgs e)
{
base.TextBox_TextChanged(sender, e);
}
private void cmbDataType_SelectedIndexChanged(object sender, EventArgs e)
{
base.ComboBox_SelectedIndexChanged(sender, e);
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAdd_Click(object sender, System.EventArgs e)
{
LoadingData = true;
con.AttributeValueElementReadWrite att = new AttributeValueElementReadWrite( "TODO: Add value", Xacml.XacmlVersion.Version11 );
lstAttributeValue.Items.Add(att);
_attribute.AttributeValues.Add( att );
LoadingData = false;
}
private void btnRemove_Click(object sender, System.EventArgs e)
{
con.AttributeValueElementReadWrite attr = lstAttributeValue.SelectedItem as con.AttributeValueElementReadWrite;
try
{
LoadingData = true;
txtValue.Text = string.Empty;
_attribute.AttributeValues.RemoveAt(lstAttributeValue.SelectedIndex);
lstAttributeValue.Items.RemoveAt(lstAttributeValue.SelectedIndex);
}
finally
{
LoadingData = false;
}
}
private void lstAttributeValue_SelectedIndexChanged(object sender, System.EventArgs e)
{
if( index != lstAttributeValue.SelectedIndex )
{
if( index != -1 )
{
con.AttributeValueElementReadWrite attrAux = lstAttributeValue.Items[index] as con.AttributeValueElementReadWrite;
attrAux.Value = txtValue.Text;
lstAttributeValue.Items.RemoveAt( index );
lstAttributeValue.Items.Insert( index, attrAux );
}
if(!LoadingData)
{
try
{
LoadingData = true;
index = lstAttributeValue.SelectedIndex;
con.AttributeValueElementReadWrite attribute = lstAttributeValue.SelectedItem as con.AttributeValueElementReadWrite;
if( attribute != null )
{
txtValue.Text = attribute.Value;
}
}
finally
{
LoadingData = false;
}
}
else
{
index = -1;
}
}
}
/// <summary>
/// Gets the element
/// </summary>
public con.AttributeElementReadWrite AttributeElement
{
get
{
if( index != -1 )
{
con.AttributeValueElementReadWrite attAux = lstAttributeValue.Items[index] as con.AttributeValueElementReadWrite;
attAux.Value = txtValue.Text;
}
_attribute.AttributeId = txtId.Text;
_attribute.DataType = cmbDataType.Text;
_attribute.Issuer = txtIssuer.Text;
return _attribute;
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Insights;
using Microsoft.Azure.Management.Insights.Models;
namespace Microsoft.Azure.Management.Insights
{
public static partial class AlertOperationsExtensions
{
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Insights.IAlertOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='parameters'>
/// Required. The rule to create or update.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse CreateOrUpdateRule(this IAlertOperations operations, string resourceGroupName, RuleCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAlertOperations)s).CreateOrUpdateRuleAsync(resourceGroupName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Insights.IAlertOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='parameters'>
/// Required. The rule to create or update.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> CreateOrUpdateRuleAsync(this IAlertOperations operations, string resourceGroupName, RuleCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateRuleAsync(resourceGroupName, parameters, CancellationToken.None);
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Insights.IAlertOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='ruleName'>
/// Required. The name of the rule to delete.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse DeleteRule(this IAlertOperations operations, string resourceGroupName, string ruleName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAlertOperations)s).DeleteRuleAsync(resourceGroupName, ruleName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Insights.IAlertOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='ruleName'>
/// Required. The name of the rule to delete.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteRuleAsync(this IAlertOperations operations, string resourceGroupName, string ruleName)
{
return operations.DeleteRuleAsync(resourceGroupName, ruleName, CancellationToken.None);
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Insights.IAlertOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='ruleName'>
/// Required. The name of the rule.
/// </param>
/// <param name='incidentName'>
/// Required. The name of the incident to retrieve.
/// </param>
/// <returns>
/// The Get Incident operation response.
/// </returns>
public static IncidentGetResponse GetIncident(this IAlertOperations operations, string resourceGroupName, string ruleName, string incidentName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAlertOperations)s).GetIncidentAsync(resourceGroupName, ruleName, incidentName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Insights.IAlertOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='ruleName'>
/// Required. The name of the rule.
/// </param>
/// <param name='incidentName'>
/// Required. The name of the incident to retrieve.
/// </param>
/// <returns>
/// The Get Incident operation response.
/// </returns>
public static Task<IncidentGetResponse> GetIncidentAsync(this IAlertOperations operations, string resourceGroupName, string ruleName, string incidentName)
{
return operations.GetIncidentAsync(resourceGroupName, ruleName, incidentName, CancellationToken.None);
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Insights.IAlertOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='ruleName'>
/// Required. The name of the rule to retrieve.
/// </param>
/// <returns>
/// The Get Rule operation response.
/// </returns>
public static RuleGetResponse GetRule(this IAlertOperations operations, string resourceGroupName, string ruleName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAlertOperations)s).GetRuleAsync(resourceGroupName, ruleName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Insights.IAlertOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='ruleName'>
/// Required. The name of the rule to retrieve.
/// </param>
/// <returns>
/// The Get Rule operation response.
/// </returns>
public static Task<RuleGetResponse> GetRuleAsync(this IAlertOperations operations, string resourceGroupName, string ruleName)
{
return operations.GetRuleAsync(resourceGroupName, ruleName, CancellationToken.None);
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Insights.IAlertOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='ruleName'>
/// Required. The name of the rule.
/// </param>
/// <returns>
/// The List incidents operation response.
/// </returns>
public static IncidentListResponse ListIncidentsForRule(this IAlertOperations operations, string resourceGroupName, string ruleName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAlertOperations)s).ListIncidentsForRuleAsync(resourceGroupName, ruleName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Insights.IAlertOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='ruleName'>
/// Required. The name of the rule.
/// </param>
/// <returns>
/// The List incidents operation response.
/// </returns>
public static Task<IncidentListResponse> ListIncidentsForRuleAsync(this IAlertOperations operations, string resourceGroupName, string ruleName)
{
return operations.ListIncidentsForRuleAsync(resourceGroupName, ruleName, CancellationToken.None);
}
/// <summary>
/// List the alert rules within a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Insights.IAlertOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='targetResourceUri'>
/// Optional. The resource identifier of the target of the alert rule.
/// </param>
/// <returns>
/// The List Rules operation response.
/// </returns>
public static RuleListResponse ListRules(this IAlertOperations operations, string resourceGroupName, string targetResourceUri)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAlertOperations)s).ListRulesAsync(resourceGroupName, targetResourceUri);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List the alert rules within a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Insights.IAlertOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='targetResourceUri'>
/// Optional. The resource identifier of the target of the alert rule.
/// </param>
/// <returns>
/// The List Rules operation response.
/// </returns>
public static Task<RuleListResponse> ListRulesAsync(this IAlertOperations operations, string resourceGroupName, string targetResourceUri)
{
return operations.ListRulesAsync(resourceGroupName, targetResourceUri, CancellationToken.None);
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Insights.IAlertOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='parameters'>
/// Required. The rule to update.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse UpdateRule(this IAlertOperations operations, string resourceGroupName, RuleCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAlertOperations)s).UpdateRuleAsync(resourceGroupName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Insights.IAlertOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='parameters'>
/// Required. The rule to update.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> UpdateRuleAsync(this IAlertOperations operations, string resourceGroupName, RuleCreateOrUpdateParameters parameters)
{
return operations.UpdateRuleAsync(resourceGroupName, parameters, CancellationToken.None);
}
}
}
| |
using GraphQL.Validation.Errors;
using GraphQL.Validation.Rules;
using Xunit;
namespace GraphQL.Tests.Validation
{
public class PossibleFragmentSpreadsTests : ValidationTestBase<PossibleFragmentSpreads, ValidationSchema>
{
[Fact]
public void of_the_same_object()
{
ShouldPassRule(@"
fragment objectWithinObject on Dog { ...dogFragment }
fragment dogFragment on Dog { barkVolume }
");
}
[Fact]
public void of_the_same_object_with_inline_fragment()
{
ShouldPassRule(@"
fragment objectWithinObjectAnon on Dog { ... on Dog { barkVolume } }
");
}
[Fact]
public void object_into_an_implemented_interface()
{
ShouldPassRule(@"
fragment objectWithinInterface on Pet { ...dogFragment }
fragment dogFragment on Dog { barkVolume }
");
}
[Fact]
public void object_into_containing_union()
{
ShouldPassRule(@"
fragment objectWithinUnion on CatOrDog { ...dogFragment }
fragment dogFragment on Dog { barkVolume }
");
}
[Fact]
public void union_into_contained_object()
{
ShouldPassRule(@"
fragment unionWithinObject on Dog { ...catOrDogFragment }
fragment catOrDogFragment on CatOrDog { __typename }
");
}
[Fact]
public void union_into_overlapping_interface()
{
ShouldPassRule(@"
fragment unionWithinInterface on Pet { ...catOrDogFragment }
fragment catOrDogFragment on CatOrDog { __typename }
");
}
[Fact]
public void union_into_overlapping_union()
{
ShouldPassRule(@"
fragment unionWithinUnion on DogOrHuman { ...catOrDogFragment }
fragment catOrDogFragment on CatOrDog { __typename }
");
}
[Fact]
public void interface_into_implemented_object()
{
ShouldPassRule(@"
fragment interfaceWithinObject on Dog { ...petFragment }
fragment petFragment on Pet { name }
");
}
[Fact]
public void interface_into_overlapping_interface()
{
ShouldPassRule(@"
fragment interfaceWithinInterface on Pet { ...beingFragment }
fragment beingFragment on Being { name }
");
}
[Fact]
public void interface_into_overlapping_interface_in_inline_fragment()
{
ShouldPassRule(@"
fragment interfaceWithinInterface on Pet { ... on Being { name } }
");
}
[Fact]
public void interface_into_overlapping_union()
{
ShouldPassRule(@"
fragment interfaceWithinUnion on CatOrDog { ...petFragment }
fragment petFragment on Pet { name }
");
}
[Fact]
public void different_object_into_object()
{
ShouldFailRule(_ =>
{
_.Query = @"
fragment invalidObjectWithinObject on Cat { ...dogFragment }
fragment dogFragment on Dog { barkVolume }
";
error(_, "dogFragment", "Cat", "Dog", 2, 65);
});
}
[Fact]
public void different_object_into_object_in_inline_fragment()
{
ShouldFailRule(_ =>
{
_.Query = @"
fragment invalidObjectWithinObjectAnon on Cat {
... on Dog { barkVolume }
}
";
errorAnon(_, "Cat", "Dog", 3, 21);
});
}
[Fact]
public void object_into_no_implementing_interface()
{
ShouldFailRule(_ =>
{
_.Query = @"
fragment invalidObjectWithinInterface on Pet { ...humanFragment }
fragment humanFragment on Human { pets { name } }
";
error(_, "humanFragment", "Pet", "Human", 2, 66);
});
}
[Fact]
public void object_into_not_containing_union()
{
ShouldFailRule(_ =>
{
_.Query = @"
fragment invalidObjectWithinUnion on CatOrDog { ...humanFragment }
fragment humanFragment on Human { pets { name } }
";
error(_, "humanFragment", "CatOrDog", "Human", 2, 67);
});
}
[Fact]
public void union_into_not_contained_object()
{
ShouldFailRule(_ =>
{
_.Query = @"
fragment invalidUnionWithinObject on Human { ...catOrDogFragment }
fragment catOrDogFragment on CatOrDog { __typename }
";
error(_, "catOrDogFragment", "Human", "CatOrDog", 2, 64);
});
}
[Fact]
public void union_into_non_overlapping_interface()
{
ShouldFailRule(_ =>
{
_.Query = @"
fragment invalidUnionWithinInterface on Pet { ...humanOrAlienFragment }
fragment humanOrAlienFragment on HumanOrAlien { __typename }
";
error(_, "humanOrAlienFragment", "Pet", "HumanOrAlien", 2, 65);
});
}
[Fact]
public void union_into_non_overlapping_union()
{
ShouldFailRule(_ =>
{
_.Query = @"
fragment invalidUnionWithinUnion on CatOrDog { ...humanOrAlienFragment }
fragment humanOrAlienFragment on HumanOrAlien { __typename }
";
error(_, "humanOrAlienFragment", "CatOrDog", "HumanOrAlien", 2, 66);
});
}
[Fact]
public void interface_into_non_implementing_object()
{
ShouldFailRule(_ =>
{
_.Query = @"
fragment invalidInterfaceWithinObject on Cat { ...intelligentFragment }
fragment intelligentFragment on Intelligent { iq }
";
error(_, "intelligentFragment", "Cat", "Intelligent", 2, 66);
});
}
[Fact]
public void interface_into_non_overlapping_interface()
{
ShouldFailRule(_ =>
{
_.Query = @"
fragment invalidInterfaceWithinInterface on Pet {
...intelligentFragment
}
fragment intelligentFragment on Intelligent { iq }
";
error(_, "intelligentFragment", "Pet", "Intelligent", 3, 21);
});
}
[Fact]
public void interface_into_non_overlapping_interface_in_inline_fragment()
{
ShouldFailRule(_ =>
{
_.Query = @"
fragment invalidInterfaceWithinInterfaceAnon on Pet {
...on Intelligent { iq }
}
";
errorAnon(_, "Pet", "Intelligent", 3, 21);
});
}
[Fact]
public void interface_into_non_overlapping_union()
{
ShouldFailRule(_ =>
{
_.Query = @"
fragment invalidInterfaceWithinUnion on HumanOrAlien { ...petFragment }
fragment petFragment on Pet { name }
";
error(_, "petFragment", "HumanOrAlien", "Pet", 2, 74);
});
}
private void error(ValidationTestConfig _, string fragName, string parentType, string fragType, int line, int column)
{
_.Error(PossibleFragmentSpreadsError.TypeIncompatibleSpreadMessage(fragName, parentType, fragType), line, column);
}
private void errorAnon(ValidationTestConfig _, string parentType, string fragType, int line, int column)
{
_.Error(PossibleFragmentSpreadsError.TypeIncompatibleAnonSpreadMessage(parentType, fragType), line, column);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
namespace System.Net.Sockets
{
// The Task-based APIs are currently wrappers over either the APM APIs (e.g. BeginConnect)
// or the SocketAsyncEventArgs APIs (e.g. ReceiveAsync(SocketAsyncEventArgs)). The latter
// are much more efficient when the SocketAsyncEventArg instances can be reused; as such,
// at present we use them for ReceiveAsync and SendAsync, caching an instance for each.
// In the future we could potentially maintain a global cache of instances used for accepts
// and connects, and potentially separate per-socket instances for Receive{Message}FromAsync,
// which would need different instances from ReceiveAsync due to having different results
// and thus different Completed logic. We also currently fall back to APM implementations
// when the single cached instance for each of send/receive is otherwise in use; we could
// potentially also employ a global pool from which to pull in such situations.
public partial class Socket
{
/// <summary>Handler for completed AcceptAsync operations.</summary>
private static readonly EventHandler<SocketAsyncEventArgs> AcceptCompletedHandler = (s, e) => CompleteAccept((Socket)s, (TaskSocketAsyncEventArgs<Socket>)e);
/// <summary>Handler for completed ReceiveAsync operations.</summary>
private static readonly EventHandler<SocketAsyncEventArgs> ReceiveCompletedHandler = (s, e) => CompleteSendReceive((Socket)s, (Int32TaskSocketAsyncEventArgs)e, isReceive: true);
/// <summary>Handler for completed SendAsync operations.</summary>
private static readonly EventHandler<SocketAsyncEventArgs> SendCompletedHandler = (s, e) => CompleteSendReceive((Socket)s, (Int32TaskSocketAsyncEventArgs)e, isReceive: false);
/// <summary>
/// Sentinel that can be stored into one of the Socket cached fields to indicate that an instance
/// was previously created but is currently being used by another concurrent operation.
/// </summary>
private static readonly TaskSocketAsyncEventArgs<Socket> s_rentedSocketSentinel = new TaskSocketAsyncEventArgs<Socket>();
/// <summary>
/// Sentinel that can be stored into one of the Int32 fields to indicate that an instance
/// was previously created but is currently being used by another concurrent operation.
/// </summary>
private static readonly Int32TaskSocketAsyncEventArgs s_rentedInt32Sentinel = new Int32TaskSocketAsyncEventArgs();
/// <summary>Cached task with a 0 value.</summary>
private static readonly Task<int> s_zeroTask = Task.FromResult(0);
/// <summary>Cached event args used with Task-based async operations.</summary>
private CachedEventArgs _cachedTaskEventArgs;
internal Task<Socket> AcceptAsync(Socket acceptSocket)
{
// Get any cached SocketAsyncEventArg we may have.
TaskSocketAsyncEventArgs<Socket> saea = Interlocked.Exchange(ref LazyInitializer.EnsureInitialized(ref _cachedTaskEventArgs).TaskAccept, s_rentedSocketSentinel);
if (saea == s_rentedSocketSentinel)
{
// An instance was once created (or is currently being created elsewhere), but some other
// concurrent operation is using it. Since we can store at most one, and since an individual
// APM operation is less expensive than creating a new SAEA and using it only once, we simply
// fall back to using an APM implementation.
return AcceptAsyncApm(acceptSocket);
}
else if (saea == null)
{
// No instance has been created yet, so create one.
saea = new TaskSocketAsyncEventArgs<Socket>();
saea.Completed += AcceptCompletedHandler;
}
// Configure the SAEA.
saea.AcceptSocket = acceptSocket;
// Initiate the accept operation.
Task<Socket> t;
if (AcceptAsync(saea))
{
// The operation is completing asynchronously (it may have already completed).
// Get the task for the operation, with appropriate synchronization to coordinate
// with the async callback that'll be completing the task.
bool responsibleForReturningToPool;
t = saea.GetCompletionResponsibility(out responsibleForReturningToPool).Task;
if (responsibleForReturningToPool)
{
// We're responsible for returning it only if the callback has already been invoked
// and gotten what it needs from the SAEA; otherwise, the callback will return it.
ReturnSocketAsyncEventArgs(saea);
}
}
else
{
// The operation completed synchronously. Get a task for it.
t = saea.SocketError == SocketError.Success ?
Task.FromResult(saea.AcceptSocket) :
Task.FromException<Socket>(GetException(saea.SocketError));
// There won't be a callback, and we're done with the SAEA, so return it to the pool.
ReturnSocketAsyncEventArgs(saea);
}
return t;
}
/// <summary>Implements Task-returning AcceptAsync on top of Begin/EndAsync.</summary>
private Task<Socket> AcceptAsyncApm(Socket acceptSocket)
{
var tcs = new TaskCompletionSource<Socket>(this);
BeginAccept(acceptSocket, 0, iar =>
{
var innerTcs = (TaskCompletionSource<Socket>)iar.AsyncState;
try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndAccept(iar)); }
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
internal Task ConnectAsync(EndPoint remoteEP)
{
var tcs = new TaskCompletionSource<bool>(this);
BeginConnect(remoteEP, iar =>
{
var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState;
try
{
((Socket)innerTcs.Task.AsyncState).EndConnect(iar);
innerTcs.TrySetResult(true);
}
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
internal Task ConnectAsync(IPAddress address, int port)
{
var tcs = new TaskCompletionSource<bool>(this);
BeginConnect(address, port, iar =>
{
var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState;
try
{
((Socket)innerTcs.Task.AsyncState).EndConnect(iar);
innerTcs.TrySetResult(true);
}
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
internal Task ConnectAsync(IPAddress[] addresses, int port)
{
var tcs = new TaskCompletionSource<bool>(this);
BeginConnect(addresses, port, iar =>
{
var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState;
try
{
((Socket)innerTcs.Task.AsyncState).EndConnect(iar);
innerTcs.TrySetResult(true);
}
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
internal Task ConnectAsync(string host, int port)
{
var tcs = new TaskCompletionSource<bool>(this);
BeginConnect(host, port, iar =>
{
var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState;
try
{
((Socket)innerTcs.Task.AsyncState).EndConnect(iar);
innerTcs.TrySetResult(true);
}
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
internal Task<int> ReceiveAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, bool fromNetworkStream)
{
ValidateBuffer(buffer);
return ReceiveAsync((Memory<byte>)buffer, socketFlags, fromNetworkStream, default).AsTask();
}
// TODO https://github.com/dotnet/corefx/issues/24430:
// Fully plumb cancellation down into socket operations.
internal ValueTask<int> ReceiveAsync(Memory<byte> buffer, SocketFlags socketFlags, bool fromNetworkStream, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
}
AwaitableSocketAsyncEventArgs saea = LazyInitializer.EnsureInitialized(ref LazyInitializer.EnsureInitialized(ref _cachedTaskEventArgs).ValueTaskReceive);
if (saea.Reserve())
{
Debug.Assert(saea.BufferList == null);
saea.SetBuffer(buffer);
saea.SocketFlags = socketFlags;
saea.WrapExceptionsInIOExceptions = fromNetworkStream;
return saea.ReceiveAsync(this);
}
else
{
// We couldn't get a cached instance, due to a concurrent receive operation on the socket.
// Fall back to wrapping APM.
return new ValueTask<int>(ReceiveAsyncApm(buffer, socketFlags));
}
}
/// <summary>Implements Task-returning ReceiveAsync on top of Begin/EndReceive.</summary>
private Task<int> ReceiveAsyncApm(Memory<byte> buffer, SocketFlags socketFlags)
{
if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> bufferArray))
{
// We were able to extract the underlying byte[] from the Memory<byte>. Use it.
var tcs = new TaskCompletionSource<int>(this);
BeginReceive(bufferArray.Array, bufferArray.Offset, bufferArray.Count, socketFlags, iar =>
{
var innerTcs = (TaskCompletionSource<int>)iar.AsyncState;
try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndReceive(iar)); }
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
else
{
// We weren't able to extract an underlying byte[] from the Memory<byte>.
// Instead read into an ArrayPool array, then copy from that into the memory.
byte[] poolArray = ArrayPool<byte>.Shared.Rent(buffer.Length);
var tcs = new TaskCompletionSource<int>(this);
BeginReceive(poolArray, 0, buffer.Length, socketFlags, iar =>
{
var state = (Tuple<TaskCompletionSource<int>, Memory<byte>, byte[]>)iar.AsyncState;
try
{
int bytesCopied = ((Socket)state.Item1.Task.AsyncState).EndReceive(iar);
new ReadOnlyMemory<byte>(state.Item3, 0, bytesCopied).Span.CopyTo(state.Item2.Span);
state.Item1.TrySetResult(bytesCopied);
}
catch (Exception e)
{
state.Item1.TrySetException(e);
}
finally
{
ArrayPool<byte>.Shared.Return(state.Item3);
}
}, Tuple.Create(tcs, buffer, poolArray));
return tcs.Task;
}
}
internal Task<int> ReceiveAsync(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
{
// Validate the arguments.
ValidateBuffersList(buffers);
Int32TaskSocketAsyncEventArgs saea = RentSocketAsyncEventArgs(isReceive: true);
if (saea != null)
{
// We got a cached instance. Configure the buffer list and initate the operation.
ConfigureBufferList(saea, buffers, socketFlags);
return GetTaskForSendReceive(ReceiveAsync(saea), saea, fromNetworkStream: false, isReceive: true);
}
else
{
// We couldn't get a cached instance, due to a concurrent receive operation on the socket.
// Fall back to wrapping APM.
return ReceiveAsyncApm(buffers, socketFlags);
}
}
/// <summary>Implements Task-returning ReceiveAsync on top of Begin/EndReceive.</summary>
private Task<int> ReceiveAsyncApm(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
{
var tcs = new TaskCompletionSource<int>(this);
BeginReceive(buffers, socketFlags, iar =>
{
var innerTcs = (TaskCompletionSource<int>)iar.AsyncState;
try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndReceive(iar)); }
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
internal Task<SocketReceiveFromResult> ReceiveFromAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEndPoint)
{
var tcs = new StateTaskCompletionSource<EndPoint, SocketReceiveFromResult>(this) { _field1 = remoteEndPoint };
BeginReceiveFrom(buffer.Array, buffer.Offset, buffer.Count, socketFlags, ref tcs._field1, iar =>
{
var innerTcs = (StateTaskCompletionSource<EndPoint, SocketReceiveFromResult>)iar.AsyncState;
try
{
int receivedBytes = ((Socket)innerTcs.Task.AsyncState).EndReceiveFrom(iar, ref innerTcs._field1);
innerTcs.TrySetResult(new SocketReceiveFromResult
{
ReceivedBytes = receivedBytes,
RemoteEndPoint = innerTcs._field1
});
}
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
internal Task<SocketReceiveMessageFromResult> ReceiveMessageFromAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEndPoint)
{
var tcs = new StateTaskCompletionSource<SocketFlags, EndPoint, SocketReceiveMessageFromResult>(this) { _field1 = socketFlags, _field2 = remoteEndPoint };
BeginReceiveMessageFrom(buffer.Array, buffer.Offset, buffer.Count, socketFlags, ref tcs._field2, iar =>
{
var innerTcs = (StateTaskCompletionSource<SocketFlags, EndPoint, SocketReceiveMessageFromResult>)iar.AsyncState;
try
{
IPPacketInformation ipPacketInformation;
int receivedBytes = ((Socket)innerTcs.Task.AsyncState).EndReceiveMessageFrom(iar, ref innerTcs._field1, ref innerTcs._field2, out ipPacketInformation);
innerTcs.TrySetResult(new SocketReceiveMessageFromResult
{
ReceivedBytes = receivedBytes,
RemoteEndPoint = innerTcs._field2,
SocketFlags = innerTcs._field1,
PacketInformation = ipPacketInformation
});
}
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
internal Task<int> SendAsync(ArraySegment<byte> buffer, SocketFlags socketFlags)
{
ValidateBuffer(buffer);
return SendAsync((ReadOnlyMemory<byte>)buffer, socketFlags, default).AsTask();
}
internal ValueTask<int> SendAsync(ReadOnlyMemory<byte> buffer, SocketFlags socketFlags, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
}
AwaitableSocketAsyncEventArgs saea = LazyInitializer.EnsureInitialized(ref LazyInitializer.EnsureInitialized(ref _cachedTaskEventArgs).ValueTaskSend);
if (saea.Reserve())
{
Debug.Assert(saea.BufferList == null);
saea.SetBuffer(MemoryMarshal.AsMemory(buffer));
saea.SocketFlags = socketFlags;
saea.WrapExceptionsInIOExceptions = false;
return saea.SendAsync(this);
}
else
{
// We couldn't get a cached instance, due to a concurrent send operation on the socket.
// Fall back to wrapping APM.
return new ValueTask<int>(SendAsyncApm(buffer, socketFlags));
}
}
internal ValueTask SendAsyncForNetworkStream(ReadOnlyMemory<byte> buffer, SocketFlags socketFlags, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return new ValueTask(Task.FromCanceled(cancellationToken));
}
AwaitableSocketAsyncEventArgs saea = LazyInitializer.EnsureInitialized(ref LazyInitializer.EnsureInitialized(ref _cachedTaskEventArgs).ValueTaskSend);
if (saea.Reserve())
{
Debug.Assert(saea.BufferList == null);
saea.SetBuffer(MemoryMarshal.AsMemory(buffer));
saea.SocketFlags = socketFlags;
saea.WrapExceptionsInIOExceptions = true;
return saea.SendAsyncForNetworkStream(this);
}
else
{
// We couldn't get a cached instance, due to a concurrent send operation on the socket.
// Fall back to wrapping APM.
return new ValueTask(SendAsyncApm(buffer, socketFlags));
}
}
/// <summary>Implements Task-returning SendAsync on top of Begin/EndSend.</summary>
private Task<int> SendAsyncApm(ReadOnlyMemory<byte> buffer, SocketFlags socketFlags)
{
if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> bufferArray))
{
var tcs = new TaskCompletionSource<int>(this);
BeginSend(bufferArray.Array, bufferArray.Offset, bufferArray.Count, socketFlags, iar =>
{
var innerTcs = (TaskCompletionSource<int>)iar.AsyncState;
try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndSend(iar)); }
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
else
{
// We weren't able to extract an underlying byte[] from the Memory<byte>.
// Instead read into an ArrayPool array, then copy from that into the memory.
byte[] poolArray = ArrayPool<byte>.Shared.Rent(buffer.Length);
buffer.Span.CopyTo(poolArray);
var tcs = new TaskCompletionSource<int>(this);
BeginSend(poolArray, 0, buffer.Length, socketFlags, iar =>
{
var state = (Tuple<TaskCompletionSource<int>, byte[]>)iar.AsyncState;
try
{
state.Item1.TrySetResult(((Socket)state.Item1.Task.AsyncState).EndSend(iar));
}
catch (Exception e)
{
state.Item1.TrySetException(e);
}
finally
{
ArrayPool<byte>.Shared.Return(state.Item2);
}
}, Tuple.Create(tcs, poolArray));
return tcs.Task;
}
}
internal Task<int> SendAsync(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
{
// Validate the arguments.
ValidateBuffersList(buffers);
Int32TaskSocketAsyncEventArgs saea = RentSocketAsyncEventArgs(isReceive: false);
if (saea != null)
{
// We got a cached instance. Configure the buffer list and initate the operation.
ConfigureBufferList(saea, buffers, socketFlags);
return GetTaskForSendReceive(SendAsync(saea), saea, fromNetworkStream: false, isReceive: false);
}
else
{
// We couldn't get a cached instance, due to a concurrent send operation on the socket.
// Fall back to wrapping APM.
return SendAsyncApm(buffers, socketFlags);
}
}
/// <summary>Implements Task-returning SendAsync on top of Begin/EndSend.</summary>
private Task<int> SendAsyncApm(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
{
var tcs = new TaskCompletionSource<int>(this);
BeginSend(buffers, socketFlags, iar =>
{
var innerTcs = (TaskCompletionSource<int>)iar.AsyncState;
try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndSend(iar)); }
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
internal Task<int> SendToAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEP)
{
var tcs = new TaskCompletionSource<int>(this);
BeginSendTo(buffer.Array, buffer.Offset, buffer.Count, socketFlags, remoteEP, iar =>
{
var innerTcs = (TaskCompletionSource<int>)iar.AsyncState;
try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndSendTo(iar)); }
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
/// <summary>Validates the supplied array segment, throwing if its array or indices are null or out-of-bounds, respectively.</summary>
private static void ValidateBuffer(ArraySegment<byte> buffer)
{
if (buffer.Array == null)
{
throw new ArgumentNullException(nameof(buffer.Array));
}
if (buffer.Offset < 0 || buffer.Offset > buffer.Array.Length)
{
throw new ArgumentOutOfRangeException(nameof(buffer.Offset));
}
if (buffer.Count < 0 || buffer.Count > buffer.Array.Length - buffer.Offset)
{
throw new ArgumentOutOfRangeException(nameof(buffer.Count));
}
}
/// <summary>Validates the supplied buffer list, throwing if it's null or empty.</summary>
private static void ValidateBuffersList(IList<ArraySegment<byte>> buffers)
{
if (buffers == null)
{
throw new ArgumentNullException(nameof(buffers));
}
if (buffers.Count == 0)
{
throw new ArgumentException(SR.Format(SR.net_sockets_zerolist, nameof(buffers)), nameof(buffers));
}
}
private static void ConfigureBufferList(
Int32TaskSocketAsyncEventArgs saea, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
{
// Configure the buffer list. We don't clear the buffers when returning the SAEA to the pool,
// so as to minimize overhead if the same buffers are used for subsequent operations (which is likely).
// But SAEA doesn't support having both a buffer and a buffer list configured, so clear out a buffer
// if there is one before we set the desired buffer list.
if (!saea.MemoryBuffer.Equals(default)) saea.SetBuffer(default);
saea.BufferList = buffers;
saea.SocketFlags = socketFlags;
}
/// <summary>Gets a task to represent the operation.</summary>
/// <param name="pending">true if the operation completes asynchronously; false if it completed synchronously.</param>
/// <param name="saea">The event args instance used with the operation.</param>
/// <param name="fromNetworkStream">
/// true if the request is coming from NetworkStream, which has special semantics for
/// exceptions and cached tasks; otherwise, false.
/// </param>
/// <param name="isReceive">true if this is a receive; false if this is a send.</param>
private Task<int> GetTaskForSendReceive(
bool pending, Int32TaskSocketAsyncEventArgs saea,
bool fromNetworkStream, bool isReceive)
{
Task<int> t;
if (pending)
{
// The operation is completing asynchronously (it may have already completed).
// Get the task for the operation, with appropriate synchronization to coordinate
// with the async callback that'll be completing the task.
bool responsibleForReturningToPool;
t = saea.GetCompletionResponsibility(out responsibleForReturningToPool).Task;
if (responsibleForReturningToPool)
{
// We're responsible for returning it only if the callback has already been invoked
// and gotten what it needs from the SAEA; otherwise, the callback will return it.
ReturnSocketAsyncEventArgs(saea, isReceive);
}
}
else
{
// The operation completed synchronously. Get a task for it.
if (saea.SocketError == SocketError.Success)
{
// Get the number of bytes successfully received/sent.
int bytesTransferred = saea.BytesTransferred;
// For zero bytes transferred, we can return our cached 0 task.
// We can also do so if the request came from network stream and is a send,
// as for that we can return any value because it returns a non-generic Task.
if (bytesTransferred == 0 || (fromNetworkStream & !isReceive))
{
t = s_zeroTask;
}
else
{
// Otherwise, create a new task for this result value.
t = Task.FromResult(bytesTransferred);
}
}
else
{
t = Task.FromException<int>(GetException(saea.SocketError, wrapExceptionsInIOExceptions: fromNetworkStream));
}
// There won't be a callback, and we're done with the SAEA, so return it to the pool.
ReturnSocketAsyncEventArgs(saea, isReceive);
}
return t;
}
/// <summary>Completes the SocketAsyncEventArg's Task with the result of the send or receive, and returns it to the specified pool.</summary>
private static void CompleteAccept(Socket s, TaskSocketAsyncEventArgs<Socket> saea)
{
// Pull the relevant state off of the SAEA
SocketError error = saea.SocketError;
Socket acceptSocket = saea.AcceptSocket;
// Synchronize with the initiating thread. If the synchronous caller already got what
// it needs from the SAEA, then we can return it to the pool now. Otherwise, it'll be
// responsible for returning it once it's gotten what it needs from it.
bool responsibleForReturningToPool;
AsyncTaskMethodBuilder<Socket> builder = saea.GetCompletionResponsibility(out responsibleForReturningToPool);
if (responsibleForReturningToPool)
{
s.ReturnSocketAsyncEventArgs(saea);
}
// Complete the builder/task with the results.
if (error == SocketError.Success)
{
builder.SetResult(acceptSocket);
}
else
{
builder.SetException(GetException(error));
}
}
/// <summary>Completes the SocketAsyncEventArg's Task with the result of the send or receive, and returns it to the specified pool.</summary>
private static void CompleteSendReceive(Socket s, Int32TaskSocketAsyncEventArgs saea, bool isReceive)
{
// Pull the relevant state off of the SAEA
SocketError error = saea.SocketError;
int bytesTransferred = saea.BytesTransferred;
bool wrapExceptionsInIOExceptions = saea._wrapExceptionsInIOExceptions;
// Synchronize with the initiating thread. If the synchronous caller already got what
// it needs from the SAEA, then we can return it to the pool now. Otherwise, it'll be
// responsible for returning it once it's gotten what it needs from it.
bool responsibleForReturningToPool;
AsyncTaskMethodBuilder<int> builder = saea.GetCompletionResponsibility(out responsibleForReturningToPool);
if (responsibleForReturningToPool)
{
s.ReturnSocketAsyncEventArgs(saea, isReceive);
}
// Complete the builder/task with the results.
if (error == SocketError.Success)
{
builder.SetResult(bytesTransferred);
}
else
{
builder.SetException(GetException(error, wrapExceptionsInIOExceptions));
}
}
/// <summary>Gets a SocketException or an IOException wrapping a SocketException for the specified error.</summary>
private static Exception GetException(SocketError error, bool wrapExceptionsInIOExceptions = false)
{
Exception e = new SocketException((int)error);
return wrapExceptionsInIOExceptions ?
new IOException(SR.Format(SR.net_io_readwritefailure, e.Message), e) :
e;
}
/// <summary>Rents a <see cref="Int32TaskSocketAsyncEventArgs"/> for immediate use.</summary>
/// <param name="isReceive">true if this instance will be used for a receive; false if for sends.</param>
private Int32TaskSocketAsyncEventArgs RentSocketAsyncEventArgs(bool isReceive)
{
// Get any cached SocketAsyncEventArg we may have.
CachedEventArgs cea = LazyInitializer.EnsureInitialized(ref _cachedTaskEventArgs);
Int32TaskSocketAsyncEventArgs saea = isReceive ?
Interlocked.Exchange(ref cea.TaskReceive, s_rentedInt32Sentinel) :
Interlocked.Exchange(ref cea.TaskSend, s_rentedInt32Sentinel);
if (saea == s_rentedInt32Sentinel)
{
// An instance was once created (or is currently being created elsewhere), but some other
// concurrent operation is using it. Since we can store at most one, and since an individual
// APM operation is less expensive than creating a new SAEA and using it only once, we simply
// return null, for a caller to fall back to using an APM implementation.
return null;
}
if (saea == null)
{
// No instance has been created yet, so create one.
saea = new Int32TaskSocketAsyncEventArgs();
saea.Completed += isReceive ? ReceiveCompletedHandler : SendCompletedHandler;
}
return saea;
}
/// <summary>Returns a <see cref="Int32TaskSocketAsyncEventArgs"/> instance for reuse.</summary>
/// <param name="saea">The instance to return.</param>
/// <param name="isReceive">true if this instance is used for receives; false if used for sends.</param>
private void ReturnSocketAsyncEventArgs(Int32TaskSocketAsyncEventArgs saea, bool isReceive)
{
Debug.Assert(_cachedTaskEventArgs != null, "Should have been initialized when renting");
Debug.Assert(saea != s_rentedInt32Sentinel);
// Reset state on the SAEA before returning it. But do not reset buffer state. That'll be done
// if necessary by the consumer, but we want to keep the buffers due to likely subsequent reuse
// and the costs associated with changing them.
saea._accessed = false;
saea._builder = default(AsyncTaskMethodBuilder<int>);
saea._wrapExceptionsInIOExceptions = false;
// Write this instance back as a cached instance. It should only ever be overwriting the sentinel,
// never null or another instance.
if (isReceive)
{
Debug.Assert(_cachedTaskEventArgs.TaskReceive == s_rentedInt32Sentinel);
Volatile.Write(ref _cachedTaskEventArgs.TaskReceive, saea);
}
else
{
Debug.Assert(_cachedTaskEventArgs.TaskSend == s_rentedInt32Sentinel);
Volatile.Write(ref _cachedTaskEventArgs.TaskSend, saea);
}
}
/// <summary>Returns a <see cref="Int32TaskSocketAsyncEventArgs"/> instance for reuse.</summary>
/// <param name="saea">The instance to return.</param>
/// <param name="isReceive">true if this instance is used for receives; false if used for sends.</param>
private void ReturnSocketAsyncEventArgs(TaskSocketAsyncEventArgs<Socket> saea)
{
Debug.Assert(_cachedTaskEventArgs != null, "Should have been initialized when renting");
Debug.Assert(saea != s_rentedSocketSentinel);
// Reset state on the SAEA before returning it. But do not reset buffer state. That'll be done
// if necessary by the consumer, but we want to keep the buffers due to likely subsequent reuse
// and the costs associated with changing them.
saea.AcceptSocket = null;
saea._accessed = false;
saea._builder = default(AsyncTaskMethodBuilder<Socket>);
// Write this instance back as a cached instance. It should only ever be overwriting the sentinel,
// never null or another instance.
Debug.Assert(_cachedTaskEventArgs.TaskAccept == s_rentedSocketSentinel);
Volatile.Write(ref _cachedTaskEventArgs.TaskAccept, saea);
}
/// <summary>Dispose of any cached <see cref="Int32TaskSocketAsyncEventArgs"/> instances.</summary>
private void DisposeCachedTaskSocketAsyncEventArgs()
{
CachedEventArgs cea = _cachedTaskEventArgs;
if (cea != null)
{
Interlocked.Exchange(ref cea.TaskAccept, s_rentedSocketSentinel)?.Dispose();
Interlocked.Exchange(ref cea.TaskReceive, s_rentedInt32Sentinel)?.Dispose();
Interlocked.Exchange(ref cea.TaskSend, s_rentedInt32Sentinel)?.Dispose();
Interlocked.Exchange(ref cea.ValueTaskReceive, AwaitableSocketAsyncEventArgs.Reserved)?.Dispose();
Interlocked.Exchange(ref cea.ValueTaskSend, AwaitableSocketAsyncEventArgs.Reserved)?.Dispose();
}
}
/// <summary>A TaskCompletionSource that carries an extra field of strongly-typed state.</summary>
private class StateTaskCompletionSource<TField1, TResult> : TaskCompletionSource<TResult>
{
internal TField1 _field1;
public StateTaskCompletionSource(object baseState) : base(baseState) { }
}
/// <summary>A TaskCompletionSource that carries several extra fields of strongly-typed state.</summary>
private class StateTaskCompletionSource<TField1, TField2, TResult> : StateTaskCompletionSource<TField1, TResult>
{
internal TField2 _field2;
public StateTaskCompletionSource(object baseState) : base(baseState) { }
}
/// <summary>Cached event args used with Task-based async operations.</summary>
private sealed class CachedEventArgs
{
/// <summary>Cached instance for accept operations.</summary>
public TaskSocketAsyncEventArgs<Socket> TaskAccept;
/// <summary>Cached instance for receive operations that return <see cref="Task{Int32}"/>.</summary>
public Int32TaskSocketAsyncEventArgs TaskReceive;
/// <summary>Cached instance for send operations that return <see cref="Task{Int32}"/>.</summary>
public Int32TaskSocketAsyncEventArgs TaskSend;
/// <summary>Cached instance for receive operations that return <see cref="ValueTask{Int32}"/>.</summary>
public AwaitableSocketAsyncEventArgs ValueTaskReceive;
/// <summary>Cached instance for send operations that return <see cref="ValueTask{Int32}"/>.</summary>
public AwaitableSocketAsyncEventArgs ValueTaskSend;
}
/// <summary>A SocketAsyncEventArgs with an associated async method builder.</summary>
private class TaskSocketAsyncEventArgs<TResult> : SocketAsyncEventArgs
{
/// <summary>
/// The builder used to create the Task representing the result of the async operation.
/// This is a mutable struct.
/// </summary>
internal AsyncTaskMethodBuilder<TResult> _builder;
/// <summary>
/// Whether the instance was already accessed as part of the operation. We expect
/// at most two accesses: one from the synchronous caller to initiate the operation,
/// and one from the callback if the operation completes asynchronously. If it completes
/// synchronously, then it's the initiator's responsbility to return the instance to
/// the pool. If it completes asynchronously, then it's the responsibility of whoever
/// accesses this second, so we track whether it's already been accessed.
/// </summary>
internal bool _accessed = false;
internal TaskSocketAsyncEventArgs() :
base(flowExecutionContext: false) // avoid flowing context at lower layers as we only expose Task, which handles it
{
}
/// <summary>Gets the builder's task with appropriate synchronization.</summary>
internal AsyncTaskMethodBuilder<TResult> GetCompletionResponsibility(out bool responsibleForReturningToPool)
{
lock (this)
{
responsibleForReturningToPool = _accessed;
_accessed = true;
var ignored = _builder.Task; // force initialization under the lock (builder itself lazily initializes w/o synchronization)
return _builder;
}
}
}
/// <summary>A SocketAsyncEventArgs with an associated async method builder.</summary>
private sealed class Int32TaskSocketAsyncEventArgs : TaskSocketAsyncEventArgs<int>
{
/// <summary>Whether exceptions that emerge should be wrapped in IOExceptions.</summary>
internal bool _wrapExceptionsInIOExceptions;
}
/// <summary>A SocketAsyncEventArgs that can be awaited to get the result of an operation.</summary>
internal sealed class AwaitableSocketAsyncEventArgs : SocketAsyncEventArgs, IValueTaskSource, IValueTaskSource<int>
{
internal static readonly AwaitableSocketAsyncEventArgs Reserved = new AwaitableSocketAsyncEventArgs() { _continuation = null };
/// <summary>Sentinel object used to indicate that the operation has completed prior to OnCompleted being called.</summary>
private static readonly Action<object> s_completedSentinel = new Action<object>(state => throw new Exception(nameof(s_completedSentinel)));
/// <summary>Sentinel object used to indicate that the instance is available for use.</summary>
private static readonly Action<object> s_availableSentinel = new Action<object>(state => throw new Exception(nameof(s_availableSentinel)));
/// <summary>
/// <see cref="s_availableSentinel"/> if the object is available for use, after GetResult has been called on a previous use.
/// null if the operation has not completed.
/// <see cref="s_completedSentinel"/> if it has completed.
/// Another delegate if OnCompleted was called before the operation could complete, in which case it's the delegate to invoke
/// when the operation does complete.
/// </summary>
private Action<object> _continuation = s_availableSentinel;
private ExecutionContext _executionContext;
private object _scheduler;
/// <summary>Current token value given to a ValueTask and then verified against the value it passes back to us.</summary>
/// <remarks>
/// This is not meant to be a completely reliable mechanism, doesn't require additional synchronization, etc.
/// It's purely a best effort attempt to catch misuse, including awaiting for a value task twice and after
/// it's already being reused by someone else.
/// </remarks>
private short _token;
/// <summary>Initializes the event args.</summary>
/// <param name="socket">The associated socket.</param>
/// <param name="buffer">The buffer to use for all operations.</param>
public AwaitableSocketAsyncEventArgs() :
base(flowExecutionContext: false) // avoid flowing context at lower layers as we only expose ValueTask, which handles it
{
}
public bool WrapExceptionsInIOExceptions { get; set; }
public bool Reserve() =>
ReferenceEquals(Interlocked.CompareExchange(ref _continuation, null, s_availableSentinel), s_availableSentinel);
private void Release()
{
_token++;
Volatile.Write(ref _continuation, s_availableSentinel);
}
protected override void OnCompleted(SocketAsyncEventArgs _)
{
// When the operation completes, see if OnCompleted was already called to hook up a continuation.
// If it was, invoke the continuation.
Action<object> c = _continuation;
if (c != null || (c = Interlocked.CompareExchange(ref _continuation, s_completedSentinel, null)) != null)
{
Debug.Assert(c != s_availableSentinel, "The delegate should not have been the available sentinel.");
Debug.Assert(c != s_completedSentinel, "The delegate should not have been the completed sentinel.");
object continuationState = UserToken;
UserToken = null;
_continuation = s_completedSentinel; // in case someone's polling IsCompleted
ExecutionContext ec = _executionContext;
if (ec == null)
{
InvokeContinuation(c, continuationState, forceAsync: false);
}
else
{
// This case should be relatively rare, as the async Task/ValueTask method builders
// use the awaiter's UnsafeOnCompleted, so this will only happen with code that
// explicitly uses the awaiter's OnCompleted instead.
_executionContext = null;
ExecutionContext.Run(ec, runState =>
{
var t = (Tuple<AwaitableSocketAsyncEventArgs, Action<object>, object>)runState;
t.Item1.InvokeContinuation(t.Item2, t.Item3, forceAsync: false);
}, Tuple.Create(this, c, continuationState));
}
}
}
/// <summary>Initiates a receive operation on the associated socket.</summary>
/// <returns>This instance.</returns>
public ValueTask<int> ReceiveAsync(Socket socket)
{
Debug.Assert(Volatile.Read(ref _continuation) == null, $"Expected null continuation to indicate reserved for use");
if (socket.ReceiveAsync(this))
{
return new ValueTask<int>(this, _token);
}
int bytesTransferred = BytesTransferred;
SocketError error = SocketError;
Release();
return error == SocketError.Success ?
new ValueTask<int>(bytesTransferred) :
new ValueTask<int>(Task.FromException<int>(CreateException(error)));
}
/// <summary>Initiates a send operation on the associated socket.</summary>
/// <returns>This instance.</returns>
public ValueTask<int> SendAsync(Socket socket)
{
Debug.Assert(Volatile.Read(ref _continuation) == null, $"Expected null continuation to indicate reserved for use");
if (socket.SendAsync(this))
{
return new ValueTask<int>(this, _token);
}
int bytesTransferred = BytesTransferred;
SocketError error = SocketError;
Release();
return error == SocketError.Success ?
new ValueTask<int>(bytesTransferred) :
new ValueTask<int>(Task.FromException<int>(CreateException(error)));
}
public ValueTask SendAsyncForNetworkStream(Socket socket)
{
Debug.Assert(Volatile.Read(ref _continuation) == null, $"Expected null continuation to indicate reserved for use");
if (socket.SendAsync(this))
{
return new ValueTask(this, _token);
}
SocketError error = SocketError;
Release();
return error == SocketError.Success ?
default :
new ValueTask(Task.FromException(CreateException(error)));
}
/// <summary>Gets the status of the operation.</summary>
public ValueTaskSourceStatus GetStatus(short token)
{
if (token != _token)
{
ThrowIncorrectTokenException();
}
return
!ReferenceEquals(_continuation, s_completedSentinel) ? ValueTaskSourceStatus.Pending :
base.SocketError == SocketError.Success ? ValueTaskSourceStatus.Succeeded :
ValueTaskSourceStatus.Faulted;
}
/// <summary>Queues the provided continuation to be executed once the operation has completed.</summary>
public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
{
if (token != _token)
{
ThrowIncorrectTokenException();
}
if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0)
{
_executionContext = ExecutionContext.Capture();
}
if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0)
{
SynchronizationContext sc = SynchronizationContext.Current;
if (sc != null && sc.GetType() != typeof(SynchronizationContext))
{
_scheduler = sc;
}
else
{
TaskScheduler ts = TaskScheduler.Current;
if (ts != TaskScheduler.Default)
{
_scheduler = ts;
}
}
}
UserToken = state; // Use UserToken to carry the continuation state around
Action<object> prevContinuation = Interlocked.CompareExchange(ref _continuation, continuation, null);
if (ReferenceEquals(prevContinuation, s_completedSentinel))
{
// Lost the race condition and the operation has now already completed.
// We need to invoke the continuation, but it must be asynchronously to
// avoid a stack dive. However, since all of the queueing mechanisms flow
// ExecutionContext, and since we're still in the same context where we
// captured it, we can just ignore the one we captured.
_executionContext = null;
UserToken = null; // we have the state in "state"; no need for the one in UserToken
InvokeContinuation(continuation, state, forceAsync: true);
}
else if (prevContinuation != null)
{
// Flag errors with the continuation being hooked up multiple times.
// This is purely to help alert a developer to a bug they need to fix.
ThrowMultipleContinuationsException();
}
}
private void InvokeContinuation(Action<object> continuation, object state, bool forceAsync)
{
object scheduler = _scheduler;
_scheduler = null;
if (scheduler != null)
{
if (scheduler is SynchronizationContext sc)
{
sc.Post(s =>
{
var t = (Tuple<Action<object>, object>)s;
t.Item1(t.Item2);
}, Tuple.Create(continuation, state));
}
else
{
Debug.Assert(scheduler is TaskScheduler, $"Expected TaskScheduler, got {scheduler}");
Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, (TaskScheduler)scheduler);
}
}
else if (forceAsync)
{
ThreadPool.QueueUserWorkItem(continuation, state, preferLocal: true);
}
else
{
continuation(state);
}
}
/// <summary>Gets the result of the completion operation.</summary>
/// <returns>Number of bytes transferred.</returns>
/// <remarks>
/// Unlike TaskAwaiter's GetResult, this does not block until the operation completes: it must only
/// be used once the operation has completed. This is handled implicitly by await.
/// </remarks>
public int GetResult(short token)
{
if (token != _token)
{
ThrowIncorrectTokenException();
}
SocketError error = SocketError;
int bytes = BytesTransferred;
Release();
if (error != SocketError.Success)
{
ThrowException(error);
}
return bytes;
}
void IValueTaskSource.GetResult(short token)
{
if (token != _token)
{
ThrowIncorrectTokenException();
}
SocketError error = SocketError;
Release();
if (error != SocketError.Success)
{
ThrowException(error);
}
}
private void ThrowIncorrectTokenException() => throw new InvalidOperationException(SR.InvalidOperation_IncorrectToken);
private void ThrowMultipleContinuationsException() => throw new InvalidOperationException(SR.InvalidOperation_MultipleContinuations);
private void ThrowException(SocketError error) => throw CreateException(error);
private Exception CreateException(SocketError error)
{
var se = new SocketException((int)error);
return WrapExceptionsInIOExceptions ? (Exception)
new IOException(SR.Format(SR.net_io_readfailure, se.Message), se) :
se;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using Mono.Addins;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Servers;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors.Friends;
using OpenSim.Server.Base;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.Avatar.Friends
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "FriendsModule")]
public class FriendsModule : ISharedRegionModule, IFriendsModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected bool m_Enabled = false;
protected class UserFriendData
{
public UUID PrincipalID;
public FriendInfo[] Friends;
public int Refcount;
public bool IsFriend(string friend)
{
foreach (FriendInfo fi in Friends)
{
if (fi.Friend == friend)
return true;
}
return false;
}
}
protected static readonly FriendInfo[] EMPTY_FRIENDS = new FriendInfo[0];
protected List<Scene> m_Scenes = new List<Scene>();
protected IPresenceService m_PresenceService = null;
protected IFriendsService m_FriendsService = null;
protected FriendsSimConnector m_FriendsSimConnector;
/// <summary>
/// Cache friends lists for users.
/// </summary>
/// <remarks>
/// This is a complex and error-prone thing to do. At the moment, we assume that the efficiency gained in
/// permissions checks outweighs the disadvantages of that complexity.
/// </remarks>
protected Dictionary<UUID, UserFriendData> m_Friends = new Dictionary<UUID, UserFriendData>();
/// <summary>
/// Maintain a record of clients that need to notify about their online status. This only
/// needs to be done on login. Subsequent online/offline friend changes are sent by a different mechanism.
/// </summary>
protected HashSet<UUID> m_NeedsToNotifyStatus = new HashSet<UUID>();
/// <summary>
/// Maintain a record of viewers that need to be sent notifications for friends that are online. This only
/// needs to be done on login. Subsequent online/offline friend changes are sent by a different mechanism.
/// </summary>
protected HashSet<UUID> m_NeedsListOfOnlineFriends = new HashSet<UUID>();
protected IPresenceService PresenceService
{
get
{
if (m_PresenceService == null)
{
if (m_Scenes.Count > 0)
m_PresenceService = m_Scenes[0].RequestModuleInterface<IPresenceService>();
}
return m_PresenceService;
}
}
public IFriendsService FriendsService
{
get
{
if (m_FriendsService == null)
{
if (m_Scenes.Count > 0)
m_FriendsService = m_Scenes[0].RequestModuleInterface<IFriendsService>();
}
return m_FriendsService;
}
}
protected IGridService GridService
{
get { return m_Scenes[0].GridService; }
}
public IUserAccountService UserAccountService
{
get { return m_Scenes[0].UserAccountService; }
}
public IScene Scene
{
get
{
if (m_Scenes.Count > 0)
return m_Scenes[0];
else
return null;
}
}
#region ISharedRegionModule
public void Initialise(IConfigSource config)
{
IConfig moduleConfig = config.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("FriendsModule", "FriendsModule");
if (name == Name)
{
InitModule(config);
m_Enabled = true;
m_log.DebugFormat("[FRIENDS MODULE]: {0} enabled.", Name);
}
}
}
protected virtual void InitModule(IConfigSource config)
{
IConfig friendsConfig = config.Configs["Friends"];
if (friendsConfig != null)
{
int mPort = friendsConfig.GetInt("Port", 0);
string connector = friendsConfig.GetString("Connector", String.Empty);
Object[] args = new Object[] { config };
m_FriendsService = ServerUtils.LoadPlugin<IFriendsService>(connector, args);
m_FriendsSimConnector = new FriendsSimConnector();
// Instantiate the request handler
IHttpServer server = MainServer.GetHttpServer((uint)mPort);
if (server != null)
server.AddStreamHandler(new FriendsRequestHandler(this));
}
if (m_FriendsService == null)
{
m_log.Error("[FRIENDS]: No Connector defined in section Friends, or failed to load, cannot continue");
throw new Exception("Connector load error");
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public virtual void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
// m_log.DebugFormat("[FRIENDS MODULE]: AddRegion on {0}", Name);
m_Scenes.Add(scene);
scene.RegisterModuleInterface<IFriendsModule>(this);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnClientClosed += OnClientClosed;
scene.EventManager.OnMakeRootAgent += OnMakeRootAgent;
scene.EventManager.OnClientLogin += OnClientLogin;
}
public virtual void RegionLoaded(Scene scene) {}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
m_Scenes.Remove(scene);
}
public virtual string Name
{
get { return "FriendsModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
public virtual int GetRightsGrantedByFriend(UUID principalID, UUID friendID)
{
FriendInfo[] friends = GetFriendsFromCache(principalID);
FriendInfo finfo = GetFriend(friends, friendID);
if (finfo != null)
{
return finfo.TheirFlags;
}
return 0;
}
private void OnMakeRootAgent(ScenePresence sp)
{
if(sp.gotCrossUpdate)
return;
RecacheFriends(sp.ControllingClient);
lock (m_NeedsToNotifyStatus)
{
if (m_NeedsToNotifyStatus.Remove(sp.UUID))
{
// Inform the friends that this user is online. This can only be done once the client is a Root Agent.
StatusChange(sp.UUID, true);
}
}
}
private void OnNewClient(IClientAPI client)
{
client.OnInstantMessage += OnInstantMessage;
client.OnApproveFriendRequest += OnApproveFriendRequest;
client.OnDenyFriendRequest += OnDenyFriendRequest;
client.OnTerminateFriendship += RemoveFriendship;
client.OnGrantUserRights += GrantRights;
client.OnFindAgent += FindFriend;
// We need to cache information for child agents as well as root agents so that friend edit/move/delete
// permissions will work across borders where both regions are on different simulators.
//
// Do not do this asynchronously. If we do, then subsequent code can outrace CacheFriends() and
// return misleading results from the still empty friends cache.
// If we absolutely need to do this asynchronously, then a signalling mechanism is needed so that calls
// to GetFriends() will wait until CacheFriends() completes. Locks are insufficient.
CacheFriends(client);
}
/// <summary>
/// Cache the friends list or increment the refcount for the existing friends list.
/// </summary>
/// <param name="client">
/// </param>
/// <returns>
/// Returns true if the list was fetched, false if it wasn't
/// </returns>
protected virtual bool CacheFriends(IClientAPI client)
{
UUID agentID = client.AgentId;
lock (m_Friends)
{
UserFriendData friendsData;
if (m_Friends.TryGetValue(agentID, out friendsData))
{
friendsData.Refcount++;
return false;
}
else
{
friendsData = new UserFriendData();
friendsData.PrincipalID = agentID;
friendsData.Friends = GetFriendsFromService(client);
friendsData.Refcount = 1;
m_Friends[agentID] = friendsData;
return true;
}
}
}
private void OnClientClosed(UUID agentID, Scene scene)
{
ScenePresence sp = scene.GetScenePresence(agentID);
if (sp != null && !sp.IsChildAgent)
{
// do this for root agents closing out
StatusChange(agentID, false);
}
lock (m_Friends)
{
UserFriendData friendsData;
if (m_Friends.TryGetValue(agentID, out friendsData))
{
friendsData.Refcount--;
if (friendsData.Refcount <= 0)
m_Friends.Remove(agentID);
}
}
}
private void OnClientLogin(IClientAPI client)
{
UUID agentID = client.AgentId;
//m_log.DebugFormat("[XXX]: OnClientLogin!");
// Register that we need to send this user's status to friends. This can only be done
// once the client becomes a Root Agent, because as part of sending out the presence
// we also get back the presence of the HG friends, and we need to send that to the
// client, but that can only be done when the client is a Root Agent.
lock (m_NeedsToNotifyStatus)
m_NeedsToNotifyStatus.Add(agentID);
// Register that we need to send the list of online friends to this user
lock (m_NeedsListOfOnlineFriends)
m_NeedsListOfOnlineFriends.Add(agentID);
}
public void IsNowRoot(ScenePresence sp)
{
OnMakeRootAgent(sp);
}
public virtual bool SendFriendsOnlineIfNeeded(IClientAPI client)
{
if (client == null)
return false;
UUID agentID = client.AgentId;
// Check if the online friends list is needed
lock (m_NeedsListOfOnlineFriends)
{
if (!m_NeedsListOfOnlineFriends.Remove(agentID))
return false;
}
// Send the friends online
List<UUID> online = GetOnlineFriends(agentID);
if (online.Count > 0)
client.SendAgentOnline(online.ToArray());
// Send outstanding friendship offers
List<string> outstanding = new List<string>();
FriendInfo[] friends = GetFriendsFromCache(agentID);
foreach (FriendInfo fi in friends)
{
if (fi.TheirFlags == -1)
outstanding.Add(fi.Friend);
}
GridInstantMessage im = new GridInstantMessage(client.Scene, UUID.Zero, String.Empty, agentID, (byte)InstantMessageDialog.FriendshipOffered,
"Will you be my friend?", true, Vector3.Zero);
foreach (string fid in outstanding)
{
UUID fromAgentID;
string firstname = "Unknown", lastname = "UserFMSFOIN";
if (!GetAgentInfo(client.Scene.RegionInfo.ScopeID, fid, out fromAgentID, out firstname, out lastname))
{
m_log.DebugFormat("[FRIENDS MODULE]: skipping malformed friend {0}", fid);
continue;
}
im.offline = 0;
im.fromAgentID = fromAgentID.Guid;
im.fromAgentName = firstname + " " + lastname;
im.imSessionID = im.fromAgentID;
im.message = FriendshipMessage(fid);
LocalFriendshipOffered(agentID, im);
}
return true;
}
protected virtual string FriendshipMessage(string friendID)
{
return "Will you be my friend?";
}
protected virtual bool GetAgentInfo(UUID scopeID, string fid, out UUID agentID, out string first, out string last)
{
first = "Unknown"; last = "UserFMGAI";
if (!UUID.TryParse(fid, out agentID))
return false;
UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(scopeID, agentID);
if (account != null)
{
first = account.FirstName;
last = account.LastName;
}
return true;
}
List<UUID> GetOnlineFriends(UUID userID)
{
List<string> friendList = new List<string>();
FriendInfo[] friends = GetFriendsFromCache(userID);
foreach (FriendInfo fi in friends)
{
if (((fi.TheirFlags & (int)FriendRights.CanSeeOnline) != 0) && (fi.TheirFlags != -1))
friendList.Add(fi.Friend);
}
List<UUID> online = new List<UUID>();
if (friendList.Count > 0)
GetOnlineFriends(userID, friendList, online);
// m_log.DebugFormat(
// "[FRIENDS MODULE]: User {0} has {1} friends online", userID, online.Count);
return online;
}
protected virtual void GetOnlineFriends(UUID userID, List<string> friendList, /*collector*/ List<UUID> online)
{
// m_log.DebugFormat(
// "[FRIENDS MODULE]: Looking for online presence of {0} users for {1}", friendList.Count, userID);
PresenceInfo[] presence = PresenceService.GetAgents(friendList.ToArray());
foreach (PresenceInfo pi in presence)
{
UUID presenceID;
if (UUID.TryParse(pi.UserID, out presenceID))
online.Add(presenceID);
}
}
/// <summary>
/// Find the client for a ID
/// </summary>
public IClientAPI LocateClientObject(UUID agentID)
{
lock (m_Scenes)
{
foreach (Scene scene in m_Scenes)
{
ScenePresence presence = scene.GetScenePresence(agentID);
if (presence != null && !presence.IsChildAgent)
return presence.ControllingClient;
}
}
return null;
}
/// <summary>
/// Caller beware! Call this only for root agents.
/// </summary>
/// <param name="agentID"></param>
/// <param name="online"></param>
private void StatusChange(UUID agentID, bool online)
{
FriendInfo[] friends = GetFriendsFromCache(agentID);
if (friends.Length > 0)
{
List<FriendInfo> friendList = new List<FriendInfo>();
foreach (FriendInfo fi in friends)
{
if (((fi.MyFlags & (int)FriendRights.CanSeeOnline) != 0) && (fi.TheirFlags != -1))
friendList.Add(fi);
}
if(friendList.Count > 0)
{
Util.FireAndForget(
delegate
{
// m_log.DebugFormat(
// "[FRIENDS MODULE]: Notifying {0} friends of {1} of online status {2}",
// friendList.Count, agentID, online);
// Notify about this user status
StatusNotify(friendList, agentID, online);
}, null, "FriendsModule.StatusChange"
);
}
}
}
protected virtual void StatusNotify(List<FriendInfo> friendList, UUID userID, bool online)
{
//m_log.DebugFormat("[FRIENDS]: Entering StatusNotify for {0}", userID);
List<string> friendStringIds = friendList.ConvertAll<string>(friend => friend.Friend);
List<string> remoteFriendStringIds = new List<string>();
foreach (string friendStringId in friendStringIds)
{
UUID friendUuid;
if (UUID.TryParse(friendStringId, out friendUuid))
{
if (LocalStatusNotification(userID, friendUuid, online))
continue;
remoteFriendStringIds.Add(friendStringId);
}
else
{
m_log.WarnFormat("[FRIENDS]: Error parsing friend ID {0}", friendStringId);
}
}
// We do this regrouping so that we can efficiently send a single request rather than one for each
// friend in what may be a very large friends list.
PresenceInfo[] friendSessions = PresenceService.GetAgents(remoteFriendStringIds.ToArray());
if(friendSessions == null)
return;
foreach (PresenceInfo friendSession in friendSessions)
{
// let's guard against sessions-gone-bad
if (friendSession != null && friendSession.RegionID != UUID.Zero)
{
//m_log.DebugFormat("[FRIENDS]: Get region {0}", friendSession.RegionID);
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
if (region != null)
{
m_FriendsSimConnector.StatusNotify(region, userID, friendSession.UserID, online);
}
}
//else
// m_log.DebugFormat("[FRIENDS]: friend session is null or the region is UUID.Zero");
}
}
protected virtual void OnInstantMessage(IClientAPI client, GridInstantMessage im)
{
if ((InstantMessageDialog)im.dialog == InstantMessageDialog.FriendshipOffered)
{
// we got a friendship offer
UUID principalID = new UUID(im.fromAgentID);
UUID friendID = new UUID(im.toAgentID);
m_log.DebugFormat("[FRIENDS]: {0} ({1}) offered friendship to {2} ({3})", principalID, client.FirstName + client.LastName, friendID, im.fromAgentName);
// Check that the friendship doesn't exist yet
FriendInfo[] finfos = GetFriendsFromCache(principalID);
if (finfos != null)
{
FriendInfo f = GetFriend(finfos, friendID);
if (f != null)
{
client.SendAgentAlertMessage("This person is already your friend. Please delete it first if you want to reestablish the friendship.", false);
return;
}
}
// This user wants to be friends with the other user.
// Let's add the relation backwards, in case the other is not online
StoreBackwards(friendID, principalID);
// Now let's ask the other user to be friends with this user
ForwardFriendshipOffer(principalID, friendID, im);
}
}
protected virtual bool ForwardFriendshipOffer(UUID agentID, UUID friendID, GridInstantMessage im)
{
// !!!!!!!! This is a hack so that we don't have to keep state (transactionID/imSessionID)
// We stick this agent's ID as imSession, so that it's directly available on the receiving end
im.imSessionID = im.fromAgentID;
im.fromAgentName = GetFriendshipRequesterName(agentID);
// Try the local sim
if (LocalFriendshipOffered(friendID, im))
return true;
// The prospective friend is not here [as root]. Let's forward.
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
m_FriendsSimConnector.FriendshipOffered(region, agentID, friendID, im.message);
return true;
}
}
// If the prospective friend is not online, he'll get the message upon login.
return false;
}
protected virtual string GetFriendshipRequesterName(UUID agentID)
{
UserAccount account = UserAccountService.GetUserAccount(UUID.Zero, agentID);
return (account == null) ? "Unknown" : account.FirstName + " " + account.LastName;
}
protected virtual void OnApproveFriendRequest(IClientAPI client, UUID friendID, List<UUID> callingCardFolders)
{
m_log.DebugFormat("[FRIENDS]: {0} accepted friendship from {1}", client.AgentId, friendID);
AddFriendship(client, friendID);
}
public void AddFriendship(IClientAPI client, UUID friendID)
{
StoreFriendships(client.AgentId, friendID);
ICallingCardModule ccm = client.Scene.RequestModuleInterface<ICallingCardModule>();
if (ccm != null)
{
ccm.CreateCallingCard(client.AgentId, friendID, UUID.Zero);
}
// Update the local cache.
RecacheFriends(client);
//
// Notify the friend
//
// Try Local
if (LocalFriendshipApproved(client.AgentId, client.Name, friendID))
{
client.SendAgentOnline(new UUID[] { friendID });
return;
}
// The friend is not here
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
m_FriendsSimConnector.FriendshipApproved(region, client.AgentId, client.Name, friendID);
client.SendAgentOnline(new UUID[] { friendID });
}
}
}
private void OnDenyFriendRequest(IClientAPI client, UUID friendID, List<UUID> callingCardFolders)
{
m_log.DebugFormat("[FRIENDS]: {0} denied friendship to {1}", client.AgentId, friendID);
DeleteFriendship(client.AgentId, friendID);
//
// Notify the friend
//
// Try local
if (LocalFriendshipDenied(client.AgentId, client.Name, friendID))
return;
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
if (region != null)
m_FriendsSimConnector.FriendshipDenied(region, client.AgentId, client.Name, friendID);
else
m_log.WarnFormat("[FRIENDS]: Could not find region {0} in locating {1}", friendSession.RegionID, friendID);
}
}
}
public void RemoveFriendship(IClientAPI client, UUID exfriendID)
{
if (!DeleteFriendship(client.AgentId, exfriendID))
client.SendAlertMessage("Unable to terminate friendship on this sim.");
// Update local cache
RecacheFriends(client);
client.SendTerminateFriend(exfriendID);
//
// Notify the friend
//
// Try local
if (LocalFriendshipTerminated(client.AgentId, exfriendID))
return;
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { exfriendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
m_FriendsSimConnector.FriendshipTerminated(region, client.AgentId, exfriendID);
}
}
}
public void FindFriend(IClientAPI remoteClient,UUID HunterID ,UUID PreyID)
{
UUID requester = remoteClient.AgentId;
if(requester != HunterID) // only allow client agent to be the hunter (?)
return;
FriendInfo[] friends = GetFriendsFromCache(requester);
if (friends.Length == 0)
return;
FriendInfo friend = GetFriend(friends, PreyID);
if (friend == null)
return;
if((friend.TheirFlags & (int)FriendRights.CanSeeOnMap) == 0)
return;
Scene hunterScene = (Scene)remoteClient.Scene;
if(hunterScene == null)
return;
// check local
ScenePresence sp;
double px;
double py;
if(hunterScene.TryGetScenePresence(PreyID, out sp))
{
if(sp == null)
return;
px = hunterScene.RegionInfo.WorldLocX + sp.AbsolutePosition.X;
py = hunterScene.RegionInfo.WorldLocY + sp.AbsolutePosition.Y;
remoteClient.SendFindAgent(HunterID, PreyID, px, py);
return;
}
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { PreyID.ToString() });
if (friendSessions == null || friendSessions.Length == 0)
return;
PresenceInfo friendSession = friendSessions[0];
if (friendSession == null)
return;
GridRegion region = GridService.GetRegionByUUID(hunterScene.RegionInfo.ScopeID, friendSession.RegionID);
if(region == null)
return;
// we don't have presence location so point to a standard region center for now
px = region.RegionLocX + 128.0;
py = region.RegionLocY + 128.0;
remoteClient.SendFindAgent(HunterID, PreyID, px, py);
}
public void GrantRights(IClientAPI remoteClient, UUID friendID, int rights)
{
UUID requester = remoteClient.AgentId;
m_log.DebugFormat(
"[FRIENDS MODULE]: User {0} changing rights to {1} for friend {2}",
requester, rights, friendID);
FriendInfo[] friends = GetFriendsFromCache(requester);
if (friends.Length == 0)
{
return;
}
// Let's find the friend in this user's friend list
FriendInfo friend = GetFriend(friends, friendID);
if (friend != null) // Found it
{
// Store it on service
if (!StoreRights(requester, friendID, rights))
{
remoteClient.SendAlertMessage("Unable to grant rights.");
return;
}
// Store it in the local cache
int myFlags = friend.MyFlags;
friend.MyFlags = rights;
// Always send this back to the original client
remoteClient.SendChangeUserRights(requester, friendID, rights);
//
// Notify the friend
//
// Try local
if (LocalGrantRights(requester, friendID, myFlags, rights))
return;
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
// TODO: You might want to send the delta to save the lookup
// on the other end!!
m_FriendsSimConnector.GrantRights(region, requester, friendID, myFlags, rights);
}
}
}
else
{
m_log.DebugFormat("[FRIENDS MODULE]: friend {0} not found for {1}", friendID, requester);
}
}
protected virtual FriendInfo GetFriend(FriendInfo[] friends, UUID friendID)
{
foreach (FriendInfo fi in friends)
{
if (fi.Friend == friendID.ToString())
return fi;
}
return null;
}
#region Local
public virtual bool LocalFriendshipOffered(UUID toID, GridInstantMessage im)
{
IClientAPI friendClient = LocateClientObject(toID);
if (friendClient != null)
{
// the prospective friend in this sim as root agent
friendClient.SendInstantMessage(im);
// we're done
return true;
}
return false;
}
public bool LocalFriendshipApproved(UUID userID, string userName, UUID friendID)
{
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
// the prospective friend in this sim as root agent
GridInstantMessage im = new GridInstantMessage(Scene, userID, userName, friendID,
(byte)OpenMetaverse.InstantMessageDialog.FriendshipAccepted, userID.ToString(), false, Vector3.Zero);
friendClient.SendInstantMessage(im);
ICallingCardModule ccm = friendClient.Scene.RequestModuleInterface<ICallingCardModule>();
if (ccm != null)
{
ccm.CreateCallingCard(friendID, userID, UUID.Zero);
}
// Update the local cache
RecacheFriends(friendClient);
// we're done
return true;
}
return false;
}
public bool LocalFriendshipDenied(UUID userID, string userName, UUID friendID)
{
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
// the prospective friend in this sim as root agent
GridInstantMessage im = new GridInstantMessage(Scene, userID, userName, friendID,
(byte)OpenMetaverse.InstantMessageDialog.FriendshipDeclined, userID.ToString(), false, Vector3.Zero);
friendClient.SendInstantMessage(im);
// we're done
return true;
}
return false;
}
public bool LocalFriendshipTerminated(UUID userID, UUID exfriendID)
{
IClientAPI friendClient = LocateClientObject(exfriendID);
if (friendClient != null)
{
// the friend in this sim as root agent
friendClient.SendTerminateFriend(userID);
// update local cache
RecacheFriends(friendClient);
// we're done
return true;
}
return false;
}
public bool LocalGrantRights(UUID userID, UUID friendID, int oldRights, int newRights)
{
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
int changedRights = newRights ^ oldRights;
bool onlineBitChanged = (changedRights & (int)FriendRights.CanSeeOnline) != 0;
if (onlineBitChanged)
{
if ((newRights & (int)FriendRights.CanSeeOnline) == 1)
friendClient.SendAgentOnline(new UUID[] { userID });
else
friendClient.SendAgentOffline(new UUID[] { userID });
}
if(changedRights != 0)
friendClient.SendChangeUserRights(userID, friendID, newRights);
// Update local cache
UpdateLocalCache(userID, friendID, newRights);
return true;
}
return false;
}
public bool LocalStatusNotification(UUID userID, UUID friendID, bool online)
{
//m_log.DebugFormat("[FRIENDS]: Local Status Notify {0} that user {1} is {2}", friendID, userID, online);
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
// the friend in this sim as root agent
if (online)
friendClient.SendAgentOnline(new UUID[] { userID });
else
friendClient.SendAgentOffline(new UUID[] { userID });
// we're done
return true;
}
return false;
}
#endregion
#region Get / Set friends in several flavours
public FriendInfo[] GetFriendsFromCache(UUID userID)
{
UserFriendData friendsData;
lock (m_Friends)
{
if (m_Friends.TryGetValue(userID, out friendsData))
return friendsData.Friends;
}
return EMPTY_FRIENDS;
}
/// <summary>
/// Update local cache only
/// </summary>
/// <param name="userID"></param>
/// <param name="friendID"></param>
/// <param name="rights"></param>
protected void UpdateLocalCache(UUID userID, UUID friendID, int rights)
{
// Update local cache
lock (m_Friends)
{
FriendInfo[] friends = GetFriendsFromCache(friendID);
if(friends != EMPTY_FRIENDS)
{
FriendInfo finfo = GetFriend(friends, userID);
if(finfo!= null)
finfo.TheirFlags = rights;
}
}
}
public virtual FriendInfo[] GetFriendsFromService(IClientAPI client)
{
return FriendsService.GetFriends(client.AgentId);
}
protected void RecacheFriends(IClientAPI client)
{
// FIXME: Ideally, we want to avoid doing this here since it sits the EventManager.OnMakeRootAgent event
// is on the critical path for transferring an avatar from one region to another.
UUID agentID = client.AgentId;
lock (m_Friends)
{
UserFriendData friendsData;
if (m_Friends.TryGetValue(agentID, out friendsData))
friendsData.Friends = GetFriendsFromService(client);
}
}
public bool AreFriendsCached(UUID userID)
{
lock (m_Friends)
return m_Friends.ContainsKey(userID);
}
protected virtual bool StoreRights(UUID agentID, UUID friendID, int rights)
{
FriendsService.StoreFriend(agentID.ToString(), friendID.ToString(), rights);
return true;
}
protected virtual void StoreBackwards(UUID friendID, UUID agentID)
{
FriendsService.StoreFriend(friendID.ToString(), agentID.ToString(), 0);
}
protected virtual void StoreFriendships(UUID agentID, UUID friendID)
{
FriendsService.StoreFriend(agentID.ToString(), friendID.ToString(), (int)FriendRights.CanSeeOnline);
FriendsService.StoreFriend(friendID.ToString(), agentID.ToString(), (int)FriendRights.CanSeeOnline);
}
protected virtual bool DeleteFriendship(UUID agentID, UUID exfriendID)
{
FriendsService.Delete(agentID, exfriendID.ToString());
FriendsService.Delete(exfriendID, agentID.ToString());
return true;
}
#endregion
}
}
| |
#region CopyrightHeader
//
// Copyright by Contributors
//
// 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.txt
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using gov.va.medora.mdo.utils;
using System.Threading;
namespace gov.va.medora.mdo.dao
{
public class ConnectionManager
{
IndexedHashtable cxnTbl;
string modality;
public ConnectionManager(string modality)
{
this.modality = modality;
cxnTbl = new IndexedHashtable();
}
public ConnectionManager(Connection cxn)
{
this.modality = cxn.DataSource.Modality;
cxnTbl = new IndexedHashtable();
addConnection(cxn);
}
public ConnectionManager(DataSource src)
{
this.modality = src.Modality;
DaoFactory df = DaoFactory.getDaoFactory(DaoFactory.getConstant(src.Protocol));
Connection cxn = df.getConnection(src);
cxnTbl = new IndexedHashtable();
addConnection(cxn);
}
internal void checkModality(Connection cxn)
{
checkModality(cxn.DataSource.Modality);
}
internal void checkModality(DataSource src)
{
checkModality(src.Modality);
}
internal void checkModality(string modality)
{
if (modality != this.modality)
{
throw new Exception("Invalid modality");
}
}
public void addConnection(Connection cxn)
{
if (cxnTbl == null)
{
cxnTbl = new IndexedHashtable();
this.modality = cxn.DataSource.Modality;
}
checkModality(cxn);
if (!cxnTbl.ContainsKey(cxn.DataSource.SiteId.Id))
{
cxnTbl.Add(cxn.SiteId.Key,cxn);
}
}
public void addConnection(DataSource src)
{
if (src.Modality != this.modality)
{
throw new Exception("Invalid modality: expected " + this.modality + ", got " + src.Modality);
}
if (!cxnTbl.ContainsKey(src.SiteId.Key))
{
int protocol = DaoFactory.getConstant(src.Protocol);
DaoFactory daoFactory = DaoFactory.getDaoFactory(protocol);
cxnTbl.Add(src.SiteId.Key, daoFactory.getConnection(src));
}
}
public void removeConnection(string siteId)
{
if (cxnTbl.ContainsKey(siteId))
{
Connection cxn = (Connection)cxnTbl.GetValue(siteId);
if (cxn.IsConnected)
{
cxn.disconnect();
}
cxnTbl.Remove(siteId);
}
}
public void addConnections(string sitelist, SiteTable siteTbl)
{
string[] siteIds = StringUtils.split(sitelist, StringUtils.COMMA);
for (int i = 0; i < siteIds.Length; i++)
{
Site site = siteTbl.getSite(siteIds[i]);
if (site == null)
{
throw new Exception("No such site: " + siteIds[i]);
}
DataSource src = site.getDataSourceByModality(this.modality);
if (src == null)
{
throw new Exception("No " + modality + " data source at site " + siteIds[i]);
}
int protocol = DaoFactory.getConstant(src.Protocol);
DaoFactory daoFactory = DaoFactory.getDaoFactory(protocol);
addConnection(daoFactory.getConnection(src));
}
}
public void addConnections(DataSource[] sources)
{
for (int i = 0; i < sources.Length; i++)
{
int protocol = DaoFactory.getConstant(sources[i].Protocol);
DaoFactory daoFactory = DaoFactory.getDaoFactory(protocol);
addConnection(daoFactory.getConnection(sources[i]));
}
}
public void addConnections(IndexedHashtable t)
{
for (int i = 0; i < t.Count; i++)
{
Connection cxn = (Connection)t.GetValue(i);
addConnection(cxn);
}
}
public IndexedHashtable connect()
{
int lth = cxnTbl.Count;
QueryThread[] queries = new QueryThread[lth];
Thread[] threads = new Thread[lth];
for (int i = 0; i < lth; i++)
{
queries[i] = new QueryThread(cxnTbl.GetValue(i), "connect", new Object[0]);
threads[i] = new Thread(new ThreadStart(queries[i].execute));
threads[i].Start();
}
IndexedHashtable result = new IndexedHashtable(lth);
for (int i = 0; i < lth; i++)
{
string key = (string)cxnTbl.GetKey(i);
threads[i].Join();
//Need to report result whether it's a connection or an exception.
if (queries[i].isExceptionResult())
{
result.Add(key, queries[i].Result);
Connection cxn = (Connection)cxnTbl.GetValue(i);
cxn.ErrorMessage = ((Exception)queries[i].Result).Message;
cxn.IsConnected = false;
}
else
{
result.Add(key, ((Connection)cxnTbl.GetValue(key)).DataSource);
}
}
return result;
}
IndexedHashtable getConnections()
{
IndexedHashtable result = new IndexedHashtable();
for (int i = 0; i < cxnTbl.Count; i++)
{
Connection cxn = (Connection)cxnTbl.GetValue(i);
if (cxn.IsConnected)
{
result.Add(cxn.SiteId.Key, cxn);
}
}
if (result.Count == 0)
{
return null;
}
return result;
}
public IndexedHashtable Connections
{
get { return getConnections(); }
}
public Connection getConnection(string id)
{
if (cxnTbl == null || !cxnTbl.ContainsKey(id))
{
return null;
}
return (Connection)cxnTbl.GetValue(id);
}
public Connection LoginConnection
{
get { return (Connection)cxnTbl.GetValue(0); }
}
public IndexedHashtable disconnect()
{
if (cxnTbl.Count == 0)
{
throw new Exception("No connections");
}
// Only disconnect from the ones that are connected
IndexedHashtable myCxns = getConnections();
int lth = myCxns.Count;
QueryThread[] queries = new QueryThread[lth];
Thread[] threads = new Thread[lth];
for (int i = 0; i < lth; i++)
{
queries[i] = new QueryThread(myCxns.GetValue(i), "disconnect", new Object[0]);
threads[i] = new Thread(new ThreadStart(queries[i].execute));
threads[i].Start();
}
IndexedHashtable result = new IndexedHashtable(lth);
for (int i = 0; i < lth; i++)
{
string key = (string)myCxns.GetKey(i);
threads[i].Join();
if (queries[i].isExceptionResult())
{
result.Add(key, queries[i].Result);
}
else
{
result.Add(key, "OK");
}
}
// We only disconnected from connected connections, but we want to clear
// the entire table
cxnTbl = new IndexedHashtable();
return result;
}
public IndexedHashtable disconnectRemoteSites()
{
if (cxnTbl.Count < 2)
{
throw new Exception("No remote connections");
}
// Only disconnect from the ones that are connected
IndexedHashtable myCxns = getConnections();
int lth = myCxns.Count - 1;
QueryThread[] queries = new QueryThread[lth];
Thread[] threads = new Thread[lth];
for (int threadIdx = 0, cxnIdx = 1; threadIdx < lth; threadIdx++, cxnIdx++)
{
queries[threadIdx] = new QueryThread(myCxns.GetValue(cxnIdx), "disconnect", new Object[0]);
threads[threadIdx] = new Thread(new ThreadStart(queries[threadIdx].execute));
threads[threadIdx].Start();
}
IndexedHashtable result = new IndexedHashtable(lth);
for (int threadIdx = 0, cxnIdx = 1; threadIdx < lth; threadIdx++, cxnIdx++)
{
string key = (string)myCxns.GetKey(cxnIdx);
threads[threadIdx].Join();
if (queries[threadIdx].isExceptionResult())
{
result.Add(key, queries[threadIdx].Result);
}
else
{
result.Add(key, "OK");
}
}
// Now remove all but the logon connection from the table
Connection loginCxn = LoginConnection;
cxnTbl = new IndexedHashtable();
cxnTbl.Add(loginCxn.SiteId.Key, loginCxn);
return result;
}
public string Modality
{
get { return modality; }
}
public bool isAuthorized
{
get
{
if (cxnTbl == null || cxnTbl.Count == 0)
{
return false;
}
Connection cxn = (Connection)cxnTbl.GetValue(0);
if (!cxn.IsConnected || cxn.Uid == "")
{
return false;
}
return true;
}
}
public bool isAuthorizedForSite(string sitecode)
{
if (!isAuthorized)
{
return false;
}
Connection cxn = getConnection(sitecode);
if (cxn == null || !cxn.IsConnected || cxn.Uid == "")
{
return false;
}
return true;
}
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// Represents a gRPC channel. Channels are an abstraction of long-lived connections to remote servers.
/// More client objects can reuse the same channel. Creating a channel is an expensive operation compared to invoking
/// a remote call so in general you should reuse a single channel for as many calls as possible.
/// </summary>
public class Channel
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Channel>();
readonly object myLock = new object();
readonly AtomicCounter activeCallCounter = new AtomicCounter();
readonly CancellationTokenSource shutdownTokenSource = new CancellationTokenSource();
readonly string target;
readonly GrpcEnvironment environment;
readonly CompletionQueueSafeHandle completionQueue;
readonly ChannelSafeHandle handle;
readonly Dictionary<string, ChannelOption> options;
bool shutdownRequested;
/// <summary>
/// Creates a channel that connects to a specific host.
/// Port will default to 80 for an unsecure channel and to 443 for a secure channel.
/// </summary>
/// <param name="target">Target of the channel.</param>
/// <param name="credentials">Credentials to secure the channel.</param>
public Channel(string target, ChannelCredentials credentials) :
this(target, credentials, null)
{
}
/// <summary>
/// Creates a channel that connects to a specific host.
/// Port will default to 80 for an unsecure channel or to 443 for a secure channel.
/// </summary>
/// <param name="target">Target of the channel.</param>
/// <param name="credentials">Credentials to secure the channel.</param>
/// <param name="options">Channel options.</param>
public Channel(string target, ChannelCredentials credentials, IEnumerable<ChannelOption> options)
{
this.target = GrpcPreconditions.CheckNotNull(target, "target");
this.options = CreateOptionsDictionary(options);
EnsureUserAgentChannelOption(this.options);
this.environment = GrpcEnvironment.AddRef();
this.completionQueue = this.environment.PickCompletionQueue();
using (var nativeChannelArgs = ChannelOptions.CreateChannelArgs(this.options.Values))
{
var nativeCredentials = credentials.GetNativeCredentials();
if (nativeCredentials != null)
{
this.handle = ChannelSafeHandle.CreateSecure(nativeCredentials, target, nativeChannelArgs);
}
else
{
this.handle = ChannelSafeHandle.CreateInsecure(target, nativeChannelArgs);
}
}
GrpcEnvironment.RegisterChannel(this);
}
/// <summary>
/// Creates a channel that connects to a specific host and port.
/// </summary>
/// <param name="host">The name or IP address of the host.</param>
/// <param name="port">The port.</param>
/// <param name="credentials">Credentials to secure the channel.</param>
public Channel(string host, int port, ChannelCredentials credentials) :
this(host, port, credentials, null)
{
}
/// <summary>
/// Creates a channel that connects to a specific host and port.
/// </summary>
/// <param name="host">The name or IP address of the host.</param>
/// <param name="port">The port.</param>
/// <param name="credentials">Credentials to secure the channel.</param>
/// <param name="options">Channel options.</param>
public Channel(string host, int port, ChannelCredentials credentials, IEnumerable<ChannelOption> options) :
this(string.Format("{0}:{1}", host, port), credentials, options)
{
}
/// <summary>
/// Gets current connectivity state of this channel.
/// After channel has been shutdown, <c>ChannelState.Shutdown</c> will be returned.
/// </summary>
public ChannelState State
{
get
{
return GetConnectivityState(false);
}
}
// cached handler for watch connectivity state
static readonly BatchCompletionDelegate WatchConnectivityStateHandler = (success, ctx, state) =>
{
var tcs = (TaskCompletionSource<bool>) state;
tcs.SetResult(success);
};
/// <summary>
/// Returned tasks completes once channel state has become different from
/// given lastObservedState.
/// If deadline is reached or an error occurs, returned task is cancelled.
/// </summary>
public async Task WaitForStateChangedAsync(ChannelState lastObservedState, DateTime? deadline = null)
{
var result = await TryWaitForStateChangedAsync(lastObservedState, deadline).ConfigureAwait(false);
if (!result)
{
throw new TaskCanceledException("Reached deadline.");
}
}
/// <summary>
/// Returned tasks completes once channel state has become different from
/// given lastObservedState (<c>true</c> is returned) or if the wait has timed out (<c>false</c> is returned).
/// </summary>
public Task<bool> TryWaitForStateChangedAsync(ChannelState lastObservedState, DateTime? deadline = null)
{
GrpcPreconditions.CheckArgument(lastObservedState != ChannelState.Shutdown,
"Shutdown is a terminal state. No further state changes can occur.");
var tcs = new TaskCompletionSource<bool>();
var deadlineTimespec = deadline.HasValue ? Timespec.FromDateTime(deadline.Value) : Timespec.InfFuture;
lock (myLock)
{
if (handle.IsClosed)
{
// If channel has been already shutdown and handle was disposed, we would end up with
// an abandoned completion added to the completion registry. Instead, we make sure we fail early.
throw new ObjectDisposedException(nameof(handle), "Channel handle has already been disposed.");
}
else
{
// pass "tcs" as "state" for WatchConnectivityStateHandler.
handle.WatchConnectivityState(lastObservedState, deadlineTimespec, completionQueue, WatchConnectivityStateHandler, tcs);
}
}
return tcs.Task;
}
/// <summary>Resolved address of the remote endpoint in URI format.</summary>
public string ResolvedTarget
{
get
{
return handle.GetTarget();
}
}
/// <summary>The original target used to create the channel.</summary>
public string Target
{
get
{
return this.target;
}
}
/// <summary>
/// Returns a token that gets cancelled once <c>ShutdownAsync</c> is invoked.
/// </summary>
public CancellationToken ShutdownToken
{
get
{
return this.shutdownTokenSource.Token;
}
}
/// <summary>
/// Allows explicitly requesting channel to connect without starting an RPC.
/// Returned task completes once state Ready was seen. If the deadline is reached,
/// or channel enters the Shutdown state, the task is cancelled.
/// There is no need to call this explicitly unless your use case requires that.
/// Starting an RPC on a new channel will request connection implicitly.
/// </summary>
/// <param name="deadline">The deadline. <c>null</c> indicates no deadline.</param>
public async Task ConnectAsync(DateTime? deadline = null)
{
var currentState = GetConnectivityState(true);
while (currentState != ChannelState.Ready)
{
if (currentState == ChannelState.Shutdown)
{
throw new OperationCanceledException("Channel has reached Shutdown state.");
}
await WaitForStateChangedAsync(currentState, deadline).ConfigureAwait(false);
currentState = GetConnectivityState(false);
}
}
/// <summary>
/// Shuts down the channel cleanly. It is strongly recommended to shutdown
/// all previously created channels before exiting from the process.
/// </summary>
/// <remarks>
/// This method doesn't wait for all calls on this channel to finish (nor does
/// it explicitly cancel all outstanding calls). It is user's responsibility to make sure
/// all the calls on this channel have finished (successfully or with an error)
/// before shutting down the channel to ensure channel shutdown won't impact
/// the outcome of those remote calls.
/// </remarks>
public async Task ShutdownAsync()
{
lock (myLock)
{
GrpcPreconditions.CheckState(!shutdownRequested);
shutdownRequested = true;
}
GrpcEnvironment.UnregisterChannel(this);
shutdownTokenSource.Cancel();
var activeCallCount = activeCallCounter.Count;
if (activeCallCount > 0)
{
Logger.Warning("Channel shutdown was called but there are still {0} active calls for that channel.", activeCallCount);
}
lock (myLock)
{
handle.Dispose();
}
await GrpcEnvironment.ReleaseAsync().ConfigureAwait(false);
}
internal ChannelSafeHandle Handle
{
get
{
return this.handle;
}
}
internal GrpcEnvironment Environment
{
get
{
return this.environment;
}
}
internal CompletionQueueSafeHandle CompletionQueue
{
get
{
return this.completionQueue;
}
}
internal void AddCallReference(object call)
{
activeCallCounter.Increment();
bool success = false;
handle.DangerousAddRef(ref success);
GrpcPreconditions.CheckState(success);
}
internal void RemoveCallReference(object call)
{
handle.DangerousRelease();
activeCallCounter.Decrement();
}
// for testing only
internal long GetCallReferenceCount()
{
return activeCallCounter.Count;
}
private ChannelState GetConnectivityState(bool tryToConnect)
{
try
{
lock (myLock)
{
return handle.CheckConnectivityState(tryToConnect);
}
}
catch (ObjectDisposedException)
{
return ChannelState.Shutdown;
}
}
private static void EnsureUserAgentChannelOption(Dictionary<string, ChannelOption> options)
{
var key = ChannelOptions.PrimaryUserAgentString;
var userAgentString = "";
ChannelOption option;
if (options.TryGetValue(key, out option))
{
// user-provided userAgentString needs to be at the beginning
userAgentString = option.StringValue + " ";
};
// TODO(jtattermusch): it would be useful to also provide .NET/mono version.
userAgentString += string.Format("grpc-csharp/{0}", VersionInfo.CurrentVersion);
options[ChannelOptions.PrimaryUserAgentString] = new ChannelOption(key, userAgentString);
}
private static Dictionary<string, ChannelOption> CreateOptionsDictionary(IEnumerable<ChannelOption> options)
{
var dict = new Dictionary<string, ChannelOption>();
if (options == null)
{
return dict;
}
foreach (var option in options)
{
dict.Add(option.Name, option);
}
return dict;
}
}
}
| |
namespace AjTalk.Language
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class BaseClassDescription : BaseBehavior, IClassDescription
{
private List<string> instancevariables = new List<string>();
private List<string> classvariables = new List<string>();
private List<object> classvariablevalues = new List<object>();
public BaseClassDescription(Machine machine)
: this(null, null, machine, string.Empty)
{
}
public BaseClassDescription(IBehavior behavior, IBehavior superclass, Machine machine, string varnames)
: base(behavior, superclass, machine)
{
IEnumerable<string> names = AsNames(varnames);
foreach (string name in names)
this.DefineInstanceVariable(name);
}
public BaseClassDescription(IBehavior behavior, IBehavior superclass, IClass metaclass, Machine machine, string varnames)
: this(behavior, superclass, machine, varnames)
{
this.SetBehavior(metaclass);
}
public override int NoInstanceVariables
{
get
{
if (this.SuperClass != null)
{
return this.instancevariables.Count + this.SuperClass.NoInstanceVariables;
}
return this.instancevariables.Count;
}
}
public override int NoClassVariables
{
get
{
if (this.SuperClass != null)
{
return this.classvariables.Count + this.SuperClass.NoClassVariables;
}
return this.classvariables.Count;
}
}
public void DefineClassVariable(string varname)
{
if (this.classvariables.Contains(varname))
throw new InvalidOperationException("Class variable already defined");
if (this.SuperClass != null && this.SuperClass is IClassDescription && ((IClassDescription)this.SuperClass).GetClassVariableOffset(varname) >= 0)
throw new InvalidOperationException("Class variable already defined");
this.classvariables.Add(varname);
this.classvariablevalues.Add(null);
}
public void DefineInstanceVariable(string varname)
{
if (varname == null)
{
throw new ArgumentNullException("varname");
}
if (this.instancevariables.Contains(varname))
{
throw new InvalidOperationException(String.Format("Instance Variable {0} already defined", varname));
}
this.instancevariables.Add(varname);
}
public virtual int GetClassVariableOffset(string varname)
{
int offset;
if (this.SuperClass != null && this.SuperClass is IClassDescription)
{
offset = ((IClassDescription)this.SuperClass).GetClassVariableOffset(varname);
if (offset >= 0)
return offset;
}
offset = this.classvariables.IndexOf(varname);
if (offset < 0)
return offset;
if (this.SuperClass != null)
offset += this.SuperClass.NoClassVariables;
return offset;
}
public int GetInstanceVariableOffset(string varname)
{
int offset;
if (this.SuperClass != null && this.SuperClass is IClassDescription)
{
offset = ((IClassDescription)this.SuperClass).GetInstanceVariableOffset(varname);
if (offset >= 0)
{
return offset;
}
}
offset = this.instancevariables.IndexOf(varname);
if (offset >= 0 && this.SuperClass != null && this.SuperClass is IClassDescription)
{
offset += ((IClassDescription)this.SuperClass).NoInstanceVariables;
}
return offset;
}
public ICollection<string> GetInstanceVariableNames()
{
IList<string> names = null;
if (this.SuperClass != null && this.SuperClass is IClassDescription)
{
var supernames = ((IClassDescription)this.SuperClass).GetInstanceVariableNames();
if (supernames != null && supernames.Count > 0)
names = new List<string>(supernames);
}
if (this.instancevariables != null && this.instancevariables.Count > 0)
{
if (names == null)
names = new List<string>();
foreach (var name in this.instancevariables)
names.Add(name);
}
return names;
}
public string GetInstanceVariableNamesAsString()
{
int nv = 0;
StringBuilder sb = new StringBuilder();
if (this.SuperClass != null && this.SuperClass is IClassDescription)
{
string vars = ((IClassDescription)this.SuperClass).GetInstanceVariableNamesAsString();
if (!string.IsNullOrEmpty(vars))
{
nv++;
sb.Append(vars);
}
}
foreach (string varname in this.instancevariables)
{
if (nv > 0)
sb.Append(" ");
sb.Append(varname);
nv++;
}
return sb.ToString();
}
public virtual ICollection<string> GetClassVariableNames()
{
IList<string> names = null;
if (this.SuperClass != null && this.SuperClass is IClassDescription)
{
var supernames = ((IClassDescription)this.SuperClass).GetClassVariableNames();
if (supernames != null && supernames.Count > 0)
names = new List<string>(supernames);
}
if (this.classvariables != null && this.classvariables.Count > 0)
{
if (names == null)
names = new List<string>();
foreach (var name in this.classvariables)
names.Add(name);
}
return names;
}
public virtual string GetClassVariableNamesAsString()
{
int nv = 0;
StringBuilder sb = new StringBuilder();
if (this.SuperClass != null && this.SuperClass is IClassDescription)
{
string vars = ((IClassDescription)this.SuperClass).GetClassVariableNamesAsString();
if (!string.IsNullOrEmpty(vars))
{
nv++;
sb.Append(vars);
}
}
foreach (string varname in this.classvariables)
{
if (nv > 0)
sb.Append(" ");
sb.Append(varname);
nv++;
}
return sb.ToString();
}
public void RedefineClassVariables(string varnames)
{
foreach (var varname in AsNames(varnames))
this.DefineClassVariable(varname);
}
public void RedefineInstanceVariables(string varnames)
{
foreach (var varname in AsNames(varnames))
if (!this.instancevariables.Contains(varname))
this.DefineInstanceVariable(varname);
}
public virtual void SetClassVariable(int offset, object value)
{
if (this.SuperClass != null && this.SuperClass is IClassDescription)
{
int super = this.SuperClass.NoClassVariables;
if (super > offset)
((IClassDescription)this.SuperClass).SetClassVariable(offset, value);
else
this.classvariablevalues[offset - super] = value;
return;
}
this.classvariablevalues[offset] = value;
}
public virtual object GetClassVariable(int offset)
{
if (this.SuperClass != null && this.SuperClass is IClassDescription)
{
int super = this.SuperClass.NoClassVariables;
if (super > offset)
return ((IClassDescription)this.SuperClass).GetClassVariable(offset);
else
return this.classvariablevalues[offset - super];
}
return this.classvariablevalues[offset];
}
private static IEnumerable<string> AsNames(string varnames)
{
if (string.IsNullOrEmpty(varnames))
return new string[] { };
string[] splits = varnames.Split(' ');
IList<string> names = new List<string>();
foreach (string split in splits)
if (!string.IsNullOrEmpty(split))
names.Add(split);
return names;
}
}
}
| |
//------------------------------------------------------------------------------
//
// zf - A command line archiver using the ZipFile class from SharpZipLib
// for compression
//
// Copyright 2006, 2010 John Reilly
//
//------------------------------------------------------------------------------
// Version History
// 1 Initial version ported from sz sample. Some stuff is not used or commented still
// 2 Display files during extract. --env Now shows .NET version information.
// 3 Add usezip64 option as a testing aid.
// 4 Fix format bug in output, remove unused code and other minor refactoring
using System;
using System.IO;
using System.Collections;
using System.Text;
using System.Globalization;
using System.Reflection;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Core;
namespace ICSharpCode.SharpZipLib.Samples.CS.ZF
{
/// <summary>
/// A command line archiver using the <see cref="ZipFile"/> class from SharpZipLib compression library
/// </summary>
public class ZipFileArchiver
{
#region Enumerations
/// <summary>
/// Options for handling overwriting of files.
/// </summary>
enum Overwrite
{
Prompt,
Never,
Always
}
/// <summary>
/// Operations that can be performed
/// </summary>
enum Operation
{
Create, // add files to new archive
Extract, // extract files from existing archive
List, // show contents of existing archive
Delete, // Delete from archive
Add, // Add to archive.
Test, // Test the archive for validity.
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ZipFileArchiver"/> class.
/// </summary>
public ZipFileArchiver()
{
// Do nothing.
}
#endregion
#region Argument Parsing
/// <summary>
/// Parse command line arguments.
/// This is fairly flexible without using any custom classes. Arguments and options can appear
/// in any order and are case insensitive. Arguments for options are signalled with an '='
/// as in -demo=argument, sometimes the '=' can be omitted as well secretly.
/// Grouping of single character options is supported.
/// </summary>
/// <returns>
/// true if arguments are valid such that processing should continue
/// </returns>
bool SetArgs(string[] args)
{
bool result = true;
int argIndex = 0;
while (argIndex < args.Length)
{
if (args[argIndex][0] == '-' || args[argIndex][0] == '/')
{
string option = args[argIndex].Substring(1).ToLower();
string optArg = "";
int parameterIndex = option.IndexOf('=');
if (parameterIndex >= 0)
{
if (parameterIndex < option.Length - 1)
{
optArg = option.Substring(parameterIndex + 1);
}
option = option.Substring(0, parameterIndex);
}
#if OPTIONTEST
Console.WriteLine("args index [{0}] option [{1}] argument [{2}]", argIndex, option, optArg);
#endif
if (option.Length == 0)
{
Console.Error.WriteLine("Invalid argument '{0}'", args[argIndex]);
result = false;
}
else
{
int optionIndex = 0;
while (optionIndex < option.Length)
{
#if OPTIONTEST
Console.WriteLine("optionIndex {0}", optionIndex);
#endif
switch(option[optionIndex])
{
case '-': // long option
optionIndex = option.Length;
switch (option)
{
case "-add":
operation_ = Operation.Add;
break;
case "-create":
operation_ = Operation.Create;
break;
case "-list":
operation_ = Operation.List;
break;
case "-extract":
operation_ = Operation.Extract;
if (optArg.Length > 0)
{
targetOutputDirectory_ = optArg;
}
break;
case "-delete":
operation_ = Operation.Delete;
break;
case "-test":
operation_ = Operation.Test;
break;
case "-env":
ShowEnvironment();
break;
case "-emptydirs":
addEmptyDirectoryEntries_ = true;
break;
case "-data":
testData_ = true;
break;
case "-zip64":
if ( optArg.Length > 0 )
{
switch ( optArg )
{
case "on":
useZip64_ = UseZip64.On;
break;
case "off":
useZip64_ = UseZip64.Off;
break;
case "auto":
useZip64_ = UseZip64.Dynamic;
break;
}
}
break;
case "-encoding":
if (optArg.Length > 0)
{
if (IsNumeric(optArg))
{
try
{
int enc = int.Parse(optArg);
if (Encoding.GetEncoding(enc) != null)
{
#if OPTIONTEST
Console.WriteLine("Encoding set to {0}", enc);
#endif
ZipConstants.DefaultCodePage = enc;
}
else
{
result = false;
Console.Error.WriteLine("Invalid encoding " + args[argIndex]);
}
}
catch (Exception)
{
result = false;
Console.Error.WriteLine("Invalid encoding " + args[argIndex]);
}
}
else
{
try
{
ZipConstants.DefaultCodePage = Encoding.GetEncoding(optArg).CodePage;
}
catch (Exception)
{
result = false;
Console.Error.WriteLine("Invalid encoding " + args[argIndex]);
}
}
}
else
{
result = false;
Console.Error.WriteLine("Missing encoding parameter");
}
break;
case "-version":
ShowVersion();
break;
case "-help":
ShowHelp();
break;
case "-restore-dates":
restoreDateTime_ = true;
break;
default:
Console.Error.WriteLine("Invalid long argument " + args[argIndex]);
result = false;
break;
}
break;
case '?':
ShowHelp();
break;
case 's':
if (optionIndex != 0)
{
result = false;
Console.Error.WriteLine("-s cannot be in a group");
}
else
{
if (optArg.Length > 0)
{
password_ = optArg;
}
else if (option.Length > 1)
{
password_ = option.Substring(1);
}
else
{
Console.Error.WriteLine("Missing argument to " + args[argIndex]);
}
}
optionIndex = option.Length;
break;
case 't':
operation_ = Operation.Test;
break;
case 'c':
operation_ = Operation.Create;
break;
case 'o':
optionIndex += 1;
overwriteFiles = optionIndex < option.Length ? (option[optionIndex] == '+') ? Overwrite.Always : Overwrite.Never : Overwrite.Never;
break;
case 'q':
silent_ = true;
if (overwriteFiles == Overwrite.Prompt)
{
overwriteFiles = Overwrite.Never;
}
break;
case 'r':
recursive_ = true;
break;
case 'v':
operation_ = Operation.List;
break;
case 'x':
if (optionIndex != 0)
{
result = false;
Console.Error.WriteLine("-x cannot be in a group");
}
else
{
operation_ = Operation.Extract;
if (optArg.Length > 0)
{
targetOutputDirectory_ = optArg;
}
}
optionIndex = option.Length;
break;
default:
Console.Error.WriteLine("Invalid argument: " + args[argIndex]);
result = false;
break;
}
++optionIndex;
}
}
}
else
{
#if OPTIONTEST
Console.WriteLine("file spec {0} = '{1}'", argIndex, args[argIndex]);
#endif
fileSpecs_.Add(args[argIndex]);
}
++argIndex;
}
if (fileSpecs_.Count > 0)
{
string checkPath = (string)fileSpecs_[0];
int deviceCheck = checkPath.IndexOf(':');
#if NET_VER_1
if (checkPath.IndexOfAny(Path.InvalidPathChars) >= 0
#else
if (checkPath.IndexOfAny(Path.GetInvalidPathChars()) >= 0
#endif
|| checkPath.IndexOf('*') >= 0 || checkPath.IndexOf('?') >= 0
|| ((deviceCheck >= 0) && (deviceCheck != 1)))
{
Console.WriteLine("There are invalid characters in the specified zip file name");
result = false;
}
}
return result && (fileSpecs_.Count > 0);
}
#endregion
#region Show - Help/Environment/Version
/// <summary>
/// Show encoding/locale information
/// </summary>
void ShowEnvironment()
{
seenHelp_ = true;
Console.Out.WriteLine("");
Console.Out.WriteLine(
"Current encoding is {0}, code page {1}, windows code page {2}",
Console.Out.Encoding.EncodingName,
Console.Out.Encoding.CodePage,
Console.Out.Encoding.WindowsCodePage);
Console.WriteLine("Default code page is {0}",
Encoding.Default.CodePage);
Console.WriteLine( "Current culture LCID 0x{0:X}, {1}", CultureInfo.CurrentCulture.LCID, CultureInfo.CurrentCulture.EnglishName);
Console.WriteLine( "Current thread OEM codepage {0}", System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.OEMCodePage);
Console.WriteLine( "Current thread Mac codepage {0}", System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.MacCodePage);
Console.WriteLine( "Current thread Ansi codepage {0}", System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ANSICodePage);
Console.WriteLine(".NET version {0}", Environment.Version);
}
/// <summary>
/// Display version information
/// </summary>
void ShowVersion()
{
seenHelp_ = true;
Console.Out.WriteLine("ZipFile Archiver v0.3 Copyright 2006 John Reilly");
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies)
{
if (assembly.GetName().Name == "ICSharpCode.SharpZipLib")
{
Console.Out.WriteLine("#ZipLib v{0} {1}", assembly.GetName().Version,
assembly.GlobalAssemblyCache ? "Running from GAC" : "Running from DLL"
);
}
}
Console.Out.WriteLine();
}
/// <summary>
/// Show help on possible options and arguments
/// </summary>
void ShowHelp()
{
if (seenHelp_)
{
return;
}
seenHelp_ = true;
ShowVersion();
Console.Out.WriteLine("usage zf {options} archive files");
Console.Out.WriteLine("");
Console.Out.WriteLine("Options:");
Console.Out.WriteLine("--add Add files to archive");
Console.Out.WriteLine("--create Create new archive");
Console.Out.WriteLine("--data Test archive data"); Console.Out.WriteLine("--delete Delete files from archive");
Console.Out.WriteLine("--encoding=codepage|name Set code page for encoding by name or number");
Console.Out.WriteLine("--extract{=dir} Extract archive contents to dir(default .)");
Console.Out.WriteLine("--help Show this help");
Console.Out.WriteLine("--env Show current environment information" );
Console.Out.WriteLine("--list List archive contents extended format");
Console.Out.WriteLine("--test Test archive for validity");
Console.Out.WriteLine("--version Show version information");
Console.Out.WriteLine("-r Recurse sub-folders");
Console.Out.WriteLine("-s=password Set archive password");
Console.Out.WriteLine("--zip64=[on|off|auto] Zip64 extension handling to use");
/*
Console.Out.WriteLine("--store Store entries (default=deflate)");
Console.Out.WriteLine("--emptydirs Create entries for empty directories");
Console.Out.WriteLine("--restore-dates Restore dates on extraction");
Console.Out.WriteLine("-o+ Overwrite files without prompting");
Console.Out.WriteLine("-o- Never overwrite files");
Console.Out.WriteLine("-q Quiet mode");
*/
Console.Out.WriteLine("");
}
#endregion
#region Archive Listing
void ListArchiveContents(ZipFile zipFile, FileInfo fileInfo)
{
const string headerTitles = "Name Length Ratio Size Date & time CRC-32 Attr";
const string headerUnderline = "------------ ---------- ----- ---------- ------------------- -------- ------";
int entryCount = 0;
long totalCompressedSize = 0;
long totalSize = 0;
foreach (ZipEntry theEntry in zipFile)
{
if ( theEntry.IsDirectory )
{
Console.Out.WriteLine("Directory {0}", theEntry.Name);
}
else if ( !theEntry.IsFile )
{
Console.Out.WriteLine("Non file entry {0}", theEntry.Name);
continue;
}
else
{
if (entryCount == 0)
{
Console.Out.WriteLine(headerTitles);
Console.Out.WriteLine(headerUnderline);
}
++entryCount;
int ratio = GetCompressionRatio(theEntry.CompressedSize, theEntry.Size);
totalSize += theEntry.Size;
totalCompressedSize += theEntry.CompressedSize;
char cryptoDisplay = ( theEntry.IsCrypted ) ? '*' : ' ';
if (theEntry.Name.Length > 12)
{
Console.Out.WriteLine(theEntry.Name);
Console.Out.WriteLine(
"{0,-12}{7} {1,10:0} {2,3}% {3,10:0} {4,10:d} {4:hh:mm:ss} {5,8:x} {6,4}",
"", theEntry.Size, ratio, theEntry.CompressedSize, theEntry.DateTime, theEntry.Crc,
InterpretExternalAttributes(theEntry.HostSystem, theEntry.ExternalFileAttributes),
cryptoDisplay);
}
else
{
Console.Out.WriteLine(
"{0,-12}{7} {1,10:0} {2,3}% {3,10:0} {4,10:d} {4:hh:mm:ss} {5,8:x} {6,4}",
theEntry.Name, theEntry.Size, ratio, theEntry.CompressedSize, theEntry.DateTime, theEntry.Crc,
InterpretExternalAttributes(theEntry.HostSystem, theEntry.ExternalFileAttributes),
cryptoDisplay);
}
}
}
if (entryCount == 0)
{
Console.Out.WriteLine("Archive is empty!");
}
else
{
Console.Out.WriteLine(headerUnderline);
Console.Out.WriteLine(
"{0,-12} {1,10:0} {2,3}% {3,10:0} {4,10:d} {4:hh:mm:ss}",
entryCount.ToString() + " entries", totalSize, GetCompressionRatio(totalCompressedSize, totalSize), fileInfo.Length, fileInfo.LastWriteTime);
}
}
/// <summary>
/// List zip file contents using ZipFile class
/// </summary>
/// <param name="fileName">File to list contents of</param>
void ListArchiveContents(string fileName)
{
try
{
FileInfo fileInfo = new FileInfo(fileName);
if (!fileInfo.Exists)
{
Console.Error.WriteLine("No such file exists {0}", fileName);
}
else
{
Console.Out.WriteLine(fileName);
try
{
using (ZipFile zipFile = new ZipFile(fileName))
{
ListArchiveContents(zipFile, fileInfo);
}
}
catch(Exception ex)
{
Console.Out.WriteLine("Problem reading archive - '{0}'", ex.Message);
}
}
}
catch(Exception exception)
{
Console.Error.WriteLine("Exception during list operation: {0}", exception.Message);
}
}
/// <summary>
/// Execute List operation
/// Currently only Zip files are supported
/// </summary>
/// <param name="fileSpecs">Files to list</param>
void List(ArrayList fileSpecs)
{
foreach (string spec in fileSpecs)
{
string pathName = Path.GetDirectoryName(spec);
if ( (pathName == null) || (pathName.Length == 0) )
{
pathName = @".\";
}
string[] names = Directory.GetFiles(pathName, Path.GetFileName(spec));
if (names.Length == 0)
{
Console.Error.WriteLine("No files found matching {0}", spec);
}
else
{
foreach (string file in names)
{
ListArchiveContents(file);
}
Console.Out.WriteLine("");
}
}
}
#endregion
#region Creation
/// <summary>
/// Create archives based on specifications passed and internal state
/// </summary>
void Create(ArrayList fileSpecs)
{
string zipFileName = fileSpecs[0] as string;
if (Path.GetExtension(zipFileName).Length == 0)
{
zipFileName = Path.ChangeExtension(zipFileName, ".zip");
}
fileSpecs.RemoveAt(0);
if ( (overwriteFiles == Overwrite.Never) && File.Exists(zipFileName))
{
Console.Error.WriteLine("File {0} already exists", zipFileName);
return;
}
try
{
using (ZipFile zf = ZipFile.Create(zipFileName) )
{
zf.Password = password_;
zf.UseZip64 = useZip64_;
zf.BeginUpdate();
activeZipFile_ = zf;
foreach (string spec in fileSpecs)
{
// This can fail with wildcards in spec...
string path = Path.GetDirectoryName(Path.GetFullPath(spec));
string fileSpec = Path.GetFileName(spec);
zf.NameTransform = new ZipNameTransform(path);
FileSystemScanner scanner = new FileSystemScanner(WildcardToRegex(fileSpec));
scanner.ProcessFile = new ProcessFileHandler(ProcessFile);
scanner.ProcessDirectory = new ProcessDirectoryHandler(ProcessDirectory);
scanner.Scan(path, recursive_);
}
zf.CommitUpdate();
}
}
catch (Exception ex)
{
Console.WriteLine("Problem creating archive - '{0}'", ex.Message);
}
}
#endregion
#region Extraction
/// <summary>
/// Extract a file storing its contents.
/// </summary>
/// <param name="inputStream">The input stream to source file contents from.</param>
/// <param name="theEntry">The <see cref="ZipEntry"/> representing the stored file details </param>
/// <param name="targetDir">The directory to store the output.</param>
/// <returns>True if operation is successful; false otherwise.</returns>
bool ExtractFile(Stream inputStream, ZipEntry theEntry, string targetDir)
{
// try and sort out the correct place to save this entry
string entryFileName;
if (Path.IsPathRooted(theEntry.Name))
{
string workName = Path.GetPathRoot(theEntry.Name);
workName = theEntry.Name.Substring(workName.Length);
entryFileName = Path.Combine(Path.GetDirectoryName(workName), Path.GetFileName(theEntry.Name));
}
else
{
entryFileName = theEntry.Name;
}
string targetName = Path.Combine(targetDir, entryFileName);
string fullPath = Path.GetDirectoryName(Path.GetFullPath(targetName));
#if TEST
Console.WriteLine("Decompress targetfile name " + entryFileName);
Console.WriteLine("Decompress targetpath " + fullPath);
#endif
// Could be an option or parameter to allow failure or try creation
if (Directory.Exists(fullPath) == false)
{
try
{
Directory.CreateDirectory(fullPath);
}
catch
{
return false;
}
}
else if (overwriteFiles == Overwrite.Prompt)
{
if (File.Exists(targetName))
{
Console.Write("File " + targetName + " already exists. Overwrite? ");
string readValue;
try
{
readValue = Console.ReadLine();
}
catch
{
readValue = null;
}
if ( (readValue == null) || (readValue.ToLower() != "y") )
{
return true;
}
}
}
if (entryFileName.Length > 0)
{
if ( !silent_ )
{
Console.Write("{0}", targetName);
}
using (FileStream outputStream = File.Create(targetName))
{
StreamUtils.Copy(inputStream, outputStream, GetBuffer());
}
if (restoreDateTime_)
{
File.SetLastWriteTime(targetName, theEntry.DateTime);
}
if ( !silent_ )
{
Console.WriteLine(" OK");
}
}
return true;
}
/// <summary>
/// Decompress a file
/// </summary>
/// <param name="fileName">File to decompress</param>
/// <param name="targetDir">Directory to create output in</param>
/// <returns>true iff all has been done successfully</returns>
bool DecompressArchive(string fileName, string targetDir)
{
bool result = true;
try
{
using (ZipFile zf = new ZipFile(fileName))
{
zf.Password = password_;
foreach ( ZipEntry entry in zf )
{
if ( entry.IsFile )
{
ExtractFile(zf.GetInputStream(entry), entry, targetDir);
}
else
{
if ( !silent_ )
{
Console.WriteLine("Skipping {0}", entry.Name);
}
}
}
if ( !silent_ )
{
Console.WriteLine("Done");
}
}
}
catch(Exception ex)
{
Console.WriteLine("Exception decompressing - '{0}'", ex);
result = false;
}
return result;
}
/// <summary>
/// Extract archives based on user input
/// Allows simple wildcards to specify multiple archives
/// </summary>
void Extract(ArrayList fileSpecs)
{
if ( (targetOutputDirectory_ == null) || (targetOutputDirectory_.Length == 0) )
{
targetOutputDirectory_ = @".\";
}
foreach(string spec in fileSpecs)
{
string [] names;
if ( (spec.IndexOf('*') >= 0) || (spec.IndexOf('?') >= 0) )
{
string pathName = Path.GetDirectoryName(spec);
if ( (pathName == null) || (pathName.Length == 0) )
{
pathName = @".\";
}
names = Directory.GetFiles(pathName, Path.GetFileName(spec));
}
else
{
names = new string[] { spec };
}
foreach (string fileName in names)
{
if (File.Exists(fileName) == false)
{
Console.Error.WriteLine("No such file exists {0}", fileName);
}
else
{
DecompressArchive(fileName, targetOutputDirectory_);
}
}
}
}
#endregion
#region Testing
/// <summary>
/// Handler for test result callbacks.
/// </summary>
/// <param name="status">The current <see cref="TestStatus"/>.</param>
/// <param name="message">The message applicable for this result.</param>
void TestResultHandler(TestStatus status, string message)
{
switch ( status.Operation )
{
case TestOperation.Initialising:
Console.WriteLine("Testing");
break;
case TestOperation.Complete:
Console.WriteLine("Testing complete");
break;
case TestOperation.EntryHeader:
// Not an error if message is null.
if ( message == null )
{
Console.Write("{0} - ", status.Entry.Name);
}
else
{
Console.WriteLine(message);
}
break;
case TestOperation.EntryData:
if ( message != null )
{
Console.WriteLine(message);
}
break;
case TestOperation.EntryComplete:
if ( status.EntryValid )
{
Console.WriteLine("OK");
}
break;
case TestOperation.MiscellaneousTests:
if ( message != null )
{
Console.WriteLine(message);
}
break;
}
}
/// <summary>
/// Test an archive to see if its valid.
/// </summary>
/// <param name="fileSpecs">The files to test.</param>
void Test(ArrayList fileSpecs)
{
string zipFileName = fileSpecs[0] as string;
if (Path.GetExtension(zipFileName).Length == 0)
{
zipFileName = Path.ChangeExtension(zipFileName, ".zip");
}
try
{
using (ZipFile zipFile = new ZipFile(zipFileName))
{
zipFile.Password = password_;
if ( zipFile.TestArchive(testData_, TestStrategy.FindAllErrors,
new ZipTestResultHandler(TestResultHandler)) )
{
Console.Out.WriteLine("Archive test passed");
}
else
{
Console.Out.WriteLine("Archive test failure");
}
}
}
catch(Exception ex)
{
Console.Out.WriteLine("Error list files - '{0}'", ex.Message);
}
}
#endregion
#region Deleting
/// <summary>
/// Delete entries from an archive
/// </summary>
/// <param name="fileSpecs">The file specs to operate on.</param>
void Delete(ArrayList fileSpecs)
{
string zipFileName = fileSpecs[0] as string;
if (Path.GetExtension(zipFileName).Length == 0)
{
zipFileName = Path.ChangeExtension(zipFileName, ".zip");
}
try
{
using (ZipFile zipFile = new ZipFile(zipFileName))
{
zipFile.BeginUpdate();
for ( int i = 1; i < fileSpecs.Count; ++i )
{
zipFile.Delete((string)fileSpecs[i]);
}
zipFile.CommitUpdate();
}
}
catch(Exception ex)
{
Console.WriteLine("Problem deleting files - '{0}'", ex.Message);
}
}
#endregion
#region Adding
/// <summary>
/// Callback for adding a new file.
/// </summary>
/// <param name="sender">The scanner calling this delegate.</param>
/// <param name="args">The event arguments.</param>
void ProcessFile(object sender, ScanEventArgs args)
{
if ( !silent_ )
{
Console.WriteLine(args.Name);
}
activeZipFile_.Add(args.Name);
}
/// <summary>
/// Callback for adding a new directory.
/// </summary>
/// <param name="sender">The scanner calling this delegate.</param>
/// <param name="args">The event arguments.</param>
/// <remarks>Directories are only added if they are empty and
/// the user has specified that empty directories are to be added.</remarks>
void ProcessDirectory(object sender, DirectoryEventArgs args)
{
if ( !args.HasMatchingFiles && addEmptyDirectoryEntries_ )
{
activeZipFile_.AddDirectory(args.Name);
}
}
/// <summary>
/// Add files to an archive
/// </summary>
/// <param name="fileSpecs">The specification for files to add.</param>
void Add(ArrayList fileSpecs)
{
string zipFileName = fileSpecs[0] as string;
if (Path.GetExtension(zipFileName).Length == 0)
{
zipFileName = Path.ChangeExtension(zipFileName, ".zip");
}
fileSpecs.RemoveAt(0);
ZipFile zipFile;
try
{
if ( File.Exists(zipFileName) )
{
zipFile = new ZipFile(zipFileName);
}
else
{
zipFile = ZipFile.Create(zipFileName);
}
using (zipFile)
{
zipFile.Password = password_;
zipFile.UseZip64 = useZip64_;
zipFile.BeginUpdate();
activeZipFile_ = zipFile;
foreach (string spec in fileSpecs)
{
string path = Path.GetDirectoryName(Path.GetFullPath(spec));
string fileSpec = Path.GetFileName(spec);
zipFile.NameTransform = new ZipNameTransform(path);
FileSystemScanner scanner = new FileSystemScanner(WildcardToRegex(fileSpec));
scanner.ProcessFile = new ProcessFileHandler(ProcessFile);
scanner.ProcessDirectory = new ProcessDirectoryHandler(ProcessDirectory);
scanner.Scan(path, recursive_);
}
zipFile.CommitUpdate();
}
}
catch(Exception ex)
{
Console.WriteLine("Problem adding to archive - '{0}'", ex.Message);
}
}
#endregion
#region Class Execute Command
/// <summary>
/// Parse command line arguments and 'execute' them.
/// </summary>
void Execute(string[] args)
{
if (SetArgs(args))
{
if (fileSpecs_.Count == 0)
{
if (!silent_)
{
Console.Out.WriteLine("Nothing to do");
}
}
else
{
switch (operation_)
{
case Operation.List:
List(fileSpecs_);
break;
case Operation.Create:
Create(fileSpecs_);
break;
case Operation.Extract:
Extract(fileSpecs_);
break;
case Operation.Delete:
Delete(fileSpecs_);
break;
case Operation.Add:
Add(fileSpecs_);
break;
case Operation.Test:
Test(fileSpecs_);
break;
}
}
}
else
{
if ( !silent_ )
{
ShowHelp();
}
}
}
#endregion
#region Support Routines
byte[] GetBuffer()
{
if ( buffer_ == null )
{
buffer_ = new byte[bufferSize_];
}
return buffer_;
}
#endregion
#region Static support routines
///<summary>
/// Calculate compression ratio as a percentage
/// This wont allow for expansion (ratio > 100) as the resulting strings can get huge easily
/// </summary>
static int GetCompressionRatio(long packedSize, long unpackedSize)
{
int result = 0;
if ( (unpackedSize > 0) && (unpackedSize >= packedSize) )
{
result = (int) Math.Round((1.0 - ((double)packedSize / (double)unpackedSize)) * 100.0);
}
return result;
}
/// <summary>
/// Interpret attributes in conjunction with operatingSystem
/// </summary>
/// <param name="operatingSystem">The operating system.</param>
/// <param name="attributes">The external attributes.</param>
/// <returns>A string representation of the attributres passed.</returns>
static string InterpretExternalAttributes(int operatingSystem, int attributes)
{
string result = string.Empty;
if ((operatingSystem == 0) || (operatingSystem == 10))
{
if ((attributes & 0x10) != 0)
result = result + "D";
else
result = result + "-";
if ((attributes & 0x08) != 0)
result = result + "V";
else
result = result + "-";
if ((attributes & 0x01) != 0)
result = result + "r";
else
result = result + "-";
if ((attributes & 0x20) != 0)
result = result + "a";
else
result = result + "-";
if ((attributes & 0x04) != 0)
result = result + "s";
else
result = result + "-";
if ((attributes & 0x02) != 0)
result = result + "h";
else
result = result + "-";
// Device
if ((attributes & 0x4) != 0)
result = result + "d";
else
result = result + "-";
// OS is NTFS
if ( operatingSystem == 10 )
{
// Encrypted
if ( (attributes & 0x4000) != 0 )
{
result += "E";
}
else
{
result += "-";
}
// Not content indexed
if ( (attributes & 0x2000) != 0 )
{
result += "n";
}
else
{
result += "-";
}
// Offline
if ( (attributes & 0x1000) != 0 )
{
result += "O";
}
else
{
result += "-";
}
// Compressed
if ( (attributes & 0x0800) != 0 )
{
result += "C";
}
else
{
result += "-";
}
// Reparse point
if ( (attributes & 0x0400) != 0 )
{
result += "R";
}
else
{
result += "-";
}
// Sparse
if ( (attributes & 0x0200) != 0 )
{
result += "S";
}
else
{
result += "-";
}
// Temporary
if ( (attributes & 0x0100) != 0 )
{
result += "T";
}
else
{
result += "-";
}
}
}
return result;
}
/// <summary>
/// Determine if string is numeric [0-9]+
/// </summary>
/// <param name="rhs">string to test</param>
/// <returns>true iff rhs is numeric</returns>
static bool IsNumeric(string rhs)
{
bool result;
if (rhs != null && rhs.Length > 0)
{
result = true;
for (int i = 0; i < rhs.Length; ++i)
{
if (!char.IsDigit(rhs[i]))
{
result = false;
break;
}
}
}
else
{
result = false;
}
return result;
}
/// <summary>
/// Make external attributes suitable for a <see cref="ZipEntry"/>
/// </summary>
/// <param name="info">The <see cref="FileInfo"/> to convert</param>
/// <returns>Returns External Attributes for Zip use</returns>
static int MakeExternalAttributes(FileInfo info)
{
return (int)info.Attributes;
}
/// <summary>
/// Convert a wildcard expression to a regular expression
/// </summary>
/// <param name="wildcard">The wildcard expression to convert.</param>
/// <returns>A regular expression representing the converted wildcard expression.</returns>
static string WildcardToRegex(string wildcard)
{
int dotPos = wildcard.IndexOf('.');
bool dotted = (dotPos >= 0) && (dotPos < wildcard.Length - 1);
string converted = wildcard.Replace(".", @"\.");
converted = converted.Replace("?", ".");
converted = converted.Replace("*", ".*");
converted = converted.Replace("(", @"\(");
converted = converted.Replace(")", @"\)");
if ( dotted )
{
converted += "$";
}
return converted;
}
#endregion
#region Main
/// <summary>
/// Entry point for program, creates archiver and runs it
/// </summary>
/// <param name="args">
/// Command line argument to process
/// </param>
public static void Main(string[] args)
{
ZipFileArchiver zf = new ZipFileArchiver();
zf.Execute(args);
}
#endregion
#region Instance Fields
/// <summary>
/// Has user already seen help output?
/// </summary>
bool seenHelp_;
/// <summary>
/// File specifications possibly with wildcards from command line
/// </summary>
ArrayList fileSpecs_ = new ArrayList();
/// <summary>
/// Create entries for directories with no files
/// </summary>
bool addEmptyDirectoryEntries_;
/// <summary>
/// Apply operations recursively
/// </summary>
bool recursive_;
/// <summary>
/// Operate silently
/// </summary>
bool silent_;
/// <summary>
/// Restore file date and time to that stored in zip file on extraction
/// </summary>
bool restoreDateTime_;
/// <summary>
/// Overwrite files handling
/// </summary>
Overwrite overwriteFiles = Overwrite.Prompt;
/// <summary>
/// Optional password for archive
/// </summary>
string password_;
/// <summary>
/// Where things will go when decompressed.
/// </summary>
string targetOutputDirectory_;
/// <summary>
/// What to do based on parsed command line arguments
/// </summary>
Operation operation_ = Operation.List;
/// <summary>
/// Flag whose value is true if data should be tested; false if it should not.
/// </summary>
bool testData_;
/// <summary>
/// The currently active <see cref="ZipFile"/>.
/// </summary>
/// <remarks>Used for callbacks/delegates</remarks>
ZipFile activeZipFile_;
/// <summary>
/// Buffer used during some operations
/// </summary>
byte[] buffer_;
/// <summary>
/// The size of buffer to provide. <see cref="GetBuffer"></see>
/// </summary>
int bufferSize_ = 4096;
/// <summary>
/// The Zip64 extension use to apply.
/// </summary>
UseZip64 useZip64_ = UseZip64.Off;
#endregion
}
}
| |
#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.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Security.Permissions;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Serialization
{
#if !SILVERLIGHT && !PocketPC && !NET20
internal interface IMetadataTypeAttribute
{
Type MetadataClassType { get; }
}
#endif
internal static class JsonTypeReflector
{
public const string IdPropertyName = "$id";
public const string RefPropertyName = "$ref";
public const string TypePropertyName = "$type";
public const string ValuePropertyName = "$value";
public const string ArrayValuesPropertyName = "$values";
public const string ShouldSerializePrefix = "ShouldSerialize";
public const string SpecifiedPostfix = "Specified";
private static readonly ThreadSafeStore<ICustomAttributeProvider, Type> JsonConverterTypeCache = new ThreadSafeStore<ICustomAttributeProvider, Type>(GetJsonConverterTypeFromAttribute);
#if !SILVERLIGHT && !PocketPC && !NET20
private static readonly ThreadSafeStore<Type, Type> AssociatedMetadataTypesCache = new ThreadSafeStore<Type, Type>(GetAssociateMetadataTypeFromAttribute);
private const string MetadataTypeAttributeTypeName =
"System.ComponentModel.DataAnnotations.MetadataTypeAttribute, System.ComponentModel.DataAnnotations, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
private static Type _cachedMetadataTypeAttributeType;
#endif
#if SILVERLIGHT
private static readonly ThreadSafeStore<ICustomAttributeProvider, Type> TypeConverterTypeCache = new ThreadSafeStore<ICustomAttributeProvider, Type>(GetTypeConverterTypeFromAttribute);
private static Type GetTypeConverterTypeFromAttribute(ICustomAttributeProvider attributeProvider)
{
TypeConverterAttribute converterAttribute = GetAttribute<TypeConverterAttribute>(attributeProvider);
if (converterAttribute == null)
return null;
return Type.GetType(converterAttribute.ConverterTypeName);
}
private static Type GetTypeConverterType(ICustomAttributeProvider attributeProvider)
{
return TypeConverterTypeCache.Get(attributeProvider);
}
#endif
public static JsonContainerAttribute GetJsonContainerAttribute(Type type)
{
return CachedAttributeGetter<JsonContainerAttribute>.GetAttribute(type);
}
public static JsonObjectAttribute GetJsonObjectAttribute(Type type)
{
return GetJsonContainerAttribute(type) as JsonObjectAttribute;
}
public static JsonArrayAttribute GetJsonArrayAttribute(Type type)
{
return GetJsonContainerAttribute(type) as JsonArrayAttribute;
}
#if !PocketPC && !NET20
public static DataContractAttribute GetDataContractAttribute(Type type)
{
// DataContractAttribute does not have inheritance
DataContractAttribute result = null;
Type currentType = type;
while (result == null && currentType != null)
{
result = CachedAttributeGetter<DataContractAttribute>.GetAttribute(currentType);
currentType = currentType.BaseType;
}
return result;
}
public static DataMemberAttribute GetDataMemberAttribute(MemberInfo memberInfo)
{
// DataMemberAttribute does not have inheritance
// can't override a field
if (memberInfo.MemberType == MemberTypes.Field)
return CachedAttributeGetter<DataMemberAttribute>.GetAttribute(memberInfo);
// search property and then search base properties if nothing is returned and the property is virtual
PropertyInfo propertyInfo = (PropertyInfo) memberInfo;
DataMemberAttribute result = CachedAttributeGetter<DataMemberAttribute>.GetAttribute(propertyInfo);
if (result == null)
{
if (propertyInfo.IsVirtual())
{
Type currentType = propertyInfo.DeclaringType;
while (result == null && currentType != null)
{
PropertyInfo baseProperty = (PropertyInfo)ReflectionUtils.GetMemberInfoFromType(currentType, propertyInfo);
if (baseProperty != null && baseProperty.IsVirtual())
result = CachedAttributeGetter<DataMemberAttribute>.GetAttribute(baseProperty);
currentType = currentType.BaseType;
}
}
}
return result;
}
#endif
public static MemberSerialization GetObjectMemberSerialization(Type objectType)
{
JsonObjectAttribute objectAttribute = GetJsonObjectAttribute(objectType);
if (objectAttribute == null)
{
#if !PocketPC && !NET20
DataContractAttribute dataContractAttribute = GetDataContractAttribute(objectType);
if (dataContractAttribute != null)
return MemberSerialization.OptIn;
#endif
return MemberSerialization.OptOut;
}
return objectAttribute.MemberSerialization;
}
private static Type GetJsonConverterType(ICustomAttributeProvider attributeProvider)
{
return JsonConverterTypeCache.Get(attributeProvider);
}
private static Type GetJsonConverterTypeFromAttribute(ICustomAttributeProvider attributeProvider)
{
JsonConverterAttribute converterAttribute = GetAttribute<JsonConverterAttribute>(attributeProvider);
return (converterAttribute != null)
? converterAttribute.ConverterType
: null;
}
public static JsonConverter GetJsonConverter(ICustomAttributeProvider attributeProvider, Type targetConvertedType)
{
Type converterType = GetJsonConverterType(attributeProvider);
if (converterType != null)
{
JsonConverter memberConverter = JsonConverterAttribute.CreateJsonConverterInstance(converterType);
if (!memberConverter.CanConvert(targetConvertedType))
throw new JsonSerializationException("JsonConverter {0} on {1} is not compatible with member type {2}.".FormatWith(CultureInfo.InvariantCulture, memberConverter.GetType().Name, attributeProvider, targetConvertedType.Name));
return memberConverter;
}
return null;
}
#if !PocketPC
public static TypeConverter GetTypeConverter(Type type)
{
#if !SILVERLIGHT
return TypeDescriptor.GetConverter(type);
#else
Type converterType = GetTypeConverterType(type);
if (converterType != null)
return (TypeConverter)ReflectionUtils.CreateInstance(converterType);
return null;
#endif
}
#endif
#if !SILVERLIGHT && !PocketPC && !NET20
private static Type GetAssociatedMetadataType(Type type)
{
return AssociatedMetadataTypesCache.Get(type);
}
private static Type GetAssociateMetadataTypeFromAttribute(Type type)
{
Type metadataTypeAttributeType = GetMetadataTypeAttributeType();
if (metadataTypeAttributeType == null)
return null;
object attribute = type.GetCustomAttributes(metadataTypeAttributeType, true).SingleOrDefault();
if (attribute == null)
return null;
IMetadataTypeAttribute metadataTypeAttribute = (DynamicCodeGeneration)
? DynamicWrapper.CreateWrapper<IMetadataTypeAttribute>(attribute)
: new LateBoundMetadataTypeAttribute(attribute);
return metadataTypeAttribute.MetadataClassType;
}
private static Type GetMetadataTypeAttributeType()
{
// always attempt to get the metadata type attribute type
// the assembly may have been loaded since last time
if (_cachedMetadataTypeAttributeType == null)
{
Type metadataTypeAttributeType = Type.GetType(MetadataTypeAttributeTypeName);
if (metadataTypeAttributeType != null)
_cachedMetadataTypeAttributeType = metadataTypeAttributeType;
else
return null;
}
return _cachedMetadataTypeAttributeType;
}
#endif
private static T GetAttribute<T>(Type type) where T : Attribute
{
T attribute;
#if !SILVERLIGHT && !PocketPC && !NET20
Type metadataType = GetAssociatedMetadataType(type);
if (metadataType != null)
{
attribute = ReflectionUtils.GetAttribute<T>(metadataType, true);
if (attribute != null)
return attribute;
}
#endif
attribute = ReflectionUtils.GetAttribute<T>(type, true);
if (attribute != null)
return attribute;
foreach (Type typeInterface in type.GetInterfaces())
{
attribute = ReflectionUtils.GetAttribute<T>(typeInterface, true);
if (attribute != null)
return attribute;
}
return null;
}
private static T GetAttribute<T>(MemberInfo memberInfo) where T : Attribute
{
T attribute;
#if !SILVERLIGHT && !PocketPC && !NET20
Type metadataType = GetAssociatedMetadataType(memberInfo.DeclaringType);
if (metadataType != null)
{
MemberInfo metadataTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(metadataType, memberInfo);
if (metadataTypeMemberInfo != null)
{
attribute = ReflectionUtils.GetAttribute<T>(metadataTypeMemberInfo, true);
if (attribute != null)
return attribute;
}
}
#endif
attribute = ReflectionUtils.GetAttribute<T>(memberInfo, true);
if (attribute != null)
return attribute;
foreach (Type typeInterface in memberInfo.DeclaringType.GetInterfaces())
{
MemberInfo interfaceTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(typeInterface, memberInfo);
if (interfaceTypeMemberInfo != null)
{
attribute = ReflectionUtils.GetAttribute<T>(interfaceTypeMemberInfo, true);
if (attribute != null)
return attribute;
}
}
return null;
}
public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider) where T : Attribute
{
Type type = attributeProvider as Type;
if (type != null)
return GetAttribute<T>(type);
MemberInfo memberInfo = attributeProvider as MemberInfo;
if (memberInfo != null)
return GetAttribute<T>(memberInfo);
return ReflectionUtils.GetAttribute<T>(attributeProvider, true);
}
private static bool? _dynamicCodeGeneration;
public static bool DynamicCodeGeneration
{
get
{
if (_dynamicCodeGeneration == null)
{
#if !PocketPC && !SILVERLIGHT && !MONODROID
try
{
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess).Demand();
new SecurityPermission(SecurityPermissionFlag.SkipVerification).Demand();
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
new SecurityPermission(PermissionState.Unrestricted).Demand();
_dynamicCodeGeneration = true;
}
catch (Exception)
{
_dynamicCodeGeneration = false;
}
#else
_dynamicCodeGeneration = false;
#endif
}
return _dynamicCodeGeneration.Value;
}
}
public static ReflectionDelegateFactory ReflectionDelegateFactory
{
get
{
#if !PocketPC && !SILVERLIGHT
if (DynamicCodeGeneration)
return DynamicReflectionDelegateFactory.Instance;
#endif
return LateBoundReflectionDelegateFactory.Instance;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections;
namespace bin2packbin
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 3)
{
Console.WriteLine("Syntax:\r\n\r\nbin2packbin source-directory target-directory header-directory\r\n\r\n");
return;
}
string source_path;
string target_path;
string header_path;
source_path = args[0];
target_path = args[1];
header_path = args[2];
if (!Directory.Exists(source_path))
{
Console.WriteLine("Source path not found\r\n");
return;
}
if (!Directory.Exists(target_path))
{
Console.WriteLine("Target path not found\r\n");
return;
}
DirectoryInfo sourceDir = new DirectoryInfo(source_path);
DirectoryInfo targetDir = new DirectoryInfo(target_path);
int counter = 0;
string name1 = "";
string name2 = "";
string name3 = "";
int n = 0;
const string NumberFormat = "0";
ArrayGenerator ag = null;
using (StreamWriter swDefine = new StreamWriter(header_path + "\\binaries.h"))
{
swDefine.WriteLine("");
swDefine.WriteLine();
using (StreamWriter swArrays = new StreamWriter(header_path + "\\binaries.cpp"))
{
swArrays.WriteLine("#include \"binaries.h\"");
swArrays.WriteLine();
foreach (FileInfo file in sourceDir.GetFiles("*.bin"))
{
string[] c1 = file.Name.Split('.');
string[] c2 = c1[0].Split('_');
string nname1;
string nname2;
string nname3;
nname1 = c2[0];
if (c2.Length > 1) nname2 = c2[1]; else nname2 = "";
if (c2.Length > 2) nname3 = c2[2]; else nname3 = "";
if ((nname1 != name1) || (nname2 != name2) || (nname3 != name3) || (n != c2.Length))
{
if (name1 != "")
{
if (ag != null)
{
ag.PrintHeader(swDefine);
ag.Print(swArrays);
ag = null;
}
}
name1 = nname1;
name2 = nname2;
name3 = nname3;
n = c2.Length;
if (c2.Length == 4)
{
ag = new ArrayGenerator(name1, name2, name3);
}
}
if (ag != null) ag.AddLine(int.Parse(c2[3]), counter.ToString(NumberFormat));
// Console.WriteLine(target_path + "\\" + counter.ToString(NumberFormat));
file.CopyTo(target_path + "\\" + counter.ToString(NumberFormat) + ".bin", true);
swDefine.WriteLine("#define " + file.Name.Replace('.', '_') + " " + counter.ToString(NumberFormat) + "");
counter++;
}
if (ag != null)
{
ag.Print(swArrays);
ag = null;
}
Console.WriteLine("bin2packbin: " + counter.ToString() + " files written to " + target_path);
}
Console.ReadLine();
}
}
}
class ArrayGenerator
{
private ArrayList list = null;
private string n1;
private string n2;
private string n3;
public ArrayGenerator(string name1, string name2, string name3)
{
n1 = name1;
n2 = name2;
n3 = name3;
list = new ArrayList();
}
public void AddLine(int id, string value)
{
list.Add(new ArrayGeneratorLine(id,value));
}
public void Print(StreamWriter sw)
{
if (list != null)
{
list.Sort();
sw.WriteLine("unsigned short int ar_" + n1 + "_" + n2 + "_" + n3 + "_count = " + list.Count.ToString() + ";");
sw.Write("unsigned short int ar_" + n1 + "_" + n2 + "_" + n3 + " [" + list.Count.ToString() + "] = { ");
foreach (object obj in list)
{
sw.Write("" + ((ArrayGeneratorLine)obj).Filename + ",");
}
sw.WriteLine("};");
}
}
public void PrintHeader(StreamWriter sw)
{
if (list != null)
{
list.Sort();
sw.WriteLine("extern unsigned short int ar_" + n1 + "_" + n2 + "_" + n3 + " [" + list.Count.ToString() + "];");
sw.WriteLine("extern unsigned short int ar_" + n1 + "_" + n2 + "_" + n3 + "_count;");
}
}
}
class ArrayGeneratorLine : IComparable
{
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
private string _filename;
public string Filename
{
get { return _filename; }
set { _filename = value; }
}
public ArrayGeneratorLine(int id, string filename)
{
_id = id;
_filename = filename;
}
#region IComparable Members
public int CompareTo(object obj)
{
return _id.CompareTo(((ArrayGeneratorLine)obj).Id);
}
#endregion
}
}
| |
namespace AgileObjects.AgileMapper.UnitTests.Configuration.MemberIgnores
{
using System;
using AgileMapper.Extensions.Internal;
using Common;
using NetStandardPolyfills;
using TestClasses;
#if !NET35
using Xunit;
#else
using Fact = NUnit.Framework.TestAttribute;
[NUnit.Framework.TestFixture]
#endif
public class WhenIgnoringMembersByGlobalFilter
{
[Fact]
public void ShouldIgnoreMembersByType()
{
using (var mapper = Mapper.CreateNew())
{
mapper.WhenMapping
.IgnoreTargetMembersOfType<long>();
var source = new { Value1 = 1, Value2 = 2 };
var result = mapper.Map(source).ToANew<PublicTwoFields<int, long>>();
result.Value1.ShouldBe(1);
result.Value2.ShouldBeDefault();
}
}
[Fact]
public void ShouldIgnoreObjectMembersByType()
{
using (var mapper = Mapper.CreateNew())
{
mapper.WhenMapping
.IgnoreTargetMembersOfType<object>();
var source = new { Value1 = "object?!", Value2 = new { Line1 = "Address!" } };
var result = mapper.Map(source).ToANew<PublicTwoFields<object, Address>>();
result.Value1.ShouldBeNull();
result.Value2.ShouldNotBeNull();
result.Value2.Line1.ShouldBe("Address!");
}
}
[Fact]
public void ShouldIgnoreComplexTypeMembersByType()
{
using (var mapper = Mapper.CreateNew())
{
mapper.WhenMapping
.IgnoreTargetMembersOfType<Address>();
var source = new { Value = new { Line1 = "Nope" } };
var result = mapper.Map(source).ToANew<PublicField<Address>>();
result.Value.ShouldBeNull();
}
}
[Fact]
public void ShouldIgnoreDerivedComplexTypeMembersByType()
{
using (var mapper = Mapper.CreateNew())
{
mapper.WhenMapping
.IgnoreTargetMembersOfType<PersonViewModel>();
var source = new { value1 = 123, Value2 = new { Name = "Larry" } };
var result = mapper.Map(source).ToANew<PublicTwoFields<int, CustomerViewModel>>();
result.Value1.ShouldBe(123);
result.Value2.ShouldBeNull();
}
}
[Fact]
public void ShouldIgnorePropertiesByMemberType()
{
using (var mapper = Mapper.CreateNew())
{
mapper.WhenMapping
.IgnoreTargetMembersWhere(member => member.IsProperty);
var source = new { Value = "Don't ignore me!" };
var propertyResult = mapper.Map(source).ToANew<PublicProperty<string>>();
var setMethodResult = mapper.Map(source).ToANew<PublicSetMethod<string>>();
propertyResult.Value.ShouldBeDefault();
setMethodResult.Value.ShouldBe("Don't ignore me!");
}
}
[Fact]
public void ShouldIgnorePropertiesByPropertyInfoMatcher()
{
using (var mapper = Mapper.CreateNew())
{
mapper.WhenMapping
.IgnoreTargetMembersWhere(member =>
member.IsPropertyMatching(p => p.GetSetMethod().Name.EndsWith("Line2")));
var source = new { Line1 = "hfjdk", Line2 = "kejkwen" };
var result = mapper.Map(source).ToANew<Address>();
result.Line1.ShouldBe("hfjdk");
result.Line2.ShouldBeNull();
}
}
[Fact]
public void ShouldIgnoreFieldsByMemberType()
{
using (var mapper = Mapper.CreateNew())
{
mapper.WhenMapping
.IgnoreTargetMembersWhere(member => member.IsField);
var source = new { Value = 873982 };
var setMethodResult = mapper.Map(source).ToANew<PublicSetMethod<long>>();
var fieldResult = mapper.Map(source).ToANew<PublicField<long>>();
fieldResult.Value.ShouldBeDefault();
setMethodResult.Value.ShouldBe(873982);
}
}
[Fact]
public void ShouldIgnoreFieldsByFieldInfoMatcher()
{
using (var mapper = Mapper.CreateNew())
{
var field1HashCode = typeof(PublicTwoFields<string, string>)
.GetPublicInstanceField("Value1")
.GetHashCode();
mapper.WhenMapping
.IgnoreTargetMembersWhere(member =>
member.IsFieldMatching(f => f.GetHashCode() == field1HashCode));
var source = new { Value1 = "koewlkswmj", Value2 = "lkgflkmdelk" };
var result = mapper.Map(source).ToANew<PublicTwoFields<string, string>>();
result.Value1.ShouldBeNull();
result.Value2.ShouldBe("lkgflkmdelk");
}
}
[Fact]
public void ShouldIgnoreSetMethodsByMemberType()
{
using (var mapper = Mapper.CreateNew())
{
mapper.WhenMapping
.IgnoreTargetMembersWhere(member => member.IsSetMethod);
var source = new { Value = 123 };
var setMethodResult = mapper.Map(source).ToANew<PublicSetMethod<int>>();
var fieldResult = mapper.Map(source).ToANew<PublicField<int>>();
setMethodResult.Value.ShouldBeDefault();
fieldResult.Value.ShouldBe(123);
}
}
[Fact]
public void ShouldIgnoreSetMethodsByMethodInfoMatcher()
{
using (var mapper = Mapper.CreateNew())
{
mapper.WhenMapping
.IgnoreTargetMembersWhere(member =>
member.IsSetMethodMatching(m =>
m.GetParameters().First().ParameterType == typeof(int)));
var source = new { Value = "673473" };
var intResult = mapper.Map(source).ToANew<PublicSetMethod<int>>();
intResult.Value.ShouldBeDefault();
var longResult = mapper.Map(source).ToANew<PublicSetMethod<long>>();
longResult.Value.ShouldBe(673473L);
}
}
[Fact]
public void ShouldIgnoreMembersByNameMatch()
{
using (var mapper = Mapper.CreateNew())
{
mapper.WhenMapping
.IgnoreTargetMembersWhere(member => member.Name.Contains("Value2"));
var source = new { Value1 = "One!", Value2 = "Two!" };
var result = mapper.Map(source).ToANew<PublicTwoFields<string, string>>();
result.Value1.ShouldBe("One!");
result.Value2.ShouldBeDefault();
}
}
[Fact]
public void ShouldIgnoreMembersByPathMatch()
{
using (var mapper = Mapper.CreateNew())
{
var source = new { Address = new Address { Line1 = "ONE!", Line2 = "TWO!" } };
mapper.WhenMapping
.IgnoreTargetMembersWhere(member => member.Path.EqualsIgnoreCase("Value.Line1"));
mapper.WhenMapping
.From(source)
.To<PublicField<Address>>()
.Map((s, pf) => s.Address)
.To(pf => pf.Value);
var result = mapper.Map(source).ToANew<PublicField<Address>>();
result.Value.Line1.ShouldBeDefault();
result.Value.Line2.ShouldBe("TWO!");
}
}
[Fact]
public void ShouldIgnoreMembersByAttribute()
{
using (var mapper = Mapper.CreateNew())
{
mapper.WhenMapping
.IgnoreTargetMembersWhere(member => member.HasAttribute<IgnoreMeAttribute>());
var source = new { Value1 = "hgfd", Value2 = default(string) };
var result = mapper.Map(source).ToANew<AttributeHelper>();
result.Value1.ShouldBeNull();
}
}
[Fact]
public void ShouldNotAttemptToIgnoreAttributedConstructorParameters()
{
using (var mapper = Mapper.CreateNew())
{
mapper.WhenMapping
.IgnoreTargetMembersWhere(member => member.HasAttribute<IgnoreMeAttribute>());
var source = new { Value2 = "hjkhgff" };
var result = mapper.Map(source).ToANew<AttributeHelper>();
result.Value1.ShouldBeNull();
result.Value2.ShouldBe("hjkhgff");
}
}
[Fact]
public void ShouldSupportOverlappingIgnoreFilters()
{
using (var mapper = Mapper.CreateNew())
{
mapper.WhenMapping
.IgnoreTargetMembersOfType<Address>()
.AndWhenMapping
.IgnoreTargetMembersWhere(member => member.IsProperty);
var source = new { Value = new Address { Line1 = "ONE!", Line2 = "TWO!" } };
var result = mapper.Map(source).ToANew<PublicProperty<Address>>();
result.Value.ShouldBeNull();
}
}
#region Helper Classes
public class AttributeHelper
{
public AttributeHelper([IgnoreMe]string value2)
{
Value2 = value2;
}
[IgnoreMe]
public string Value1 { get; set; }
public string Value2 { get; }
}
public sealed class IgnoreMeAttribute : Attribute
{
}
#endregion
}
}
| |
using System;
using Csla;
using SelfLoad.DataAccess;
using SelfLoad.DataAccess.ERLevel;
namespace SelfLoad.Business.ERLevel
{
/// <summary>
/// C11_City_Child (editable child object).<br/>
/// This is a generated base class of <see cref="C11_City_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="C10_City"/> collection.
/// </remarks>
[Serializable]
public partial class C11_City_Child : BusinessBase<C11_City_Child>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="City_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> City_Child_NameProperty = RegisterProperty<string>(p => p.City_Child_Name, "CityRoads Child Name");
/// <summary>
/// Gets or sets the CityRoads Child Name.
/// </summary>
/// <value>The CityRoads Child Name.</value>
public string City_Child_Name
{
get { return GetProperty(City_Child_NameProperty); }
set { SetProperty(City_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="C11_City_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="C11_City_Child"/> object.</returns>
internal static C11_City_Child NewC11_City_Child()
{
return DataPortal.CreateChild<C11_City_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="C11_City_Child"/> object, based on given parameters.
/// </summary>
/// <param name="city_ID1">The City_ID1 parameter of the C11_City_Child to fetch.</param>
/// <returns>A reference to the fetched <see cref="C11_City_Child"/> object.</returns>
internal static C11_City_Child GetC11_City_Child(int city_ID1)
{
return DataPortal.FetchChild<C11_City_Child>(city_ID1);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="C11_City_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public C11_City_Child()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="C11_City_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="C11_City_Child"/> object from the database, based on given criteria.
/// </summary>
/// <param name="city_ID1">The City ID1.</param>
protected void Child_Fetch(int city_ID1)
{
var args = new DataPortalHookArgs(city_ID1);
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var dal = dalManager.GetProvider<IC11_City_ChildDal>();
var data = dal.Fetch(city_ID1);
Fetch(data);
}
OnFetchPost(args);
}
/// <summary>
/// Loads a <see cref="C11_City_Child"/> object from the given <see cref="C11_City_ChildDto"/>.
/// </summary>
/// <param name="data">The C11_City_ChildDto to use.</param>
private void Fetch(C11_City_ChildDto data)
{
// Value properties
LoadProperty(City_Child_NameProperty, data.City_Child_Name);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="C11_City_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(C10_City parent)
{
var dto = new C11_City_ChildDto();
dto.Parent_City_ID = parent.City_ID;
dto.City_Child_Name = City_Child_Name;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IC11_City_ChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="C11_City_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(C10_City parent)
{
if (!IsDirty)
return;
var dto = new C11_City_ChildDto();
dto.Parent_City_ID = parent.City_ID;
dto.City_Child_Name = City_Child_Name;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IC11_City_ChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="C11_City_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(C10_City parent)
{
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IC11_City_ChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.City_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Copyright 2015 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.
using UnityEngine;
using System.Runtime.InteropServices;
/// @cond
namespace Gvr.Internal {
public abstract class GvrDevice :
#if UNITY_ANDROID
BaseAndroidDevice
#else
BaseVRDevice
#endif
{
// A relatively unique id to use when calling our C++ native render plugin.
private const int kRenderEvent = 0x47554342;
// Event IDs sent up from native layer. Bit flags.
// Keep in sync with the corresponding declaration in unity.h.
private const int kTilted = 1 << 1;
private const int kProfileChanged = 1 << 2;
private const int kVRBackButtonPressed = 1 << 3;
private float[] headData = new float[16];
private float[] viewData = new float[16 * 6 + 12];
private float[] profileData = new float[13];
private Matrix4x4 headView = new Matrix4x4();
private Matrix4x4 leftEyeView = new Matrix4x4();
private Matrix4x4 rightEyeView = new Matrix4x4();
protected bool debugDisableNativeProjections = false;
protected bool debugDisableNativeUILayer = false;
public override void SetDistortionCorrectionEnabled(bool enabled) {
EnableDistortionCorrection(enabled);
}
public override void SetNeckModelScale(float scale) {
SetNeckModelFactor(scale);
}
public override bool SetDefaultDeviceProfile(System.Uri uri) {
byte[] profile = System.Text.Encoding.UTF8.GetBytes(uri.ToString());
return SetDefaultProfile(profile, profile.Length);
}
public override void Init() {
// Start will send a log event, so SetUnityVersion first.
byte[] version = System.Text.Encoding.UTF8.GetBytes(Application.unityVersion);
SetUnityVersion(version, version.Length);
Start();
}
public override void UpdateState() {
ProcessEvents();
GetHeadPose(headData);
ExtractMatrix(ref headView, headData);
headPose.SetRightHanded(headView.inverse);
}
public override void UpdateScreenData() {
UpdateProfile();
if (debugDisableNativeProjections) {
ComputeEyesFromProfile();
} else {
UpdateView();
}
profileChanged = true;
}
public override void Recenter() {
ResetHeadTracker();
}
public override void PostRender(RenderTexture stereoScreen) {
SetTextureId((int)stereoScreen.GetNativeTexturePtr());
// Disable obsolete warnings - we don't need to pass in a callback here.
#pragma warning disable 618
GL.IssuePluginEvent(kRenderEvent);
#pragma warning restore 618
}
public override void OnPause(bool pause) {
if (pause) {
Pause();
} else {
Resume();
}
}
public override void OnApplicationQuit() {
Stop();
base.OnApplicationQuit();
}
private void UpdateView() {
GetViewParameters(viewData);
int j = 0;
j = ExtractMatrix(ref leftEyeView, viewData, j);
j = ExtractMatrix(ref rightEyeView, viewData, j);
leftEyePose.SetRightHanded(leftEyeView.inverse);
rightEyePose.SetRightHanded(rightEyeView.inverse);
j = ExtractMatrix(ref leftEyeDistortedProjection, viewData, j);
j = ExtractMatrix(ref rightEyeDistortedProjection, viewData, j);
j = ExtractMatrix(ref leftEyeUndistortedProjection, viewData, j);
j = ExtractMatrix(ref rightEyeUndistortedProjection, viewData, j);
leftEyeUndistortedViewport.Set(viewData[j], viewData[j+1], viewData[j+2], viewData[j+3]);
leftEyeDistortedViewport = leftEyeUndistortedViewport;
j += 4;
rightEyeUndistortedViewport.Set(viewData[j], viewData[j+1], viewData[j+2], viewData[j+3]);
rightEyeDistortedViewport = rightEyeUndistortedViewport;
j += 4;
leftEyeOrientation = (int)viewData[j];
rightEyeOrientation = (int)viewData[j+1];
j += 2;
recommendedTextureSize = new Vector2(viewData[j], viewData[j+1]);
j += 2;
}
private void UpdateProfile() {
GetProfile(profileData);
GvrProfile.Viewer device = new GvrProfile.Viewer();
GvrProfile.Screen screen = new GvrProfile.Screen();
device.maxFOV.outer = profileData[0];
device.maxFOV.upper = profileData[1];
device.maxFOV.inner = profileData[2];
device.maxFOV.lower = profileData[3];
screen.width = profileData[4];
screen.height = profileData[5];
screen.border = profileData[6];
device.lenses.separation = profileData[7];
device.lenses.offset = profileData[8];
device.lenses.screenDistance = profileData[9];
device.lenses.alignment = (int)profileData[10];
device.distortion.Coef = new [] { profileData[11], profileData[12] };
Profile.screen = screen;
Profile.viewer = device;
float[] rect = new float[4];
Profile.GetLeftEyeNoLensTanAngles(rect);
float maxRadius = GvrProfile.GetMaxRadius(rect);
Profile.viewer.inverse = GvrProfile.ApproximateInverse(
Profile.viewer.distortion, maxRadius);
}
private static int ExtractMatrix(ref Matrix4x4 mat, float[] data, int i = 0) {
// Matrices returned from our native layer are in row-major order.
for (int r = 0; r < 4; r++) {
for (int c = 0; c < 4; c++, i++) {
mat[r, c] = data[i];
}
}
return i;
}
protected virtual void ProcessEvents() {
int flags = GetEventFlags();
tilted = ((flags & kTilted) != 0);
backButtonPressed = ((flags & kVRBackButtonPressed) != 0);
if ((flags & kProfileChanged) != 0) {
UpdateScreenData();
}
}
#if UNITY_IOS && !UNITY_HAS_GOOGLEVR
private const string dllName = "__Internal";
#elif UNITY_HAS_GOOGLEVR
private const string dllName = "gvr";
#else
private const string dllName = "gvrunity";
#endif // UNITY_IOS
[DllImport(dllName)]
private static extern void Start();
[DllImport(dllName)]
private static extern void SetTextureId(int id);
[DllImport(dllName)]
private static extern bool SetDefaultProfile(byte[] uri, int size);
[DllImport(dllName)]
private static extern void SetUnityVersion(byte[] version_str, int version_length);
[DllImport(dllName)]
private static extern void EnableDistortionCorrection(bool enable);
[DllImport(dllName)]
private static extern void SetNeckModelFactor(float factor);
[DllImport(dllName)]
private static extern void ResetHeadTracker();
[DllImport(dllName)]
private static extern int GetEventFlags();
[DllImport(dllName)]
private static extern void GetProfile(float[] profile);
[DllImport(dllName)]
private static extern void GetHeadPose(float[] pose);
[DllImport(dllName)]
private static extern void GetViewParameters(float[] viewParams);
[DllImport(dllName)]
private static extern void Pause();
[DllImport(dllName)]
private static extern void Resume();
[DllImport(dllName)]
private static extern void Stop();
}
}
/// @endcond
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
public class CSharpCommandLineParser : CommandLineParser
{
public static CSharpCommandLineParser Default { get; } = new CSharpCommandLineParser();
internal static CSharpCommandLineParser ScriptRunner { get; } = new CSharpCommandLineParser(isScriptRunner: true);
internal CSharpCommandLineParser(bool isScriptRunner = false)
: base(CSharp.MessageProvider.Instance, isScriptRunner)
{
}
protected override string RegularFileExtension { get { return ".cs"; } }
protected override string ScriptFileExtension { get { return ".csx"; } }
internal sealed override CommandLineArguments CommonParse(IEnumerable<string> args, string baseDirectory, string sdkDirectoryOpt, string additionalReferenceDirectories)
{
return Parse(args, baseDirectory, sdkDirectoryOpt, additionalReferenceDirectories);
}
/// <summary>
/// Parses a command line.
/// </summary>
/// <param name="args">A collection of strings representing the command line arguments.</param>
/// <param name="baseDirectory">The base directory used for qualifying file locations.</param>
/// <param name="sdkDirectory">The directory to search for mscorlib, or null if not available.</param>
/// <param name="additionalReferenceDirectories">A string representing additional reference paths.</param>
/// <returns>a commandlinearguments object representing the parsed command line.</returns>
public new CSharpCommandLineArguments Parse(IEnumerable<string> args, string baseDirectory, string sdkDirectory, string additionalReferenceDirectories = null)
{
List<Diagnostic> diagnostics = new List<Diagnostic>();
List<string> flattenedArgs = new List<string>();
List<string> scriptArgs = IsScriptRunner ? new List<string>() : null;
FlattenArgs(args, diagnostics, flattenedArgs, scriptArgs, baseDirectory);
string appConfigPath = null;
bool displayLogo = true;
bool displayHelp = false;
bool optimize = false;
bool checkOverflow = false;
bool allowUnsafe = false;
bool concurrentBuild = true;
bool deterministic = false; // TODO(5431): Enable deterministic mode by default
bool emitPdb = false;
DebugInformationFormat debugInformationFormat = DebugInformationFormat.Pdb;
bool debugPlus = false;
string pdbPath = null;
bool noStdLib = IsScriptRunner; // don't add mscorlib from sdk dir when running scripts
string outputDirectory = baseDirectory;
ImmutableArray<KeyValuePair<string, string>> pathMap = ImmutableArray<KeyValuePair<string, string>>.Empty;
string outputFileName = null;
string documentationPath = null;
string errorLogPath = null;
bool parseDocumentationComments = false; //Don't just null check documentationFileName because we want to do this even if the file name is invalid.
bool utf8output = false;
OutputKind outputKind = OutputKind.ConsoleApplication;
SubsystemVersion subsystemVersion = SubsystemVersion.None;
LanguageVersion languageVersion = CSharpParseOptions.Default.LanguageVersion;
string mainTypeName = null;
string win32ManifestFile = null;
string win32ResourceFile = null;
string win32IconFile = null;
bool noWin32Manifest = false;
Platform platform = Platform.AnyCpu;
ulong baseAddress = 0;
int fileAlignment = 0;
bool? delaySignSetting = null;
string keyFileSetting = null;
string keyContainerSetting = null;
List<ResourceDescription> managedResources = new List<ResourceDescription>();
List<CommandLineSourceFile> sourceFiles = new List<CommandLineSourceFile>();
List<CommandLineSourceFile> additionalFiles = new List<CommandLineSourceFile>();
bool sourceFilesSpecified = false;
bool resourcesOrModulesSpecified = false;
Encoding codepage = null;
var checksumAlgorithm = SourceHashAlgorithm.Sha1;
var defines = ArrayBuilder<string>.GetInstance();
List<CommandLineReference> metadataReferences = new List<CommandLineReference>();
List<CommandLineAnalyzerReference> analyzers = new List<CommandLineAnalyzerReference>();
List<string> libPaths = new List<string>();
List<string> sourcePaths = new List<string>();
List<string> keyFileSearchPaths = new List<string>();
List<string> usings = new List<string>();
var generalDiagnosticOption = ReportDiagnostic.Default;
var diagnosticOptions = new Dictionary<string, ReportDiagnostic>();
var noWarns = new Dictionary<string, ReportDiagnostic>();
var warnAsErrors = new Dictionary<string, ReportDiagnostic>();
int warningLevel = 4;
bool highEntropyVA = false;
bool printFullPaths = false;
string moduleAssemblyName = null;
string moduleName = null;
List<string> features = new List<string>();
string runtimeMetadataVersion = null;
bool errorEndLocation = false;
bool reportAnalyzer = false;
CultureInfo preferredUILang = null;
string touchedFilesPath = null;
var sqmSessionGuid = Guid.Empty;
bool optionsEnded = false;
bool interactiveMode = false;
// Process ruleset files first so that diagnostic severity settings specified on the command line via
// /nowarn and /warnaserror can override diagnostic severity settings specified in the ruleset file.
if (!IsScriptRunner)
{
foreach (string arg in flattenedArgs)
{
string name, value;
if (TryParseOption(arg, out name, out value) && (name == "ruleset"))
{
var unquoted = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
}
else
{
generalDiagnosticOption = GetDiagnosticOptionsFromRulesetFile(diagnosticOptions, diagnostics, unquoted, baseDirectory);
}
}
}
}
foreach (string arg in flattenedArgs)
{
Debug.Assert(optionsEnded || !arg.StartsWith("@", StringComparison.Ordinal));
string name, value;
if (optionsEnded || !TryParseOption(arg, out name, out value))
{
sourceFiles.AddRange(ParseFileArgument(arg, baseDirectory, diagnostics));
if (sourceFiles.Count > 0)
{
sourceFilesSpecified = true;
}
continue;
}
switch (name)
{
case "?":
case "help":
displayHelp = true;
continue;
case "r":
case "reference":
metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: false));
continue;
case "features":
if (value == null)
{
features.Clear();
}
else
{
features.Add(value);
}
continue;
case "lib":
case "libpath":
case "libpaths":
ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_LIB_OPTION, diagnostics);
continue;
#if DEBUG
case "attachdebugger":
Debugger.Launch();
continue;
#endif
}
if (IsScriptRunner)
{
switch (name)
{
case "-": // csi -- script.csx
if (value != null) break;
// Indicates that the remaining arguments should not be treated as options.
optionsEnded = true;
continue;
case "i":
case "i+":
if (value != null) break;
interactiveMode = true;
continue;
case "i-":
if (value != null) break;
interactiveMode = false;
continue;
case "loadpath":
case "loadpaths":
ParseAndResolveReferencePaths(name, value, baseDirectory, sourcePaths, MessageID.IDS_REFERENCEPATH_OPTION, diagnostics);
continue;
case "u":
case "using":
case "usings":
case "import":
case "imports":
usings.AddRange(ParseUsings(arg, value, diagnostics));
continue;
}
}
else
{
switch (name)
{
case "a":
case "analyzer":
analyzers.AddRange(ParseAnalyzers(arg, value, diagnostics));
continue;
case "d":
case "define":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg);
continue;
}
IEnumerable<Diagnostic> defineDiagnostics;
defines.AddRange(ParseConditionalCompilationSymbols(RemoveQuotesAndSlashes(value), out defineDiagnostics));
diagnostics.AddRange(defineDiagnostics);
continue;
case "codepage":
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
continue;
}
var encoding = TryParseEncodingName(value);
if (encoding == null)
{
AddDiagnostic(diagnostics, ErrorCode.FTL_BadCodepage, value);
continue;
}
codepage = encoding;
continue;
case "checksumalgorithm":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
continue;
}
var newChecksumAlgorithm = TryParseHashAlgorithmName(value);
if (newChecksumAlgorithm == SourceHashAlgorithm.None)
{
AddDiagnostic(diagnostics, ErrorCode.FTL_BadChecksumAlgorithm, value);
continue;
}
checksumAlgorithm = newChecksumAlgorithm;
continue;
case "checked":
case "checked+":
if (value != null)
{
break;
}
checkOverflow = true;
continue;
case "checked-":
if (value != null)
break;
checkOverflow = false;
continue;
case "noconfig":
// It is already handled (see CommonCommandLineCompiler.cs).
continue;
case "sqmsessionguid":
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_MissingGuidForOption, "<text>", name);
}
else
{
if (!Guid.TryParse(value, out sqmSessionGuid))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFormatForGuidForOption, value, name);
}
}
continue;
case "preferreduilang":
value = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg);
continue;
}
try
{
preferredUILang = new CultureInfo(value);
if (CorLightup.Desktop.IsUserCustomCulture(preferredUILang) ?? false)
{
// Do not use user custom cultures.
preferredUILang = null;
}
}
catch (CultureNotFoundException)
{
}
if (preferredUILang == null)
{
AddDiagnostic(diagnostics, ErrorCode.WRN_BadUILang, value);
}
continue;
case "out":
if (string.IsNullOrWhiteSpace(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
ParseOutputFile(value, diagnostics, baseDirectory, out outputFileName, out outputDirectory);
}
continue;
case "t":
case "target":
if (value == null)
{
break; // force 'unrecognized option'
}
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget);
}
else
{
outputKind = ParseTarget(value, diagnostics);
}
continue;
case "moduleassemblyname":
value = value != null ? value.Unquote() : null;
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg);
}
else if (!MetadataHelpers.IsValidAssemblyOrModuleName(value))
{
// Dev11 C# doesn't check the name (VB does)
AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidAssemblyName, "<text>", arg);
}
else
{
moduleAssemblyName = value;
}
continue;
case "modulename":
var unquotedModuleName = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(unquotedModuleName))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "modulename");
continue;
}
else
{
moduleName = unquotedModuleName;
}
continue;
case "platform":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<string>", arg);
}
else
{
platform = ParsePlatform(value, diagnostics);
}
continue;
case "recurse":
value = RemoveQuotesAndSlashes(value);
if (value == null)
{
break; // force 'unrecognized option'
}
else if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
int before = sourceFiles.Count;
sourceFiles.AddRange(ParseRecurseArgument(value, baseDirectory, diagnostics));
if (sourceFiles.Count > before)
{
sourceFilesSpecified = true;
}
}
continue;
case "doc":
parseDocumentationComments = true;
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg);
continue;
}
string unquoted = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(unquoted))
{
// CONSIDER: This diagnostic exactly matches dev11, but it would be simpler (and more consistent with /out)
// if we just let the next case handle /doc:"".
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/doc:"); // Different argument.
}
else
{
documentationPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory);
}
continue;
case "addmodule":
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/addmodule:");
}
else if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
// NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory.
// Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory.
// An error will be reported by the assembly manager anyways.
metadataReferences.AddRange(ParseSeparatedPaths(value).Select(path => new CommandLineReference(path, MetadataReferenceProperties.Module)));
resourcesOrModulesSpecified = true;
}
continue;
case "l":
case "link":
metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: true));
continue;
case "win32res":
win32ResourceFile = GetWin32Setting(arg, value, diagnostics);
continue;
case "win32icon":
win32IconFile = GetWin32Setting(arg, value, diagnostics);
continue;
case "win32manifest":
win32ManifestFile = GetWin32Setting(arg, value, diagnostics);
noWin32Manifest = false;
continue;
case "nowin32manifest":
noWin32Manifest = true;
win32ManifestFile = null;
continue;
case "res":
case "resource":
if (value == null)
{
break; // Dev11 reports unrecognized option
}
var embeddedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: true);
if (embeddedResource != null)
{
managedResources.Add(embeddedResource);
resourcesOrModulesSpecified = true;
}
continue;
case "linkres":
case "linkresource":
if (value == null)
{
break; // Dev11 reports unrecognized option
}
var linkedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: false);
if (linkedResource != null)
{
managedResources.Add(linkedResource);
resourcesOrModulesSpecified = true;
}
continue;
case "debug":
emitPdb = true;
// unused, parsed for backward compat only
if (value != null)
{
if (value.IsEmpty())
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), name);
continue;
}
switch (value.ToLower()) {
case "full":
case "pdbonly":
debugInformationFormat = DebugInformationFormat.Pdb;
break;
case "portable":
debugInformationFormat = DebugInformationFormat.PortablePdb;
break;
case "embedded":
debugInformationFormat = DebugInformationFormat.Embedded;
break;
default:
AddDiagnostic(diagnostics, ErrorCode.ERR_BadDebugType, value);
break;
}
}
continue;
case "debug+":
//guard against "debug+:xx"
if (value != null)
break;
emitPdb = true;
debugPlus = true;
continue;
case "debug-":
if (value != null)
break;
emitPdb = false;
debugPlus = false;
continue;
case "o":
case "optimize":
case "o+":
case "optimize+":
if (value != null)
break;
optimize = true;
continue;
case "o-":
case "optimize-":
if (value != null)
break;
optimize = false;
continue;
case "deterministic":
case "deterministic+":
if (value != null)
break;
deterministic = true;
continue;
case "deterministic-":
if (value != null)
break;
deterministic = false;
continue;
case "p":
case "parallel":
case "p+":
case "parallel+":
if (value != null)
break;
concurrentBuild = true;
continue;
case "p-":
case "parallel-":
if (value != null)
break;
concurrentBuild = false;
continue;
case "warnaserror":
case "warnaserror+":
if (value == null)
{
generalDiagnosticOption = ReportDiagnostic.Error;
// Reset specific warnaserror options (since last /warnaserror flag on the command line always wins),
// and bump warnings to errors.
warnAsErrors.Clear();
foreach (var key in diagnosticOptions.Keys)
{
if (diagnosticOptions[key] == ReportDiagnostic.Warn)
{
warnAsErrors[key] = ReportDiagnostic.Error;
}
}
continue;
}
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else
{
AddWarnings(warnAsErrors, ReportDiagnostic.Error, ParseWarnings(value));
}
continue;
case "warnaserror-":
if (value == null)
{
generalDiagnosticOption = ReportDiagnostic.Default;
// Clear specific warnaserror options (since last /warnaserror flag on the command line always wins).
warnAsErrors.Clear();
continue;
}
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else
{
foreach (var id in ParseWarnings(value))
{
ReportDiagnostic ruleSetValue;
if (diagnosticOptions.TryGetValue(id, out ruleSetValue))
{
warnAsErrors[id] = ruleSetValue;
}
else
{
warnAsErrors[id] = ReportDiagnostic.Default;
}
}
}
continue;
case "w":
case "warn":
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
continue;
}
int newWarningLevel;
if (string.IsNullOrEmpty(value) ||
!int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out newWarningLevel))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else if (newWarningLevel < 0 || newWarningLevel > 4)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadWarningLevel, name);
}
else
{
warningLevel = newWarningLevel;
}
continue;
case "nowarn":
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
continue;
}
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else
{
AddWarnings(noWarns, ReportDiagnostic.Suppress, ParseWarnings(value));
}
continue;
case "unsafe":
case "unsafe+":
if (value != null)
break;
allowUnsafe = true;
continue;
case "unsafe-":
if (value != null)
break;
allowUnsafe = false;
continue;
case "langversion":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/langversion:");
}
else if (!TryParseLanguageVersion(value, CSharpParseOptions.Default.LanguageVersion, out languageVersion))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadCompatMode, value);
}
continue;
case "delaysign":
case "delaysign+":
if (value != null)
{
break;
}
delaySignSetting = true;
continue;
case "delaysign-":
if (value != null)
{
break;
}
delaySignSetting = false;
continue;
case "keyfile":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, "keyfile");
}
else
{
keyFileSetting = RemoveQuotesAndSlashes(value);
}
// NOTE: Dev11/VB also clears "keycontainer", see also:
//
// MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by
// MSDN: custom attribute) in the same compilation, the compiler will first try the key container.
// MSDN: If that succeeds, then the assembly is signed with the information in the key container.
// MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile.
// MSDN: If that succeeds, the assembly is signed with the information in the key file and the key
// MSDN: information will be installed in the key container (similar to sn -i) so that on the next
// MSDN: compilation, the key container will be valid.
continue;
case "keycontainer":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "keycontainer");
}
else
{
keyContainerSetting = value;
}
// NOTE: Dev11/VB also clears "keyfile", see also:
//
// MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by
// MSDN: custom attribute) in the same compilation, the compiler will first try the key container.
// MSDN: If that succeeds, then the assembly is signed with the information in the key container.
// MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile.
// MSDN: If that succeeds, the assembly is signed with the information in the key file and the key
// MSDN: information will be installed in the key container (similar to sn -i) so that on the next
// MSDN: compilation, the key container will be valid.
continue;
case "highentropyva":
case "highentropyva+":
if (value != null)
break;
highEntropyVA = true;
continue;
case "highentropyva-":
if (value != null)
break;
highEntropyVA = false;
continue;
case "nologo":
displayLogo = false;
continue;
case "baseaddress":
value = RemoveQuotesAndSlashes(value);
ulong newBaseAddress;
if (string.IsNullOrEmpty(value) || !TryParseUInt64(value, out newBaseAddress))
{
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, value);
}
}
else
{
baseAddress = newBaseAddress;
}
continue;
case "subsystemversion":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "subsystemversion");
continue;
}
// It seems VS 2012 just silently corrects invalid values and suppresses the error message
SubsystemVersion version = SubsystemVersion.None;
if (SubsystemVersion.TryParse(value, out version))
{
subsystemVersion = version;
}
else
{
AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidSubsystemVersion, value);
}
continue;
case "touchedfiles":
unquoted = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "touchedfiles");
continue;
}
else
{
touchedFilesPath = unquoted;
}
continue;
case "bugreport":
UnimplementedSwitch(diagnostics, name);
continue;
case "utf8output":
if (value != null)
break;
utf8output = true;
continue;
case "m":
case "main":
// Remove any quotes for consistent behavior as MSBuild can return quoted or
// unquoted main.
unquoted = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
continue;
}
mainTypeName = unquoted;
continue;
case "fullpaths":
if (value != null)
break;
printFullPaths = true;
continue;
case "pathmap":
// "/pathmap:K1=V1,K2=V2..."
{
if (value == null)
break;
pathMap = pathMap.Concat(ParsePathMap(value, diagnostics));
}
continue;
case "filealign":
value = RemoveQuotesAndSlashes(value);
ushort newAlignment;
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else if (!TryParseUInt16(value, out newAlignment))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value);
}
else if (!CompilationOptions.IsValidFileAlignment(newAlignment))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value);
}
else
{
fileAlignment = newAlignment;
}
continue;
case "pdb":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
pdbPath = ParsePdbPath(value, diagnostics, baseDirectory);
}
continue;
case "errorendlocation":
errorEndLocation = true;
continue;
case "reportanalyzer":
reportAnalyzer = true;
continue;
case "nostdlib":
case "nostdlib+":
if (value != null)
break;
noStdLib = true;
continue;
case "nostdlib-":
if (value != null)
break;
noStdLib = false;
continue;
case "errorreport":
continue;
case "errorlog":
unquoted = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<file>", RemoveQuotesAndSlashes(arg));
}
else
{
errorLogPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory);
}
continue;
case "appconfig":
unquoted = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<text>", RemoveQuotesAndSlashes(arg));
}
else
{
appConfigPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory);
}
continue;
case "runtimemetadataversion":
unquoted = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
continue;
}
runtimeMetadataVersion = unquoted;
continue;
case "ruleset":
// The ruleset arg has already been processed in a separate pass above.
continue;
case "additionalfile":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<file list>", name);
continue;
}
additionalFiles.AddRange(ParseAdditionalFileArgument(value, baseDirectory, diagnostics));
continue;
}
}
AddDiagnostic(diagnostics, ErrorCode.ERR_BadSwitch, arg);
}
foreach (var o in warnAsErrors)
{
diagnosticOptions[o.Key] = o.Value;
}
// Specific nowarn options always override specific warnaserror options.
foreach (var o in noWarns)
{
diagnosticOptions[o.Key] = o.Value;
}
if (!IsScriptRunner && !sourceFilesSpecified && (outputKind.IsNetModule() || !resourcesOrModulesSpecified))
{
AddDiagnostic(diagnostics, diagnosticOptions, ErrorCode.WRN_NoSources);
}
if (!noStdLib && sdkDirectory != null)
{
metadataReferences.Insert(0, new CommandLineReference(Path.Combine(sdkDirectory, "mscorlib.dll"), MetadataReferenceProperties.Assembly));
}
if (!platform.Requires64Bit())
{
if (baseAddress > uint.MaxValue - 0x8000)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, string.Format("0x{0:X}", baseAddress));
baseAddress = 0;
}
}
// add additional reference paths if specified
if (!string.IsNullOrWhiteSpace(additionalReferenceDirectories))
{
ParseAndResolveReferencePaths(null, additionalReferenceDirectories, baseDirectory, libPaths, MessageID.IDS_LIB_ENV, diagnostics);
}
ImmutableArray<string> referencePaths = BuildSearchPaths(sdkDirectory, libPaths);
ValidateWin32Settings(win32ResourceFile, win32IconFile, win32ManifestFile, outputKind, diagnostics);
// Dev11 searches for the key file in the current directory and assembly output directory.
// We always look to base directory and then examine the search paths.
keyFileSearchPaths.Add(baseDirectory);
if (baseDirectory != outputDirectory)
{
keyFileSearchPaths.Add(outputDirectory);
}
var parsedFeatures = CompilerOptionParseUtilities.ParseFeatures(features);
string compilationName;
GetCompilationAndModuleNames(diagnostics, outputKind, sourceFiles, sourceFilesSpecified, moduleAssemblyName, ref outputFileName, ref moduleName, out compilationName);
var parseOptions = new CSharpParseOptions
(
languageVersion: languageVersion,
preprocessorSymbols: defines.ToImmutableAndFree(),
documentationMode: parseDocumentationComments ? DocumentationMode.Diagnose : DocumentationMode.None,
kind: SourceCodeKind.Regular,
features: parsedFeatures
);
var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script);
// We want to report diagnostics with source suppression in the error log file.
// However, these diagnostics won't be reported on the command line.
var reportSuppressedDiagnostics = errorLogPath != null;
var options = new CSharpCompilationOptions
(
outputKind: outputKind,
moduleName: moduleName,
mainTypeName: mainTypeName,
scriptClassName: WellKnownMemberNames.DefaultScriptClassName,
usings: usings,
optimizationLevel: optimize ? OptimizationLevel.Release : OptimizationLevel.Debug,
checkOverflow: checkOverflow,
allowUnsafe: allowUnsafe,
deterministic: deterministic,
concurrentBuild: concurrentBuild,
cryptoKeyContainer: keyContainerSetting,
cryptoKeyFile: keyFileSetting,
delaySign: delaySignSetting,
platform: platform,
generalDiagnosticOption: generalDiagnosticOption,
warningLevel: warningLevel,
specificDiagnosticOptions: diagnosticOptions,
reportSuppressedDiagnostics: reportSuppressedDiagnostics
);
if (debugPlus)
{
options = options.WithDebugPlusMode(debugPlus);
}
var emitOptions = new EmitOptions
(
metadataOnly: false,
debugInformationFormat: debugInformationFormat,
pdbFilePath: null, // to be determined later
outputNameOverride: null, // to be determined later
baseAddress: baseAddress,
highEntropyVirtualAddressSpace: highEntropyVA,
fileAlignment: fileAlignment,
subsystemVersion: subsystemVersion,
runtimeMetadataVersion: runtimeMetadataVersion
);
// add option incompatibility errors if any
diagnostics.AddRange(options.Errors);
return new CSharpCommandLineArguments
{
IsScriptRunner = IsScriptRunner,
InteractiveMode = interactiveMode || IsScriptRunner && sourceFiles.Count == 0,
BaseDirectory = baseDirectory,
PathMap = pathMap,
Errors = diagnostics.AsImmutable(),
Utf8Output = utf8output,
CompilationName = compilationName,
OutputFileName = outputFileName,
PdbPath = pdbPath,
EmitPdb = emitPdb,
OutputDirectory = outputDirectory,
DocumentationPath = documentationPath,
ErrorLogPath = errorLogPath,
AppConfigPath = appConfigPath,
SourceFiles = sourceFiles.AsImmutable(),
Encoding = codepage,
ChecksumAlgorithm = checksumAlgorithm,
MetadataReferences = metadataReferences.AsImmutable(),
AnalyzerReferences = analyzers.AsImmutable(),
AdditionalFiles = additionalFiles.AsImmutable(),
ReferencePaths = referencePaths,
SourcePaths = sourcePaths.AsImmutable(),
KeyFileSearchPaths = keyFileSearchPaths.AsImmutable(),
Win32ResourceFile = win32ResourceFile,
Win32Icon = win32IconFile,
Win32Manifest = win32ManifestFile,
NoWin32Manifest = noWin32Manifest,
DisplayLogo = displayLogo,
DisplayHelp = displayHelp,
ManifestResources = managedResources.AsImmutable(),
CompilationOptions = options,
ParseOptions = IsScriptRunner ? scriptParseOptions : parseOptions,
EmitOptions = emitOptions,
ScriptArguments = scriptArgs.AsImmutableOrEmpty(),
TouchedFilesPath = touchedFilesPath,
PrintFullPaths = printFullPaths,
ShouldIncludeErrorEndLocation = errorEndLocation,
PreferredUILang = preferredUILang,
SqmSessionGuid = sqmSessionGuid,
ReportAnalyzer = reportAnalyzer
};
}
private static void ParseAndResolveReferencePaths(string switchName, string switchValue, string baseDirectory, List<string> builder, MessageID origin, List<Diagnostic> diagnostics)
{
if (string.IsNullOrEmpty(switchValue))
{
Debug.Assert(!string.IsNullOrEmpty(switchName));
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_PathList.Localize(), switchName);
return;
}
foreach (string path in ParseSeparatedPaths(switchValue))
{
string resolvedPath = FileUtilities.ResolveRelativePath(path, baseDirectory);
if (resolvedPath == null)
{
AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryHasInvalidPath.Localize());
}
else if (!PortableShim.Directory.Exists(resolvedPath))
{
AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryDoesNotExist.Localize());
}
else
{
builder.Add(resolvedPath);
}
}
}
private static string GetWin32Setting(string arg, string value, List<Diagnostic> diagnostics)
{
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
string noQuotes = RemoveQuotesAndSlashes(value);
if (string.IsNullOrWhiteSpace(noQuotes))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
return noQuotes;
}
}
return null;
}
private void GetCompilationAndModuleNames(
List<Diagnostic> diagnostics,
OutputKind outputKind,
List<CommandLineSourceFile> sourceFiles,
bool sourceFilesSpecified,
string moduleAssemblyName,
ref string outputFileName,
ref string moduleName,
out string compilationName)
{
string simpleName;
if (outputFileName == null)
{
// In C#, if the output file name isn't specified explicitly, then executables take their
// names from the files containing their entrypoints and libraries derive their names from
// their first input files.
if (!IsScriptRunner && !sourceFilesSpecified)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_OutputNeedsName);
simpleName = null;
}
else if (outputKind.IsApplication())
{
simpleName = null;
}
else
{
simpleName = PathUtilities.RemoveExtension(PathUtilities.GetFileName(sourceFiles.FirstOrDefault().Path));
outputFileName = simpleName + outputKind.GetDefaultExtension();
if (simpleName.Length == 0 && !outputKind.IsNetModule())
{
AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName);
outputFileName = simpleName = null;
}
}
}
else
{
simpleName = PathUtilities.RemoveExtension(outputFileName);
if (simpleName.Length == 0)
{
AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName);
outputFileName = simpleName = null;
}
}
if (outputKind.IsNetModule())
{
Debug.Assert(!IsScriptRunner);
compilationName = moduleAssemblyName;
}
else
{
if (moduleAssemblyName != null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_AssemblyNameOnNonModule);
}
compilationName = simpleName;
}
if (moduleName == null)
{
moduleName = outputFileName;
}
}
private static ImmutableArray<string> BuildSearchPaths(string sdkDirectoryOpt, List<string> libPaths)
{
var builder = ArrayBuilder<string>.GetInstance();
// Match how Dev11 builds the list of search paths
// see PCWSTR LangCompiler::GetSearchPath()
// current folder first -- base directory is searched by default
// Add SDK directory if it is available
if (sdkDirectoryOpt != null)
{
builder.Add(sdkDirectoryOpt);
}
// libpath
builder.AddRange(libPaths);
return builder.ToImmutableAndFree();
}
public static IEnumerable<string> ParseConditionalCompilationSymbols(string value, out IEnumerable<Diagnostic> diagnostics)
{
Diagnostic myDiagnostic = null;
value = value.TrimEnd(null);
// Allow a trailing semicolon or comma in the options
if (!value.IsEmpty() &&
(value.Last() == ';' || value.Last() == ','))
{
value = value.Substring(0, value.Length - 1);
}
string[] values = value.Split(new char[] { ';', ',' } /*, StringSplitOptions.RemoveEmptyEntries*/);
var defines = new ArrayBuilder<string>(values.Length);
foreach (string id in values)
{
string trimmedId = id.Trim();
if (SyntaxFacts.IsValidIdentifier(trimmedId))
{
defines.Add(trimmedId);
}
else if (myDiagnostic == null)
{
myDiagnostic = Diagnostic.Create(CSharp.MessageProvider.Instance, (int)ErrorCode.WRN_DefineIdentifierRequired, trimmedId);
}
}
diagnostics = myDiagnostic == null ? SpecializedCollections.EmptyEnumerable<Diagnostic>()
: SpecializedCollections.SingletonEnumerable(myDiagnostic);
return defines.AsEnumerable();
}
private static Platform ParsePlatform(string value, IList<Diagnostic> diagnostics)
{
switch (value.ToLowerInvariant())
{
case "x86":
return Platform.X86;
case "x64":
return Platform.X64;
case "itanium":
return Platform.Itanium;
case "anycpu":
return Platform.AnyCpu;
case "anycpu32bitpreferred":
return Platform.AnyCpu32BitPreferred;
case "arm":
return Platform.Arm;
default:
AddDiagnostic(diagnostics, ErrorCode.ERR_BadPlatformType, value);
return Platform.AnyCpu;
}
}
private static OutputKind ParseTarget(string value, IList<Diagnostic> diagnostics)
{
switch (value.ToLowerInvariant())
{
case "exe":
return OutputKind.ConsoleApplication;
case "winexe":
return OutputKind.WindowsApplication;
case "library":
return OutputKind.DynamicallyLinkedLibrary;
case "module":
return OutputKind.NetModule;
case "appcontainerexe":
return OutputKind.WindowsRuntimeApplication;
case "winmdobj":
return OutputKind.WindowsRuntimeMetadata;
default:
AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget);
return OutputKind.ConsoleApplication;
}
}
private static IEnumerable<string> ParseUsings(string arg, string value, IList<Diagnostic> diagnostics)
{
if (value.Length == 0)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Namespace1.Localize(), arg);
yield break;
}
foreach (var u in value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
yield return u;
}
}
private IEnumerable<CommandLineAnalyzerReference> ParseAnalyzers(string arg, string value, List<Diagnostic> diagnostics)
{
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg);
yield break;
}
else if (value.Length == 0)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
yield break;
}
List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList();
foreach (string path in paths)
{
yield return new CommandLineAnalyzerReference(path);
}
}
private IEnumerable<CommandLineReference> ParseAssemblyReferences(string arg, string value, IList<Diagnostic> diagnostics, bool embedInteropTypes)
{
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg);
yield break;
}
else if (value.Length == 0)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
yield break;
}
// /r:"reference"
// /r:alias=reference
// /r:alias="reference"
// /r:reference;reference
// /r:"path;containing;semicolons"
// /r:"unterminated_quotes
// /r:"quotes"in"the"middle
// /r:alias=reference;reference ... error 2034
// /r:nonidf=reference ... error 1679
int eqlOrQuote = value.IndexOfAny(new[] { '"', '=' });
string alias;
if (eqlOrQuote >= 0 && value[eqlOrQuote] == '=')
{
alias = value.Substring(0, eqlOrQuote);
value = value.Substring(eqlOrQuote + 1);
if (!SyntaxFacts.IsValidIdentifier(alias))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadExternIdentifier, alias);
yield break;
}
}
else
{
alias = null;
}
List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList();
if (alias != null)
{
if (paths.Count > 1)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_OneAliasPerReference, value);
yield break;
}
if (paths.Count == 0)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_AliasMissingFile, alias);
yield break;
}
}
foreach (string path in paths)
{
// NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory.
// Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory.
var aliases = (alias != null) ? ImmutableArray.Create(alias) : ImmutableArray<string>.Empty;
var properties = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes);
yield return new CommandLineReference(path, properties);
}
}
private static void ValidateWin32Settings(string win32ResourceFile, string win32IconResourceFile, string win32ManifestFile, OutputKind outputKind, IList<Diagnostic> diagnostics)
{
if (win32ResourceFile != null)
{
if (win32IconResourceFile != null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndIcon);
}
if (win32ManifestFile != null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndManifest);
}
}
if (outputKind.IsNetModule() && win32ManifestFile != null)
{
AddDiagnostic(diagnostics, ErrorCode.WRN_CantHaveManifestForModule);
}
}
internal static ResourceDescription ParseResourceDescription(
string arg,
string resourceDescriptor,
string baseDirectory,
IList<Diagnostic> diagnostics,
bool embedded)
{
string filePath;
string fullPath;
string fileName;
string resourceName;
string accessibility;
ParseResourceDescription(
resourceDescriptor,
baseDirectory,
false,
out filePath,
out fullPath,
out fileName,
out resourceName,
out accessibility);
bool isPublic;
if (accessibility == null)
{
// If no accessibility is given, we default to "public".
// NOTE: Dev10 distinguishes between null and empty/whitespace-only.
isPublic = true;
}
else if (string.Equals(accessibility, "public", StringComparison.OrdinalIgnoreCase))
{
isPublic = true;
}
else if (string.Equals(accessibility, "private", StringComparison.OrdinalIgnoreCase))
{
isPublic = false;
}
else
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadResourceVis, accessibility);
return null;
}
if (string.IsNullOrEmpty(filePath))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
return null;
}
if (fullPath == null || string.IsNullOrWhiteSpace(fileName) || fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
{
AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, filePath);
return null;
}
Func<Stream> dataProvider = () =>
{
// Use FileShare.ReadWrite because the file could be opened by the current process.
// For example, it is an XML doc file produced by the build.
return PortableShim.FileStream.Create(fullPath, PortableShim.FileMode.Open, PortableShim.FileAccess.Read, PortableShim.FileShare.ReadWrite);
};
return new ResourceDescription(resourceName, fileName, dataProvider, isPublic, embedded, checkArgs: false);
}
private static bool TryParseLanguageVersion(string str, LanguageVersion defaultVersion, out LanguageVersion version)
{
if (str == null)
{
version = defaultVersion;
return true;
}
switch (str.ToLowerInvariant())
{
case "iso-1":
version = LanguageVersion.CSharp1;
return true;
case "iso-2":
version = LanguageVersion.CSharp2;
return true;
case "default":
version = defaultVersion;
return true;
default:
int versionNumber;
if (int.TryParse(str, NumberStyles.None, CultureInfo.InvariantCulture, out versionNumber) && ((LanguageVersion)versionNumber).IsValid())
{
version = (LanguageVersion)versionNumber;
return true;
}
version = defaultVersion;
return false;
}
}
private static IEnumerable<string> ParseWarnings(string value)
{
value = value.Unquote();
string[] values = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string id in values)
{
ushort number;
if (ushort.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, out number) &&
ErrorFacts.IsWarning((ErrorCode)number))
{
// The id refers to a compiler warning.
yield return CSharp.MessageProvider.Instance.GetIdForErrorCode(number);
}
else
{
// Previous versions of the compiler used to report a warning (CS1691)
// whenever an unrecognized warning code was supplied in /nowarn or
// /warnaserror. We no longer generate a warning in such cases.
// Instead we assume that the unrecognized id refers to a custom diagnostic.
yield return id;
}
}
}
private static void AddWarnings(Dictionary<string, ReportDiagnostic> d, ReportDiagnostic kind, IEnumerable<string> items)
{
foreach (var id in items)
{
ReportDiagnostic existing;
if (d.TryGetValue(id, out existing))
{
// Rewrite the existing value with the latest one unless it is for /nowarn.
if (existing != ReportDiagnostic.Suppress)
d[id] = kind;
}
else
{
d.Add(id, kind);
}
}
}
private static void UnimplementedSwitch(IList<Diagnostic> diagnostics, string switchName)
{
AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName);
}
private static void UnimplementedSwitchValue(IList<Diagnostic> diagnostics, string switchName, string value)
{
AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName + ":" + value);
}
internal override void GenerateErrorForNoFilesFoundInRecurse(string path, IList<Diagnostic> diagnostics)
{
// no error in csc.exe
}
private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode)
{
diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode));
}
private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode, params object[] arguments)
{
diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode, arguments));
}
/// <summary>
/// Diagnostic for the errorCode added if the warningOptions does not mention suppressed for the errorCode.
/// </summary>
private static void AddDiagnostic(IList<Diagnostic> diagnostics, Dictionary<string, ReportDiagnostic> warningOptions, ErrorCode errorCode, params object[] arguments)
{
int code = (int)errorCode;
ReportDiagnostic value;
warningOptions.TryGetValue(CSharp.MessageProvider.Instance.GetIdForErrorCode(code), out value);
if (value != ReportDiagnostic.Suppress)
{
AddDiagnostic(diagnostics, errorCode, arguments);
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
namespace Orchard.ResourceManagement
{
public class ResourceDefinition
{
private static readonly Dictionary<string, string> _resourceTypeTagNames = new Dictionary<string, string> {
{ "script", "script" },
{ "stylesheet", "link" }
};
private static readonly Dictionary<string, string> _filePathAttributes = new Dictionary<string, string> {
{ "script", "src" },
{ "link", "href" }
};
private static readonly Dictionary<string, Dictionary<string, string>> _resourceAttributes = new Dictionary<string, Dictionary<string, string>> {
{ "script", new Dictionary<string, string> { {"type", "text/javascript"} } },
{ "stylesheet", new Dictionary<string, string> { {"type", "text/css"}, {"rel", "stylesheet"} } }
};
private static readonly Dictionary<string, TagRenderMode> _fileTagRenderModes = new Dictionary<string, TagRenderMode> {
{ "script", TagRenderMode.Normal },
{ "link", TagRenderMode.SelfClosing }
};
private static readonly Dictionary<string, string> _resourceTypeDirectories = new Dictionary<string, string> {
{"script", "scripts/"},
{"stylesheet", "styles/"}
};
private string _basePath;
public ResourceDefinition(ResourceManifest manifest, string type, string name)
{
Manifest = manifest;
Type = type;
Name = name;
TagName = _resourceTypeTagNames.ContainsKey(Type) ? _resourceTypeTagNames[Type] : "meta";
FilePathAttributeName = _filePathAttributes.ContainsKey(TagName) ? _filePathAttributes[TagName] : null;
TagRenderMode = _fileTagRenderModes.ContainsKey(TagName) ? _fileTagRenderModes[TagName] : TagRenderMode.Normal;
}
internal static string GetBasePathFromViewPath(string resourceType, string viewPath)
{
if (String.IsNullOrEmpty(viewPath))
{
return null;
}
string basePath = null;
var viewsPartIndex = viewPath.IndexOf("/Views", StringComparison.OrdinalIgnoreCase);
if (viewsPartIndex >= 0)
{
basePath = viewPath.Substring(0, viewsPartIndex + 1) + GetResourcePath(resourceType);
}
return basePath;
}
internal static string GetResourcePath(string resourceType)
{
string path;
_resourceTypeDirectories.TryGetValue(resourceType, out path);
return path ?? "";
}
private static string Coalesce(params string[] strings)
{
foreach (var str in strings)
{
if (!String.IsNullOrEmpty(str))
{
return str;
}
}
return null;
}
public ResourceManifest Manifest { get; private set; }
public string TagName { get; private set; }
public TagRenderMode TagRenderMode { get; private set; }
public string Name { get; private set; }
public string Type { get; private set; }
public string Version { get; private set; }
public string BasePath
{
get
{
if (!String.IsNullOrEmpty(_basePath))
{
return _basePath;
}
var basePath = Manifest.BasePath;
if (!String.IsNullOrEmpty(basePath))
{
basePath += GetResourcePath(Type);
}
return basePath ?? "";
}
}
public string Url { get; private set; }
public string UrlDebug { get; private set; }
public string UrlCdn { get; private set; }
public string UrlCdnDebug { get; private set; }
public string CdnDebugIntegrity { get; private set; }
public string CdnIntegrity { get; private set; }
public string[] Cultures { get; private set; }
public bool CdnSupportsSsl { get; private set; }
public IEnumerable<string> Dependencies { get; private set; }
public string FilePathAttributeName { get; private set; }
public AttributeDictionary Attributes { get; private set; }
public ResourceDefinition SetAttribute(string name, string value)
{
if (Attributes == null)
{
Attributes = new AttributeDictionary();
}
Attributes[name] = value;
return this;
}
public ResourceDefinition SetBasePath(string virtualPath)
{
_basePath = virtualPath;
return this;
}
public ResourceDefinition SetUrl(string url)
{
return SetUrl(url, null);
}
public ResourceDefinition SetUrl(string url, string urlDebug)
{
if (String.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
Url = url;
if (urlDebug != null)
{
UrlDebug = urlDebug;
}
return this;
}
public ResourceDefinition SetCdn(string cdnUrl)
{
return SetCdn(cdnUrl, null, null);
}
public ResourceDefinition SetCdn(string cdnUrl, string cdnUrlDebug)
{
return SetCdn(cdnUrl, cdnUrlDebug, null);
}
public ResourceDefinition SetCdnIntegrity(string cdnIntegrity)
{
return SetCdnIntegrity(cdnIntegrity, null);
}
public ResourceDefinition SetCdnIntegrity(string cdnIntegrity, string cdnDebugIntegrity)
{
if (String.IsNullOrEmpty(cdnIntegrity))
{
throw new ArgumentNullException("cdnUrl");
}
CdnIntegrity = cdnIntegrity;
if (cdnDebugIntegrity != null)
{
CdnDebugIntegrity = cdnDebugIntegrity;
}
return this;
}
public ResourceDefinition SetCdn(string cdnUrl, string cdnUrlDebug, bool? cdnSupportsSsl)
{
if (String.IsNullOrEmpty(cdnUrl))
{
throw new ArgumentNullException("cdnUrl");
}
UrlCdn = cdnUrl;
if (cdnUrlDebug != null)
{
UrlCdnDebug = cdnUrlDebug;
}
if (cdnSupportsSsl.HasValue)
{
CdnSupportsSsl = cdnSupportsSsl.Value;
}
return this;
}
/// <summary>
/// Sets the version of the resource.
/// </summary>
/// <param name="version">The version to set, in the form of <code>major.minor[.build[.revision]]</code></param>
public ResourceDefinition SetVersion(string version)
{
Version = version;
return this;
}
public ResourceDefinition SetCultures(params string[] cultures)
{
Cultures = cultures;
return this;
}
public ResourceDefinition SetDependencies(params string[] dependencies)
{
Dependencies = dependencies;
return this;
}
public TagBuilder GetTagBuilder(RequireSettings settings, string applicationPath)
{
string url;
// Url priority:
if (settings.DebugMode)
{
url = settings.CdnMode
? Coalesce(UrlCdnDebug, UrlDebug, UrlCdn, Url)
: Coalesce(UrlDebug, Url, UrlCdnDebug, UrlCdn);
}
else
{
url = settings.CdnMode
? Coalesce(UrlCdn, Url, UrlCdnDebug, UrlDebug)
: Coalesce(Url, UrlDebug, UrlCdn, UrlCdnDebug);
}
if (String.IsNullOrEmpty(url))
{
url = null;
}
if (!String.IsNullOrEmpty(settings.Culture))
{
string nearestCulture = FindNearestCulture(settings.Culture);
if (!String.IsNullOrEmpty(nearestCulture))
{
url = Path.ChangeExtension(url, nearestCulture + Path.GetExtension(url));
}
}
if (url.StartsWith("~/", StringComparison.Ordinal))
{
// For tilde slash paths, drop the leading ~ to make it work with the underlying IFileProvider.
url = url.Substring(1);
}
var tagBuilder = new TagBuilder(TagName);
if (!String.IsNullOrEmpty(CdnIntegrity) && url != null && url == UrlCdn)
{
tagBuilder.Attributes["integrity"] = CdnIntegrity;
tagBuilder.Attributes["crossorigin"] = "anonymous";
}
else if (!String.IsNullOrEmpty(CdnDebugIntegrity) && url != null && url == UrlCdnDebug)
{
tagBuilder.Attributes["integrity"] = CdnDebugIntegrity;
tagBuilder.Attributes["crossorigin"] = "anonymous";
}
if (_resourceAttributes.ContainsKey(Type))
{
tagBuilder.MergeAttributes(_resourceAttributes[Type]);
}
if (Attributes != null)
{
tagBuilder.MergeAttributes(Attributes);
}
if (settings.HasAttributes)
{
tagBuilder.MergeAttributes(settings.Attributes);
}
if (!String.IsNullOrEmpty(FilePathAttributeName))
{
if (!String.IsNullOrEmpty(url))
{
tagBuilder.MergeAttribute(FilePathAttributeName, url, true);
}
}
return tagBuilder;
}
public string FindNearestCulture(string culture)
{
// go for an exact match
if (Cultures == null)
{
return null;
}
int selectedIndex = Array.IndexOf(Cultures, culture);
if (selectedIndex != -1)
{
return Cultures[selectedIndex];
}
// try parent culture if any
var cultureInfo = new CultureInfo(culture);
if (cultureInfo.Parent.Name != culture)
{
var selectedCulture = FindNearestCulture(cultureInfo.Parent.Name);
if (selectedCulture != null)
{
return selectedCulture;
}
}
return null;
}
public override bool Equals(object obj)
{
if (obj == null || obj.GetType() != GetType())
{
return false;
}
var that = (ResourceDefinition)obj;
return string.Equals(that.Name, Name, StringComparison.Ordinal) &&
string.Equals(that.Type, Type, StringComparison.Ordinal) &&
string.Equals(that.Version, Version, StringComparison.Ordinal);
}
public override int GetHashCode()
{
return (Name ?? "").GetHashCode() ^ (Type ?? "").GetHashCode();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
// TODO: Once we upgrade to C# 6, remove all of these and simply import the Http class.
using CURLAUTH = Interop.Http.CURLAUTH;
using CURLcode = Interop.Http.CURLcode;
using CURLINFO = Interop.Http.CURLINFO;
using CURLMcode = Interop.Http.CURLMcode;
using CURLMSG = Interop.Http.CURLMSG;
using CURLoption = Interop.Http.CURLoption;
using SafeCurlMultiHandle = Interop.Http.SafeCurlMultiHandle;
using CurlSeekResult = Interop.Http.CurlSeekResult;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
/// <summary>Provides a multi handle and the associated processing for all requests on the handle.</summary>
private sealed class MultiAgent
{
private static readonly Interop.Http.ReadWriteCallback s_receiveHeadersCallback = CurlReceiveHeadersCallback;
private static readonly Interop.Http.ReadWriteCallback s_sendCallback = CurlSendCallback;
private static readonly Interop.Http.SeekCallback s_seekCallback = CurlSeekCallback;
private static readonly Interop.Http.ReadWriteCallback s_receiveBodyCallback = CurlReceiveBodyCallback;
/// <summary>
/// A collection of not-yet-processed incoming requests for work to be done
/// by this multi agent. This can include making new requests, canceling
/// active requests, or unpausing active requests.
/// Protected by a lock on <see cref="_incomingRequests"/>.
/// </summary>
private readonly Queue<IncomingRequest> _incomingRequests = new Queue<IncomingRequest>();
/// <summary>Map of activeOperations, indexed by a GCHandle ptr.</summary>
private readonly Dictionary<IntPtr, ActiveRequest> _activeOperations = new Dictionary<IntPtr, ActiveRequest>();
/// <summary>
/// Special file descriptor used to wake-up curl_multi_wait calls. This is the read
/// end of a pipe, with the write end written to when work is queued or when cancellation
/// is requested. This is only valid while the worker is executing.
/// </summary>
private SafeFileHandle _wakeupRequestedPipeFd;
/// <summary>
/// Write end of the pipe connected to <see cref="_wakeupRequestedPipeFd"/>.
/// This is only valid while the worker is executing.
/// </summary>
private SafeFileHandle _requestWakeupPipeFd;
/// <summary>
/// Task for the currently running worker, or null if there is no current worker.
/// Protected by a lock on <see cref="_incomingRequests"/>.
/// </summary>
private Task _runningWorker;
/// <summary>Queues a request for the multi handle to process.</summary>
public void Queue(IncomingRequest request)
{
lock (_incomingRequests)
{
// Add the request, then initiate processing.
_incomingRequests.Enqueue(request);
EnsureWorkerIsRunning();
}
}
/// <summary>Gets the ID of the currently running worker, or null if there isn't one.</summary>
internal int? RunningWorkerId { get { return _runningWorker != null ? (int?)_runningWorker.Id : null; } }
/// <summary>Schedules the processing worker if one hasn't already been scheduled.</summary>
private void EnsureWorkerIsRunning()
{
Debug.Assert(Monitor.IsEntered(_incomingRequests), "Needs to be called under _incomingRequests lock");
if (_runningWorker == null)
{
VerboseTrace("MultiAgent worker queued");
// Create pipe used to forcefully wake up curl_multi_wait calls when something important changes.
// This is created here rather than in Process so that the pipe is available immediately
// for subsequent queue calls to use.
Debug.Assert(_wakeupRequestedPipeFd == null, "Read pipe should have been cleared");
Debug.Assert(_requestWakeupPipeFd == null, "Write pipe should have been cleared");
unsafe
{
int* fds = stackalloc int[2];
Interop.CheckIo(Interop.Sys.Pipe(fds));
_wakeupRequestedPipeFd = new SafeFileHandle((IntPtr)fds[Interop.Sys.ReadEndOfPipe], true);
_requestWakeupPipeFd = new SafeFileHandle((IntPtr)fds[Interop.Sys.WriteEndOfPipe], true);
}
// Kick off the processing task. It's "DenyChildAttach" to avoid any surprises if
// code happens to create attached tasks, and it's LongRunning because this thread
// is likely going to sit around for a while in a wait loop (and the more requests
// are concurrently issued to the same agent, the longer the thread will be around).
const TaskCreationOptions Options = TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning;
_runningWorker = new Task(s =>
{
VerboseTrace("MultiAgent worker starting");
var thisRef = (MultiAgent)s;
try
{
// Do the actual processing
thisRef.WorkerLoop();
}
catch (Exception exc)
{
Debug.Fail("Unexpected exception from processing loop: " + exc.ToString());
}
finally
{
VerboseTrace("MultiAgent worker shutting down");
lock (thisRef._incomingRequests)
{
// Close our wakeup pipe (ignore close errors).
// This is done while holding the lock to prevent
// subsequent Queue calls to see an improperly configured
// set of descriptors.
thisRef._wakeupRequestedPipeFd.Dispose();
thisRef._wakeupRequestedPipeFd = null;
thisRef._requestWakeupPipeFd.Dispose();
thisRef._requestWakeupPipeFd = null;
// In the time between we stopped processing and now,
// more requests could have been added. If they were
// kick off another processing loop.
thisRef._runningWorker = null;
if (thisRef._incomingRequests.Count > 0)
{
thisRef.EnsureWorkerIsRunning();
}
}
}
}, this, CancellationToken.None, Options);
_runningWorker.Start(TaskScheduler.Default); // started after _runningWorker field set to avoid race conditions
}
else // _workerRunning == true
{
// The worker is already running. If there are already queued requests, we're done.
// However, if there aren't any queued requests, Process could be blocked inside of
// curl_multi_wait, and we want to make sure it wakes up to see that there additional
// requests waiting to be handled. So we write to the wakeup pipe.
Debug.Assert(_incomingRequests.Count >= 1, "We just queued a request, so the count should be at least 1");
if (_incomingRequests.Count == 1)
{
RequestWakeup();
}
}
}
/// <summary>Write a byte to the wakeup pipe.</summary>
private void RequestWakeup()
{
unsafe
{
VerboseTrace("Writing to wakeup pipe");
byte b = 1;
Interop.CheckIo(Interop.Sys.Write(_requestWakeupPipeFd, &b, 1));
}
}
/// <summary>Clears data from the wakeup pipe.</summary>
/// <remarks>
/// This must only be called when we know there's data to be read.
/// The MultiAgent could easily deadlock if it's called when there's no data in the pipe.
/// </remarks>
private unsafe void ReadFromWakeupPipeWhenKnownToContainData()
{
// It's possible but unlikely that there will be tons of extra data in the pipe,
// more than we end up reading out here (it's unlikely because we only write a byte to the pipe when
// transitioning from 0 to 1 incoming request). In that unlikely event, the worst
// case will be that the next one or more waits will wake up immediately, with each one
// subsequently clearing out more of the pipe.
const int ClearBufferSize = 64; // sufficiently large to clear the pipe in any normal case
byte* clearBuf = stackalloc byte[ClearBufferSize];
int bytesRead = Interop.CheckIo(Interop.Sys.Read(_wakeupRequestedPipeFd, clearBuf, ClearBufferSize));
VerboseTraceIf(bytesRead > 1, "Read more than one byte from wakeup pipe: " + bytesRead);
}
/// <summary>Requests that libcurl unpause the connection associated with this request.</summary>
internal void RequestUnpause(EasyRequest easy)
{
VerboseTrace(easy: easy);
Queue(new IncomingRequest { Easy = easy, Type = IncomingRequestType.Unpause });
}
/// <summary>Creates and configures a new multi handle.</summary>
private SafeCurlMultiHandle CreateAndConfigureMultiHandle()
{
// Create the new handle
SafeCurlMultiHandle multiHandle = Interop.Http.MultiCreate();
if (multiHandle.IsInvalid)
{
throw CreateHttpRequestException();
}
// In support of HTTP/2, enable HTTP/2 connections to be multiplexed if possible.
// We must only do this if the version of libcurl being used supports HTTP/2 multiplexing.
// Due to a change in a libcurl signature, if we try to make this call on an older libcurl,
// we'll end up accidentally and unconditionally enabling HTTP 1.1 pipelining.
if (s_supportsHttp2Multiplexing)
{
ThrowIfCURLMError(Interop.Http.MultiSetOptionLong(multiHandle,
Interop.Http.CURLMoption.CURLMOPT_PIPELINING,
(long)Interop.Http.CurlPipe.CURLPIPE_MULTIPLEX));
}
return multiHandle;
}
private void WorkerLoop()
{
Debug.Assert(!Monitor.IsEntered(_incomingRequests), "No locks should be held while invoking Process");
Debug.Assert(_runningWorker != null && _runningWorker.Id == Task.CurrentId, "This is the worker, so it must be running");
Debug.Assert(_wakeupRequestedPipeFd != null && !_wakeupRequestedPipeFd.IsInvalid, "Should have a valid pipe for wake ups");
// Create the multi handle to use for this round of processing. This one handle will be used
// to service all easy requests currently available and all those that come in while
// we're processing other requests. Once the work quiesces and there are no more requests
// to process, this multi handle will be released as the worker goes away. The next
// time a request arrives and a new worker is spun up, a new multi handle will be created.
SafeCurlMultiHandle multiHandle = CreateAndConfigureMultiHandle();
// Clear our active operations table. This should already be clear, either because
// all previous operations completed without unexpected exception, or in the case of an
// unexpected exception we should have cleaned up gracefully anyway. But just in case...
Debug.Assert(_activeOperations.Count == 0, "We shouldn't have any active operations when starting processing.");
_activeOperations.Clear();
bool endingSuccessfully = false;
try
{
// Continue processing as long as there are any active operations
while (true)
{
// First handle any requests in the incoming requests queue.
while (true)
{
IncomingRequest request;
lock (_incomingRequests)
{
if (_incomingRequests.Count == 0) break;
request = _incomingRequests.Dequeue();
}
HandleIncomingRequest(multiHandle, request);
}
// If we have no active operations, we're done.
if (_activeOperations.Count == 0)
{
endingSuccessfully = true;
return;
}
// We have one or more active operations. Run any work that needs to be run.
ThrowIfCURLMError(Interop.Http.MultiPerform(multiHandle));
// Complete and remove any requests that have finished being processed.
CURLMSG message;
IntPtr easyHandle;
CURLcode result;
while (Interop.Http.MultiInfoRead(multiHandle, out message, out easyHandle, out result))
{
Debug.Assert(message == CURLMSG.CURLMSG_DONE, "CURLMSG_DONE is supposed to be the only message type");
if (message == CURLMSG.CURLMSG_DONE)
{
IntPtr gcHandlePtr;
CURLcode getInfoResult = Interop.Http.EasyGetInfoPointer(easyHandle, CURLINFO.CURLINFO_PRIVATE, out gcHandlePtr);
Debug.Assert(getInfoResult == CURLcode.CURLE_OK, "Failed to get info on a completing easy handle");
if (getInfoResult == CURLcode.CURLE_OK)
{
ActiveRequest completedOperation;
bool gotActiveOp = _activeOperations.TryGetValue(gcHandlePtr, out completedOperation);
Debug.Assert(gotActiveOp, "Expected to find GCHandle ptr in active operations table");
if (gotActiveOp)
{
DeactivateActiveRequest(multiHandle, completedOperation.Easy, gcHandlePtr, completedOperation.CancellationRegistration);
FinishRequest(completedOperation.Easy, result);
}
}
}
}
// Wait for more things to do.
bool isWakeupRequestedPipeActive;
bool isTimeout;
ThrowIfCURLMError(Interop.Http.MultiWait(multiHandle, _wakeupRequestedPipeFd, out isWakeupRequestedPipeActive, out isTimeout));
if (isWakeupRequestedPipeActive)
{
// We woke up (at least in part) because a wake-up was requested.
// Read the data out of the pipe to clear it.
Debug.Assert(!isTimeout, "should not have timed out if isExtraFileDescriptorActive");
VerboseTrace("curl_multi_wait wake-up notification");
ReadFromWakeupPipeWhenKnownToContainData();
}
VerboseTraceIf(isTimeout, "curl_multi_wait timeout");
// PERF NOTE: curl_multi_wait uses poll (assuming it's available), which is O(N) in terms of the number of fds
// being waited on. If this ends up being a scalability bottleneck, we can look into using the curl_multi_socket_*
// APIs, which would let us switch to using epoll by being notified when sockets file descriptors are added or
// removed and configuring the epoll context with EPOLL_CTL_ADD/DEL, which at the expense of a lot of additional
// complexity would let us turn the O(N) operation into an O(1) operation. The additional complexity would come
// not only in the form of additional callbacks and managing the socket collection, but also in the form of timer
// management, which is necessary when using the curl_multi_socket_* APIs and which we avoid by using just
// curl_multi_wait/perform.
}
}
finally
{
// If we got an unexpected exception, something very bad happened. We may have some
// operations that we initiated but that weren't completed. Make sure to clean up any
// such operations, failing them and releasing their resources.
if (_activeOperations.Count > 0)
{
Debug.Assert(!endingSuccessfully, "We should only have remaining operations if we got an unexpected exception");
foreach (KeyValuePair<IntPtr, ActiveRequest> pair in _activeOperations)
{
ActiveRequest failingOperation = pair.Value;
IntPtr failingOperationGcHandle = pair.Key;
DeactivateActiveRequest(multiHandle, failingOperation.Easy, failingOperationGcHandle, failingOperation.CancellationRegistration);
// Complete the operation's task and clean up any of its resources
failingOperation.Easy.FailRequest(CreateHttpRequestException());
failingOperation.Easy.Cleanup(); // no active processing remains, so cleanup
}
// Clear the table.
_activeOperations.Clear();
}
// Finally, dispose of the multi handle.
multiHandle.Dispose();
}
}
private void HandleIncomingRequest(SafeCurlMultiHandle multiHandle, IncomingRequest request)
{
Debug.Assert(!Monitor.IsEntered(_incomingRequests), "Incoming requests lock should only be held while accessing the queue");
VerboseTrace("Type: " + request.Type, easy: request.Easy);
EasyRequest easy = request.Easy;
switch (request.Type)
{
case IncomingRequestType.New:
ActivateNewRequest(multiHandle, easy);
break;
case IncomingRequestType.Cancel:
Debug.Assert(easy._associatedMultiAgent == this, "Should only cancel associated easy requests");
Debug.Assert(easy._cancellationToken.IsCancellationRequested, "Cancellation should have been requested");
FindAndFailActiveRequest(multiHandle, easy, new OperationCanceledException(easy._cancellationToken));
break;
case IncomingRequestType.Unpause:
Debug.Assert(easy._associatedMultiAgent == this, "Should only unpause associated easy requests");
if (!easy._easyHandle.IsClosed)
{
IntPtr gcHandlePtr;
ActiveRequest ar;
Debug.Assert(FindActiveRequest(easy, out gcHandlePtr, out ar), "Couldn't find active request for unpause");
CURLcode unpauseResult = Interop.Http.EasyUnpause(easy._easyHandle);
try
{
ThrowIfCURLEError(unpauseResult);
}
catch (Exception exc)
{
FindAndFailActiveRequest(multiHandle, easy, exc);
}
}
break;
default:
Debug.Fail("Invalid request type: " + request.Type);
break;
}
}
private void ActivateNewRequest(SafeCurlMultiHandle multiHandle, EasyRequest easy)
{
Debug.Assert(easy != null, "We should never get a null request");
Debug.Assert(easy._associatedMultiAgent == null, "New requests should not be associated with an agent yet");
// If cancellation has been requested, complete the request proactively
if (easy._cancellationToken.IsCancellationRequested)
{
easy.FailRequest(new OperationCanceledException(easy._cancellationToken));
easy.Cleanup(); // no active processing remains, so cleanup
return;
}
// Otherwise, configure it. Most of the configuration was already done when the EasyRequest
// was created, but there's additional configuration we need to do specific to this
// multi agent, specifically telling the easy request about its own GCHandle and setting
// up callbacks for data processing. Once it's configured, add it to the multi handle.
GCHandle gcHandle = GCHandle.Alloc(easy);
IntPtr gcHandlePtr = GCHandle.ToIntPtr(gcHandle);
try
{
easy._associatedMultiAgent = this;
easy.SetCurlOption(CURLoption.CURLOPT_PRIVATE, gcHandlePtr);
easy.SetCurlCallbacks(gcHandlePtr, s_receiveHeadersCallback, s_sendCallback, s_seekCallback, s_receiveBodyCallback);
ThrowIfCURLMError(Interop.Http.MultiAddHandle(multiHandle, easy._easyHandle));
}
catch (Exception exc)
{
gcHandle.Free();
easy.FailRequest(exc);
easy.Cleanup(); // no active processing remains, so cleanup
return;
}
// And if cancellation can be requested, hook up a cancellation callback.
// This callback will put the easy request back into the queue, which will
// ensure that a wake-up request has been issued. When we pull
// the easy request out of the request queue, we'll see that it's already
// associated with this agent, meaning that it's a cancellation request,
// and we'll deal with it appropriately.
var cancellationReg = default(CancellationTokenRegistration);
if (easy._cancellationToken.CanBeCanceled)
{
cancellationReg = easy._cancellationToken.Register(s =>
{
var state = (Tuple<MultiAgent, EasyRequest>)s;
state.Item1.Queue(new IncomingRequest { Easy = state.Item2, Type = IncomingRequestType.Cancel });
}, Tuple.Create<MultiAgent, EasyRequest>(this, easy));
}
// Finally, add it to our map.
_activeOperations.Add(
gcHandlePtr,
new ActiveRequest { Easy = easy, CancellationRegistration = cancellationReg });
}
private void DeactivateActiveRequest(
SafeCurlMultiHandle multiHandle, EasyRequest easy,
IntPtr gcHandlePtr, CancellationTokenRegistration cancellationRegistration)
{
// Remove the operation from the multi handle so we can shut down the multi handle cleanly
CURLMcode removeResult = Interop.Http.MultiRemoveHandle(multiHandle, easy._easyHandle);
Debug.Assert(removeResult == CURLMcode.CURLM_OK, "Failed to remove easy handle"); // ignore cleanup errors in release
// Release the associated GCHandle so that it's not kept alive forever
if (gcHandlePtr != IntPtr.Zero)
{
try
{
GCHandle.FromIntPtr(gcHandlePtr).Free();
_activeOperations.Remove(gcHandlePtr);
}
catch (InvalidOperationException)
{
Debug.Fail("Couldn't get/free the GCHandle for an active operation while shutting down due to failure");
}
}
// Undo cancellation registration
cancellationRegistration.Dispose();
}
private bool FindActiveRequest(EasyRequest easy, out IntPtr gcHandlePtr, out ActiveRequest activeRequest)
{
// We maintain an IntPtr=>ActiveRequest mapping, which makes it cheap to look-up by GCHandle ptr but
// expensive to look up by EasyRequest. If we find this becoming a bottleneck, we can add a reverse
// map that stores the other direction as well.
foreach (KeyValuePair<IntPtr, ActiveRequest> pair in _activeOperations)
{
if (pair.Value.Easy == easy)
{
gcHandlePtr = pair.Key;
activeRequest = pair.Value;
return true;
}
}
gcHandlePtr = IntPtr.Zero;
activeRequest = default(ActiveRequest);
return false;
}
private void FindAndFailActiveRequest(SafeCurlMultiHandle multiHandle, EasyRequest easy, Exception error)
{
VerboseTrace("Error: " + error.Message, easy: easy);
IntPtr gcHandlePtr;
ActiveRequest activeRequest;
if (FindActiveRequest(easy, out gcHandlePtr, out activeRequest))
{
DeactivateActiveRequest(multiHandle, easy, gcHandlePtr, activeRequest.CancellationRegistration);
easy.FailRequest(error);
easy.Cleanup(); // no active processing remains, so we can cleanup
}
else
{
Debug.Assert(easy.Task.IsCompleted, "We should only not be able to find the request if it failed or we started to send back the response.");
}
}
private void FinishRequest(EasyRequest completedOperation, CURLcode messageResult)
{
VerboseTrace("messageResult: " + messageResult, easy: completedOperation);
if (completedOperation._responseMessage.StatusCode != HttpStatusCode.Unauthorized)
{
if (completedOperation._handler.PreAuthenticate)
{
long authAvailable;
if (Interop.Http.EasyGetInfoLong(completedOperation._easyHandle, CURLINFO.CURLINFO_HTTPAUTH_AVAIL, out authAvailable) == CURLcode.CURLE_OK)
{
completedOperation._handler.AddCredentialToCache(
completedOperation._requestMessage.RequestUri, (CURLAUTH)authAvailable, completedOperation._networkCredential);
}
// Ignore errors: no need to fail for the sake of putting the credentials into the cache
}
}
// Complete or fail the request
try
{
bool unsupportedProtocolRedirect = messageResult == CURLcode.CURLE_UNSUPPORTED_PROTOCOL && completedOperation._isRedirect;
if (!unsupportedProtocolRedirect)
{
ThrowIfCURLEError(messageResult);
}
completedOperation.EnsureResponseMessagePublished();
}
catch (Exception exc)
{
completedOperation.FailRequest(exc);
}
// At this point, we've completed processing the entire request, either due to error
// or due to completing the entire response.
completedOperation.Cleanup();
}
private static ulong CurlReceiveHeadersCallback(IntPtr buffer, ulong size, ulong nitems, IntPtr context)
{
CurlHandler.VerboseTrace("size: " + size + ", nitems: " + nitems);
size *= nitems;
if (size == 0)
{
return 0;
}
EasyRequest easy;
if (TryGetEasyRequestFromContext(context, out easy))
{
try
{
// The callback is invoked once per header; multi-line headers get merged into a single line.
string responseHeader = Marshal.PtrToStringAnsi(buffer).Trim();
HttpResponseMessage response = easy._responseMessage;
if (!TryParseStatusLine(response, responseHeader, easy))
{
int index = 0;
string headerName = CurlResponseParseUtils.ReadHeaderName(responseHeader, out index);
if (headerName != null)
{
string headerValue = responseHeader.Substring(index).Trim();
if (!response.Headers.TryAddWithoutValidation(headerName, headerValue))
{
response.Content.Headers.TryAddWithoutValidation(headerName, headerValue);
}
else if (easy._isRedirect && string.Equals(headerName, HttpKnownHeaderNames.Location, StringComparison.OrdinalIgnoreCase))
{
HandleRedirectLocationHeader(easy, headerValue);
}
else if (string.Equals(headerName, HttpKnownHeaderNames.SetCookie, StringComparison.OrdinalIgnoreCase))
{
easy._handler.AddResponseCookies(easy, headerValue);
}
}
}
return size;
}
catch (Exception ex)
{
easy.FailRequest(ex); // cleanup will be handled by main processing loop
}
}
// Returing a value other than size fails the callback and forces
// request completion with an error
return size - 1;
}
private static ulong CurlReceiveBodyCallback(
IntPtr buffer, ulong size, ulong nitems, IntPtr context)
{
CurlHandler.VerboseTrace("size: " + size + ", nitems: " + nitems);
size *= nitems;
EasyRequest easy;
if (TryGetEasyRequestFromContext(context, out easy))
{
try
{
if (!(easy.Task.IsCanceled || easy.Task.IsFaulted))
{
// Complete the task if it hasn't already been. This will make the
// stream available to consumers. A previous write callback
// may have already completed the task to publish the response.
easy.EnsureResponseMessagePublished();
// Try to transfer the data to a reader. This will return either the
// amount of data transferred (equal to the amount requested
// to be transferred), or it will return a pause request.
return easy._responseMessage.ResponseStream.TransferDataToStream(buffer, (long)size);
}
}
catch (Exception ex)
{
easy.FailRequest(ex); // cleanup will be handled by main processing loop
}
}
// Returing a value other than size fails the callback and forces
// request completion with an error.
CurlHandler.VerboseTrace("Error: returning a bad size to abort the request");
return (size > 0) ? size - 1 : 1;
}
private static ulong CurlSendCallback(IntPtr buffer, ulong size, ulong nitems, IntPtr context)
{
CurlHandler.VerboseTrace("size: " + size + ", nitems: " + nitems);
int length = checked((int)(size * nitems));
Debug.Assert(length <= RequestBufferSize, "length " + length + " should not be larger than RequestBufferSize " + RequestBufferSize);
if (length == 0)
{
return 0;
}
EasyRequest easy;
if (TryGetEasyRequestFromContext(context, out easy))
{
Debug.Assert(easy._requestContentStream != null, "We should only be in the send callback if we have a request content stream");
Debug.Assert(easy._associatedMultiAgent != null, "The request should be associated with a multi agent.");
try
{
// Transfer data from the request's content stream to libcurl
return TransferDataFromRequestStream(buffer, length, easy);
}
catch (Exception ex)
{
easy.FailRequest(ex); // cleanup will be handled by main processing loop
}
}
// Something went wrong.
return Interop.Http.CURL_READFUNC_ABORT;
}
/// <summary>
/// Transfers up to <paramref name="length"/> data from the <paramref name="easy"/>'s
/// request content (non-memory) stream to the buffer.
/// </summary>
/// <returns>The number of bytes transferred.</returns>
private static ulong TransferDataFromRequestStream(IntPtr buffer, int length, EasyRequest easy)
{
MultiAgent multi = easy._associatedMultiAgent;
// First check to see whether there's any data available from a previous asynchronous read request.
// If there is, the transfer state's Task field will be non-null, with its Result representing
// the number of bytes read. The Buffer will then contain all of that read data. If the Count
// is 0, then this is the first time we're checking that Task, and so we populate the Count
// from that read result. After that, we can transfer as much data remains between Offset and
// Count. Multiple callbacks may pull from that one read.
EasyRequest.SendTransferState sts = easy._sendTransferState;
if (sts != null)
{
// Is there a previous read that may still have data to be consumed?
if (sts._task != null)
{
if (!sts._task.IsCompleted)
{
// We have a previous read that's not yet completed. This should be quite rare, but it can
// happen when we're unpaused prematurely, potentially due to the request still finishing
// being sent as the server starts to send a response. Since we still have the outstanding
// read, we simply re-pause. When the task completes (which could have happened immediately
// after the check). the continuation we previously created will fire and queue an unpause.
// Since all of this processing is single-threaded on the current thread, that unpause request
// is guaranteed to happen after this re-pause.
multi.VerboseTrace("Re-pausing reading after a spurious un-pause", easy: easy);
return Interop.Http.CURL_READFUNC_PAUSE;
}
// Determine how many bytes were read on the last asynchronous read.
// If nothing was read, then we're done and can simply return 0 to indicate
// the end of the stream.
int bytesRead = sts._task.GetAwaiter().GetResult(); // will throw if read failed
Debug.Assert(bytesRead >= 0 && bytesRead <= sts._buffer.Length, "ReadAsync returned an invalid result length: " + bytesRead);
if (bytesRead == 0)
{
multi.VerboseTrace("End of stream from stored task", easy: easy);
sts.SetTaskOffsetCount(null, 0, 0);
return 0;
}
// If Count is still 0, then this is the first time after the task completed
// that we're examining the data: transfer the bytesRead to the Count.
if (sts._count == 0)
{
multi.VerboseTrace("ReadAsync completed with bytes: " + bytesRead, easy: easy);
sts._count = bytesRead;
}
// Now Offset and Count are both accurate. Determine how much data we can copy to libcurl...
int availableData = sts._count - sts._offset;
Debug.Assert(availableData > 0, "There must be some data still available.");
// ... and copy as much of that as libcurl will allow.
int bytesToCopy = Math.Min(availableData, length);
Marshal.Copy(sts._buffer, sts._offset, buffer, bytesToCopy);
multi.VerboseTrace("Copied " + bytesToCopy + " bytes from request stream", easy: easy);
// Update the offset. If we've gone through all of the data, reset the state
// so that the next time we're called back we'll do a new read.
sts._offset += bytesToCopy;
Debug.Assert(sts._offset <= sts._count, "Offset should never exceed count");
if (sts._offset == sts._count)
{
sts.SetTaskOffsetCount(null, 0, 0);
}
// Return the amount of data copied
Debug.Assert(bytesToCopy > 0, "We should never return 0 bytes here.");
return (ulong)bytesToCopy;
}
// sts was non-null but sts.Task was null, meaning there was no previous task/data
// from which to satisfy any of this request.
}
else // sts == null
{
// Allocate a transfer state object to use for the remainder of this request.
easy._sendTransferState = sts = new EasyRequest.SendTransferState();
}
Debug.Assert(sts != null, "By this point we should have a transfer object");
Debug.Assert(sts._task == null, "There shouldn't be a task now.");
Debug.Assert(sts._count == 0, "Count should be zero.");
Debug.Assert(sts._offset == 0, "Offset should be zero.");
// If we get here, there was no previously read data available to copy.
// Initiate a new asynchronous read.
Task<int> asyncRead = easy._requestContentStream.ReadAsyncInternal(
sts._buffer, 0, Math.Min(sts._buffer.Length, length), easy._cancellationToken);
Debug.Assert(asyncRead != null, "Badly implemented stream returned a null task from ReadAsync");
// Even though it's "Async", it's possible this read could complete synchronously or extremely quickly.
// Check to see if it did, in which case we can also satisfy the libcurl request synchronously in this callback.
if (asyncRead.IsCompleted)
{
multi.VerboseTrace("ReadAsync completed immediately", easy: easy);
// Get the amount of data read.
int bytesRead = asyncRead.GetAwaiter().GetResult(); // will throw if read failed
if (bytesRead == 0)
{
multi.VerboseTrace("End of stream from quick returning ReadAsync", easy: easy);
return 0;
}
// Copy as much as we can.
int bytesToCopy = Math.Min(bytesRead, length);
Debug.Assert(bytesToCopy > 0 && bytesToCopy <= sts._buffer.Length, "ReadAsync quickly returned an invalid result length: " + bytesToCopy);
Marshal.Copy(sts._buffer, 0, buffer, bytesToCopy);
multi.VerboseTrace("Copied " + bytesToCopy + " from quick returning ReadAsync", easy: easy);
// If we read more than we were able to copy, stash it away for the next read.
if (bytesToCopy < bytesRead)
{
multi.VerboseTrace("Stashing away " + (bytesRead - bytesToCopy) + " bytes for next read.", easy: easy);
sts.SetTaskOffsetCount(asyncRead, bytesToCopy, bytesRead);
}
// Return the number of bytes read.
return (ulong)bytesToCopy;
}
// Otherwise, the read completed asynchronously. Store the task, and hook up a continuation
// such that the connection will be unpaused once the task completes.
sts.SetTaskOffsetCount(asyncRead, 0, 0);
asyncRead.ContinueWith((t, s) =>
{
EasyRequest easyRef = (EasyRequest)s;
easyRef._associatedMultiAgent.RequestUnpause(easyRef);
}, easy, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
// Then pause the connection.
multi.VerboseTrace("Pausing the connection", easy: easy);
return Interop.Http.CURL_READFUNC_PAUSE;
}
private static CurlSeekResult CurlSeekCallback(IntPtr context, long offset, int origin)
{
CurlHandler.VerboseTrace("offset: " + offset + ", origin: " + origin);
EasyRequest easy;
if (TryGetEasyRequestFromContext(context, out easy))
{
try
{
// If libcul is requesting we seek back to the beginning and if the request
// content stream is in a position to reset itself, reset and let libcurl
// know we did the seek; otherwise, let it know we can't seek.
if (offset == 0 && origin == (int)SeekOrigin.Begin &&
easy._requestContentStream != null && easy._requestContentStream.TryReset())
{
// Dump any state associated with the old stream's position
if (easy._sendTransferState != null)
{
easy._sendTransferState.SetTaskOffsetCount(null, 0, 0);
}
// Restart the transfer
easy._requestContentStream.Run();
return CurlSeekResult.CURL_SEEKFUNC_OK;
}
else
{
return CurlSeekResult.CURL_SEEKFUNC_CANTSEEK;
}
}
catch (Exception ex)
{
easy.FailRequest(ex); // cleanup will be handled by main processing loop
}
}
// Something went wrong
return CurlSeekResult.CURL_SEEKFUNC_FAIL;
}
private static bool TryGetEasyRequestFromContext(IntPtr context, out EasyRequest easy)
{
// Get the EasyRequest from the context
try
{
GCHandle handle = GCHandle.FromIntPtr(context);
easy = (EasyRequest)handle.Target;
Debug.Assert(easy != null, "Expected non-null EasyRequest in GCHandle");
return easy != null;
}
catch (InvalidCastException)
{
Debug.Fail("EasyRequest wasn't the GCHandle's Target");
}
catch (InvalidOperationException)
{
Debug.Fail("Invalid GCHandle");
}
easy = null;
return false;
}
[Conditional(VerboseDebuggingConditional)]
private void VerboseTrace(string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null)
{
CurlHandler.VerboseTrace(text, memberName, easy, agent: this);
}
[Conditional(VerboseDebuggingConditional)]
private void VerboseTraceIf(bool condition, string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null)
{
if (condition)
{
CurlHandler.VerboseTrace(text, memberName, easy, agent: this);
}
}
/// <summary>Represents an active request currently being processed by the agent.</summary>
private struct ActiveRequest
{
public EasyRequest Easy;
public CancellationTokenRegistration CancellationRegistration;
}
/// <summary>Represents an incoming request to be processed by the agent.</summary>
internal struct IncomingRequest
{
public IncomingRequestType Type;
public EasyRequest Easy;
}
/// <summary>The type of an incoming request to be processed by the agent.</summary>
internal enum IncomingRequestType : byte
{
/// <summary>A new request that's never been submitted to an agent.</summary>
New,
/// <summary>A request to cancel a request previously submitted to the agent.</summary>
Cancel,
/// <summary>A request to unpause the connection associated with a request previously submitted to the agent.</summary>
Unpause
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Diagnostics;
using System.Globalization;
namespace System.DirectoryServices.AccountManagement
{
internal enum PrincipalAccessMask
{
ChangePassword
}
internal abstract class StoreCtx : IDisposable
{
//
// StoreCtx information
//
// Retrieves the Path (ADsPath) of the object used as the base of the StoreCtx
internal abstract string BasePath { get; }
// The PrincipalContext object to which this StoreCtx belongs. Initialized by PrincipalContext after it creates
// this StoreCtx instance.
private PrincipalContext _owningContext = null;
internal PrincipalContext OwningContext
{
[System.Security.SecurityCritical]
get
{
return _owningContext;
}
[System.Security.SecurityCritical]
set
{
Debug.Assert(value != null);
_owningContext = value;
}
}
//
// CRUD
//
// Used to perform the specified operation on the Principal. They also make any needed security subsystem
// calls to obtain digitial signatures (e..g, to sign the Principal Extension/GroupMember Relationship for
// WinFS).
//
// Insert() and Update() must check to make sure no properties not supported by this StoreCtx
// have been set, prior to persisting the Principal.
internal abstract void Insert(Principal p);
internal abstract void Update(Principal p);
internal abstract void Delete(Principal p);
internal abstract void Move(StoreCtx originalStore, Principal p);
//
// Native <--> Principal
//
// For modified object, pushes any changes (including IdentityClaim changes)
// into the underlying store-specific object (e.g., DirectoryEntry) and returns the underlying object.
// For unpersisted object, creates a underlying object if one doesn't already exist (in
// Principal.UnderlyingObject), then pushes any changes into the underlying object.
internal abstract object PushChangesToNative(Principal p);
// Given a underlying store object (e.g., DirectoryEntry), further narrowed down a discriminant
// (if applicable for the StoreCtx type), returns a fresh instance of a Principal
// object based on it. The WinFX Principal API follows ADSI-style semantics, where you get multiple
// in-memory objects all referring to the same store pricipal, rather than WinFS semantics, where
// multiple searches all return references to the same in-memory object.
// Used to implement the reverse wormhole. Also, used internally by FindResultEnumerator
// to construct Principals from the store objects returned by a store query.
//
// The Principal object produced by this method does not have all the properties
// loaded. The Principal object will call the Load method on demand to load its properties
// from its Principal.UnderlyingObject.
//
//
// This method works for native objects from the store corresponding to _this_ StoreCtx.
// Each StoreCtx will also have its own internal algorithms used for dealing with cross-store objects, e.g.,
// for use when iterating over group membership. These routines are exposed as
// ResolveCrossStoreRefToPrincipal, and will be called by the StoreCtx's associated ResultSet
// classes when iterating over a representation of a "foreign" principal.
internal abstract Principal GetAsPrincipal(object storeObject, object discriminant);
// Loads the store values from p.UnderlyingObject into p, performing schema mapping as needed.
internal abstract void Load(Principal p);
// Loads only the psecified property into the principal object. The object should have already been persisted or searched for this to happen.
internal abstract void Load(Principal p, string principalPropertyName);
// Performs store-specific resolution of an IdentityReference to a Principal
// corresponding to the IdentityReference. Returns null if no matching object found.
// principalType can be used to scope the search to principals of a specified type, e.g., users or groups.
// Specify typeof(Principal) to search all principal types.
internal abstract Principal FindPrincipalByIdentRef(
Type principalType, string urnScheme, string urnValue, DateTime referenceDate);
// Returns a type indicating the type of object that would be returned as the wormhole for the specified
// Principal. For some StoreCtxs, this method may always return a constant (e.g., typeof(DirectoryEntry)
// for ADStoreCtx). For others, it may vary depending on the Principal passed in.
internal abstract Type NativeType(Principal p);
//
// Special operations: the Principal classes delegate their implementation of many of the
// special methods to their underlying StoreCtx
//
// methods for manipulating accounts
internal abstract void InitializeUserAccountControl(AuthenticablePrincipal p);
internal abstract bool IsLockedOut(AuthenticablePrincipal p);
internal abstract void UnlockAccount(AuthenticablePrincipal p);
// methods for manipulating passwords
internal abstract void SetPassword(AuthenticablePrincipal p, string newPassword);
internal abstract void ChangePassword(AuthenticablePrincipal p, string oldPassword, string newPassword);
internal abstract void ExpirePassword(AuthenticablePrincipal p);
internal abstract void UnexpirePassword(AuthenticablePrincipal p);
internal abstract bool AccessCheck(Principal p, PrincipalAccessMask targetPermission);
// the various FindBy* methods
internal abstract ResultSet FindByLockoutTime(
DateTime dt, MatchType matchType, Type principalType);
internal abstract ResultSet FindByLogonTime(
DateTime dt, MatchType matchType, Type principalType);
internal abstract ResultSet FindByPasswordSetTime(
DateTime dt, MatchType matchType, Type principalType);
internal abstract ResultSet FindByBadPasswordAttempt(
DateTime dt, MatchType matchType, Type principalType);
internal abstract ResultSet FindByExpirationTime(
DateTime dt, MatchType matchType, Type principalType);
// Get groups of which p is a direct member
internal abstract ResultSet GetGroupsMemberOf(Principal p);
// Get groups from this ctx which contain a principal corresponding to foreignPrincipal
// (which is a principal from foreignContext)
internal abstract ResultSet GetGroupsMemberOf(Principal foreignPrincipal, StoreCtx foreignContext);
// Get groups of which p is a member, using AuthZ S4U APIs for recursive membership
internal abstract ResultSet GetGroupsMemberOfAZ(Principal p);
// Get members of group g
internal abstract BookmarkableResultSet GetGroupMembership(GroupPrincipal g, bool recursive);
// Is p a member of g in the store?
internal abstract bool SupportsNativeMembershipTest { get; }
internal abstract bool IsMemberOfInStore(GroupPrincipal g, Principal p);
// Can a Clear() operation be performed on the specified group? If not, also returns
// a string containing a human-readable explanation of why not, suitable for use in an exception.
internal abstract bool CanGroupBeCleared(GroupPrincipal g, out string explanationForFailure);
// Can the given member be removed from the specified group? If not, also returns
// a string containing a human-readable explanation of why not, suitable for use in an exception.
internal abstract bool CanGroupMemberBeRemoved(GroupPrincipal g, Principal member, out string explanationForFailure);
//
// Query operations
//
// Returns true if this store has native support for search (and thus a wormhole).
// Returns true for everything but SAM (both reg-SAM and MSAM).
internal abstract bool SupportsSearchNatively { get; }
// Returns a type indicating the type of object that would be returned as the wormhole for the specified
// PrincipalSearcher.
internal abstract Type SearcherNativeType();
// Pushes the query represented by the QBE filter into the PrincipalSearcher's underlying native
// searcher object (creating a fresh native searcher and assigning it to the PrincipalSearcher if one
// doesn't already exist) and returns the native searcher.
// If the PrincipalSearcher does not have a query filter set (PrincipalSearcher.QueryFilter == null),
// produces a query that will match all principals in the store.
//
// For stores which don't have a native searcher (SAM), the StoreCtx
// is free to create any type of object it chooses to use as its internal representation of the query.
//
// Also adds in any clauses to the searcher to ensure that only principals, not mere
// contacts, are retrieved from the store.
internal abstract object PushFilterToNativeSearcher(PrincipalSearcher ps);
// The core query operation.
// Given a PrincipalSearcher containg a query filter, transforms it into the store schema
// and performs the query to get a collection of matching native objects (up to a maximum of sizeLimit,
// or uses the sizelimit already set on the DirectorySearcher if sizeLimit == -1).
// If the PrincipalSearcher does not have a query filter (PrincipalSearcher.QueryFilter == null),
// matches all principals in the store.
//
// The collection may not be complete, i.e., paging - the returned ResultSet will automatically
// page in additional results as needed.
internal abstract ResultSet Query(PrincipalSearcher ps, int sizeLimit);
//
// Cross-store support
//
// Given a native store object that represents a "foreign" principal (e.g., a FPO object in this store that
// represents a pointer to another store), maps that representation to the other store's StoreCtx and returns
// a Principal from that other StoreCtx. The implementation of this method is highly dependent on the
// details of the particular store, and must have knowledge not only of this StoreCtx, but also of how to
// interact with other StoreCtxs to fulfill the request.
//
// This method is typically used by ResultSet implementations, when they're iterating over a collection
// (e.g., of group membership) and encounter a entry that represents a foreign principal.
internal abstract Principal ResolveCrossStoreRefToPrincipal(object o);
//
// Data Validation
//
// Validiate the passed property name to determine if it is valid for the store and Principal type.
// used by the principal objects to determine if a property is valid in the property before
// save is called.
internal abstract bool IsValidProperty(Principal p, string propertyName);
// Returns true if AccountInfo is supported for the specified principal, false otherwise.
// Used when a application tries to access the AccountInfo property of a newly-inserted
// (not yet persisted) AuthenticablePrincipal, to determine whether it should be allowed.
internal abstract bool SupportsAccounts(AuthenticablePrincipal p);
// Returns the set of credential types supported by this store for the specified principal.
// Used when a application tries to access the PasswordInfo property of a newly-inserted
// (not yet persisted) AuthenticablePrincipal, to determine whether it should be allowed.
// Also used to implement AuthenticablePrincipal.SupportedCredentialTypes.
internal abstract CredentialTypes SupportedCredTypes(AuthenticablePrincipal p);
//
// Construct a fake Principal to represent a well-known SID like
// "\Everyone" or "NT AUTHORITY\NETWORK SERVICE"
//
internal abstract Principal ConstructFakePrincipalFromSID(byte[] sid);
//
// IDisposable implementation
//
// Disposes of this instance of a StoreCtx. Calling this method more than once is allowed, and all but
// the first call should be ignored.
public virtual void Dispose()
{
// Nothing to do in the base class
}
//
// QBE Filter parsing
//
// These property sets include only the properties used to build QBE filters,
// e.g., the Group.Members property is not included
internal static string[] principalProperties = new string[]
{
PropertyNames.PrincipalDisplayName,
PropertyNames.PrincipalDescription,
PropertyNames.PrincipalSamAccountName,
PropertyNames.PrincipalUserPrincipalName,
PropertyNames.PrincipalGuid,
PropertyNames.PrincipalSid,
PropertyNames.PrincipalStructuralObjectClass,
PropertyNames.PrincipalName,
PropertyNames.PrincipalDistinguishedName,
PropertyNames.PrincipalExtensionCache
};
internal static string[] authenticablePrincipalProperties = new string[]
{
PropertyNames.AuthenticablePrincipalEnabled,
PropertyNames.AuthenticablePrincipalCertificates,
PropertyNames.PwdInfoLastBadPasswordAttempt,
PropertyNames.AcctInfoExpirationDate,
PropertyNames.AcctInfoExpiredAccount,
PropertyNames.AcctInfoLastLogon,
PropertyNames.AcctInfoAcctLockoutTime,
PropertyNames.AcctInfoBadLogonCount,
PropertyNames.PwdInfoLastPasswordSet
};
// includes AccountInfo and PasswordInfo
internal static string[] userProperties = new string[]
{
PropertyNames.UserGivenName,
PropertyNames.UserMiddleName,
PropertyNames.UserSurname,
PropertyNames.UserEmailAddress,
PropertyNames.UserVoiceTelephoneNumber,
PropertyNames.UserEmployeeID,
PropertyNames.AcctInfoPermittedWorkstations,
PropertyNames.AcctInfoPermittedLogonTimes,
PropertyNames.AcctInfoSmartcardRequired,
PropertyNames.AcctInfoDelegationPermitted,
PropertyNames.AcctInfoHomeDirectory,
PropertyNames.AcctInfoHomeDrive,
PropertyNames.AcctInfoScriptPath,
PropertyNames.PwdInfoPasswordNotRequired,
PropertyNames.PwdInfoPasswordNeverExpires,
PropertyNames.PwdInfoCannotChangePassword,
PropertyNames.PwdInfoAllowReversiblePasswordEncryption
};
internal static string[] groupProperties = new string[]
{
PropertyNames.GroupIsSecurityGroup,
PropertyNames.GroupGroupScope
};
internal static string[] computerProperties = new string[]
{
PropertyNames.ComputerServicePrincipalNames
};
[System.Security.SecurityCritical]
protected QbeFilterDescription BuildQbeFilterDescription(Principal p)
{
QbeFilterDescription qbeFilterDescription = new QbeFilterDescription();
// We don't have to check to make sure the application didn't try to set any
// disallowed properties (i..e, referential properties, such as Group.Members),
// because that check was enforced by the PrincipalSearcher in its
// FindAll() and GetUnderlyingSearcher() methods, by calling
// PrincipalSearcher.HasReferentialPropertiesSet().
if (p is Principal)
BuildFilterSet(p, principalProperties, qbeFilterDescription);
if (p is AuthenticablePrincipal)
BuildFilterSet(p, authenticablePrincipalProperties, qbeFilterDescription);
if (p is UserPrincipal) // includes AccountInfo and PasswordInfo
{
// AcctInfoExpirationDate and AcctInfoExpiredAccount represent filters on the same property
// check that only one is specified
if (p.GetChangeStatusForProperty(PropertyNames.AcctInfoExpirationDate) &&
p.GetChangeStatusForProperty(PropertyNames.AcctInfoExpiredAccount))
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
SR.StoreCtxMultipleFiltersForPropertyUnsupported,
PropertyNamesExternal.GetExternalForm(ExpirationDateFilter.PropertyNameStatic)));
}
BuildFilterSet(p, userProperties, qbeFilterDescription);
}
if (p is GroupPrincipal)
BuildFilterSet(p, groupProperties, qbeFilterDescription);
if (p is ComputerPrincipal)
BuildFilterSet(p, computerProperties, qbeFilterDescription);
return qbeFilterDescription;
}
// Applies to supplied propertySet to the supplied Principal, and adds any resulting filters
// to qbeFilterDescription.
[System.Security.SecurityCritical]
private void BuildFilterSet(Principal p, string[] propertySet, QbeFilterDescription qbeFilterDescription)
{
foreach (string propertyName in propertySet)
{
if (p.GetChangeStatusForProperty(propertyName))
{
// Property has changed. Add it to the filter set.
object value = p.GetValueForProperty(propertyName);
GlobalDebug.WriteLineIf(
GlobalDebug.Info,
"StoreCtx",
"BuildFilterSet: type={0}, property name={1}, property value={2} of type {3}",
p.GetType().ToString(),
propertyName,
value.ToString(),
value.GetType().ToString());
// Build the right filter based on type of the property value
if (value is PrincipalValueCollection<string>)
{
PrincipalValueCollection<string> trackingList = (PrincipalValueCollection<string>)value;
foreach (string s in trackingList.Inserted)
{
object filter = FilterFactory.CreateFilter(propertyName);
((FilterBase)filter).Value = (string)s;
qbeFilterDescription.FiltersToApply.Add(filter);
}
}
else if (value is X509Certificate2Collection)
{
// Since QBE filter objects are always unpersisted, any certs in the collection
// must have been inserted by the application.
X509Certificate2Collection certCollection = (X509Certificate2Collection)value;
foreach (X509Certificate2 cert in certCollection)
{
object filter = FilterFactory.CreateFilter(propertyName);
((FilterBase)filter).Value = (X509Certificate2)cert;
qbeFilterDescription.FiltersToApply.Add(filter);
}
}
else
{
// It's not one of the multivalued cases. Try the scalar cases.
object filter = FilterFactory.CreateFilter(propertyName);
if (value == null)
{
((FilterBase)filter).Value = null;
}
else if (value is bool)
{
((FilterBase)filter).Value = (bool)value;
}
else if (value is string)
{
((FilterBase)filter).Value = (string)value;
}
else if (value is GroupScope)
{
((FilterBase)filter).Value = (GroupScope)value;
}
else if (value is byte[])
{
((FilterBase)filter).Value = (byte[])value;
}
else if (value is Nullable<DateTime>)
{
((FilterBase)filter).Value = (Nullable<DateTime>)value;
}
else if (value is ExtensionCache)
{
((FilterBase)filter).Value = (ExtensionCache)value;
}
else if (value is QbeMatchType)
{
((FilterBase)filter).Value = (QbeMatchType)value;
}
else
{
// Internal error. Didn't match either the known multivalued or scalar cases.
Debug.Fail(String.Format(
CultureInfo.CurrentCulture,
"StoreCtx.BuildFilterSet: fell off end looking for {0} of type {1}",
propertyName,
value.GetType().ToString()
));
}
qbeFilterDescription.FiltersToApply.Add(filter);
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
/// <summary>
/// System.Text.StringBuilder.Replace(oldChar,newChar,startIndex,count)
/// </summary>
class StringBuilderReplace3
{
private const int c_MIN_STRING_LEN = 8;
private const int c_MAX_STRING_LEN = 256;
private const int c_MAX_SHORT_STR_LEN = 31;//short string (<32 chars)
private const int c_MIN_LONG_STR_LEN = 257;//long string ( >256 chars)
private const int c_MAX_LONG_STR_LEN = 65535;
public static int Main()
{
StringBuilderReplace3 test = new StringBuilderReplace3();
TestLibrary.TestFramework.BeginTestCase("for Method:System.Text.StringBuilder.Replace(String,String)");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive test scenarios
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Old string does not exist in source StringBuilder, random new string. ";
const string c_TEST_ID = "P001";
string strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(strSrc);
string newString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
string oldString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
while(-1 < strSrc.IndexOf(oldString))
{
oldString = TestLibrary.Generator.GetString(-55, false,c_MIN_STRING_LEN, c_MAX_STRING_LEN);
}
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
System.Text.StringBuilder newSB = new System.Text.StringBuilder(strSrc.Replace(oldString, newString));
try
{
stringBuilder = stringBuilder.Replace(oldString, newString);
if (0 != string.Compare(newSB.ToString(), stringBuilder.ToString()))
{
string errorDesc = "Value is not " + newSB.ToString() + " as expected: Actual(" + stringBuilder.ToString() + ")";
errorDesc += GetDataString(strSrc, oldString, newString);
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID,errorDesc);
retVal = false;
}
}
catch(Exception e)
{
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, oldString, newString));
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Old string exist in source StringBuilder, random new string. ";
const string c_TEST_ID = "P002";
string strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(strSrc);
string newString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
// 0 <= startIndex < strSrc.Length ( == startIndex is a valid index into strSrc)
int startIndex = TestLibrary.Generator.GetInt32(-55) % strSrc.Length;
// we require that: substrSize >= 1
// substrSize + startIndex <= strSrc.Length
// which is implied by 1 <= substrSize <= strSrc.Length-startIndex
// now for any Int32 k, 0 <= k % strSrc.Length-startIndex <= (strSrcLength-startIndex)-1
// and so 1 <= 1 + (k % strSrc.Length-startIndex) <= strSrcLength-startIndex
// so generate k randomly and let substrSize := 1 + (k % strSrc.Length - startIndex).
int substrSize = (TestLibrary.Generator.GetInt32(-55) % (strSrc.Length - startIndex)) + 1;
string oldString = strSrc.Substring(startIndex, substrSize);
System.Text.StringBuilder newSB = new System.Text.StringBuilder(strSrc.Replace(oldString, newString));
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder = stringBuilder.Replace(oldString, newString);
if (0 != string.Compare(newSB.ToString(), stringBuilder.ToString()))
{
string errorDesc = "Value is not " + newSB.ToString() + " as expected: Actual(" + stringBuilder.ToString() + ")";
errorDesc += GetDataString(strSrc, oldString, newString);
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID,errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, oldString, newString));
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: source StringBuilder is empty, random new string. ";
const string c_TEST_ID = "P003";
string strSrc = string.Empty;
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(strSrc);
string newString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
string oldString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder = stringBuilder.Replace(oldString, newString);
if (string.Empty != stringBuilder.ToString())
{
string errorDesc = "Value is not string of empty as expected: Actual(" + stringBuilder.ToString() + ")";
errorDesc += GetDataString(strSrc, oldString, newString);
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID+errorDesc,errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, oldString, newString));
retVal = false;
}
return retVal;
}
#endregion
#region Negative test scenarios
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: old string value is null reference.";
const string c_TEST_ID = "N001";
string strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
string oldStr = null;
string newStr = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(strSrc);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Replace(oldStr, newStr);
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, "ArgumentNullException is not thrown as expected." + GetDataString(strSrc, oldStr, newStr));
retVal = false;
}
catch (ArgumentNullException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, oldStr, newStr));
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: old string value is string of empty.";
const string c_TEST_ID = "N002";
string strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
string oldStr = string.Empty;
string newStr = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(strSrc);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Replace(oldStr, newStr);
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, "ArgumentNullException is not thrown as expected." + GetDataString(strSrc, oldStr, newStr));
retVal = false;
}
catch (ArgumentException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, oldStr, newStr));
retVal = false;
}
return retVal;
}
#endregion
private string GetDataString(string strSrc, string oldStr, string newStr)
{
string str1, str;
int len1;
if (null == strSrc)
{
str1 = "null";
len1 = 0;
}
else
{
str1 = strSrc;
len1 = strSrc.Length;
}
str = "\n [Source string value] \n \" " + str1 + " \n \" [Length of source string] \n " + len1.ToString()
+ "\n[Old string]\n \" " + oldStr + "\" \n[New string]\n \"" + newStr + "\"";
return str;
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using OpenLiveWriter.Controls;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.Localization;
namespace OpenLiveWriter.HtmlEditor.Linking
{
/// <summary>
/// Summary description for GlossaryManager.
/// </summary>
public class GlossaryManager
{
private static readonly object _lock = new object();
private static GlossaryManager _instance;
private readonly XmlDocument glossaryDocument;
private readonly XmlNode mainNode;
private readonly Hashtable _entries;
private GlossaryUrlSuggester finder = new GlossaryUrlSuggester();
private GlossaryManager()
{
//load up the hashmap of items
_entries = Hashtable.Synchronized(new Hashtable(StringComparer.CurrentCultureIgnoreCase));
InitializeDocument();
glossaryDocument = new XmlDocument();
try
{
glossaryDocument.Load(_glossaryFile);
}
catch(XmlException e)
{
Trace.Fail("Error loading Glossary.xml: " + e);
return;
}
// get the list of glossary items from the xml
mainNode = glossaryDocument.SelectSingleNode("//glossary");
if (mainNode == null)
{
Trace.Fail("Invalid Glossary.xml file detected: Couldn't find root glossary node.");
return;
}
XmlNodeList entryNodes = glossaryDocument.SelectNodes( "//glossary/entry" ) ;
try
{
if (!GlossarySettings.Initialized) // Initialize the default
{
if (entryNodes == null || entryNodes.Count == 0)
{
AddEntry(Res.Get(StringId.GlossaryExampleTitle), "http://www.OpenLiveWriter.org", "", "", false);
}
}
}
catch (ArgumentException e)
{
Trace.Fail("Failed to initialize default glossary entries: " + e);
}
if (entryNodes != null)
{
foreach (XmlNode entryNode in entryNodes)
{
string linktext;
GlossaryLinkItem item;
try
{
linktext = NodeText(entryNode.SelectSingleNode(TEXT));
item = GlossaryLinkItemFromXml(entryNode);
}
catch (ArgumentException e)
{
Trace.Fail("Failed parsing glossary entry: " + e);
continue;
}
try
{
_entries.Add(linktext, item);
finder.Add(linktext, item);
}
catch (ArgumentException e)
{
Trace.Fail("Duplicate entries in Glossary.xml detected: " + e);
}
}
}
}
#region Public Methods
/// <summary>
/// Returns the singleton plugin manager instance.
/// </summary>
public static GlossaryManager Instance
{
get
{
if (_instance == null)
{
lock(_lock)
{
if (_instance == null)
{
_instance = new GlossaryManager();
}
}
}
return _instance;
}
}
public ICollection GetItems()
{
lock (_lock)
{
ArrayList valuesList = new ArrayList(_entries.Values);
valuesList.Sort(Comparer.DefaultInvariant);
return valuesList;
}
}
public void DeleteEntry(string text)
{
lock (_lock)
{
RemoveEntry(text);
}
}
public GlossaryLinkItem AddFromForm(Form parent)
{
//show form to get entry data
using (AddLinkDialog addForm = new AddLinkDialog(_entries.Keys))
{
if (DialogResult.OK == addForm.ShowDialog(parent))
{
return AddEntry(addForm.LinkText, addForm.Url, addForm.Title, addForm.Rel, addForm.OpenInNewWindow);
}
}
return null;
}
public GlossaryLinkItem EditEntry(Form parent, string text)
{
//shows form to edit existing entry
using (AddLinkDialog editForm = new AddLinkDialog(_entries.Keys))
{
editForm.Edit = true;
GlossaryLinkItem editItem = (GlossaryLinkItem)_entries[text];
editForm.LinkText = editItem.Text;
editForm.Url = editItem.Url;
editForm.Title = editItem.Title;
editForm.OpenInNewWindow = editItem.OpenInNewWindow;
editForm.Rel = editItem.Rel;
if (DialogResult.OK == editForm.ShowDialog(parent))
{
//if the link text was changed, make sure to delete the original entry
if (!editItem.Text.Equals(editForm.LinkText, StringComparison.CurrentCultureIgnoreCase))
{
if (_entries.ContainsKey(editForm.LinkText))
{
if (DisplayMessage.Show( MessageId.ConfirmReplaceEntry ) == DialogResult.Yes)
RemoveEntry(text);
else
return null;
}
lock (_lock)
{
DeleteEntry(editItem.Text);
return AddEntry(editForm.LinkText, editForm.Url, editForm.Title, editForm.Rel, editForm.OpenInNewWindow);
}
}
else
{
return AddEntry(editForm.LinkText, editForm.Url, editForm.Title, editForm.Rel, editForm.OpenInNewWindow);
}
}
}
return null;
}
// the match length is the number of matching characters from the end of the string
public GlossaryLinkItem SuggestLink(string text, out int matchLength)
{
lock (_lock)
{
return finder.FindMatch(text, out matchLength);
}
}
public GlossaryLinkItem FindEntry(string text)
{
lock (_lock)
{
if (_entries.ContainsKey(text))
{
return (GlossaryLinkItem)_entries[text];
}
return null;
}
}
public bool FindExactEntry(string text, string url, string title)
{
lock (_lock)
{
if (_entries.ContainsKey(text))
{
GlossaryLinkItem foundItem = (GlossaryLinkItem)_entries[text];
return (foundItem.Url.Equals(url, StringComparison.OrdinalIgnoreCase) &&
foundItem.Title.Equals(title, StringComparison.CurrentCultureIgnoreCase));
}
return false;
}
}
public bool ContainsEntry(string text)
{
lock (_lock)
{
return _entries.ContainsKey(text);
}
}
public GlossaryLinkItem AddEntry(string text, string url, string title, string rel, bool openInNewWindow)
{
if (title == null)
title = String.Empty;
if (url == null)
throw new ArgumentException("url cannot be null");
if (text == null)
throw new ArgumentException("text cannot be null");
lock (_lock)
{
RemoveEntry(text);
GlossaryLinkItem entry = new GlossaryLinkItem(text, url, title, rel, openInNewWindow);
_entries.Add(text, entry);
XmlNode newEntry = GlossaryLinkXmlFromItem(entry);
mainNode.AppendChild(newEntry);
SaveGlossary();
finder.Add(text, entry);
return entry;
}
}
#endregion
#region private
private void RemoveEntry(string text)
{
if (_entries.ContainsKey(text))
{
XmlNodeList entryNodes = glossaryDocument.SelectNodes("//glossary/entry/text");
bool removedXmlEntry = false;
if (entryNodes != null)
{
foreach (XmlNode node in entryNodes)
{
if (text.Equals(NodeText(node), StringComparison.CurrentCultureIgnoreCase))
{
mainNode.RemoveChild(node.ParentNode);
removedXmlEntry = true;
}
}
}
Debug.Assert(removedXmlEntry, "Glossary entry existed in Hashtable but not the XML file!");
_entries.Remove(text);
SaveGlossary();
finder = new GlossaryUrlSuggester();
foreach (DictionaryEntry entry in _entries)
{
finder.Add((string)entry.Key, (GlossaryLinkItem)entry.Value);
}
}
}
private static GlossaryLinkItem GlossaryLinkItemFromXml(XmlNode node)
{
string text = NodeText(node.SelectSingleNode(TEXT));
if ( text.Length == 0 )
throw new ArgumentException("Missing text parameter") ;
string url = NodeText(node.SelectSingleNode(URL)) ;
if ( url.Length == 0 )
throw new ArgumentException("Missing URL parameter");
string title = NodeText(node.SelectSingleNode(TITLE));
string rel = NodeText(node.SelectSingleNode(REL));
string openInNewWindowText = NodeText(node.SelectSingleNode(NEWWINDOW));
bool openInNewWindow;
if(!bool.TryParse(openInNewWindowText, out openInNewWindow))
{
// Default to true if unable to parse it.
openInNewWindow = true;
}
return new GlossaryLinkItem(text, url, title, rel, openInNewWindow);
}
private const string TEXT = "text";
private const string URL = "url";
private const string TITLE = "title";
private const string REL = "rel";
private const string NEWWINDOW = "openInNewWindow";
private XmlNode GlossaryLinkXmlFromItem(GlossaryLinkItem item)
{
XmlElement entryNode = glossaryDocument.CreateElement("entry");
AppendNode(entryNode, TEXT, item.Text);
AppendNode(entryNode, URL, item.Url);
AppendNode(entryNode, TITLE, item.Title);
AppendNode(entryNode, REL, item.Rel);
AppendNode(entryNode, NEWWINDOW, item.OpenInNewWindow.ToString());
return entryNode;
}
private void AppendNode(XmlNode entryNode, string elementName, string value)
{
XmlElement subNode = glossaryDocument.CreateElement(elementName);
subNode.InnerText = value;
entryNode.AppendChild(subNode);
}
private static void InitializeDocument()
{
if ( !Directory.Exists(_glossaryDirectory) )
Directory.CreateDirectory(_glossaryDirectory);
if (!File.Exists(_glossaryFile))
{
XmlDocument emptyGlossary = new XmlDocument();
XmlDeclaration declaration = emptyGlossary.CreateXmlDeclaration("1.0", "utf-8", null);
XmlElement rootNode = emptyGlossary.CreateElement("glossary");
emptyGlossary.InsertBefore(declaration, emptyGlossary.DocumentElement);
emptyGlossary.AppendChild(rootNode);
emptyGlossary.Save(_glossaryFile);
}
}
private static string _glossaryDirectory
{
get
{
string appData = ApplicationEnvironment.ApplicationDataDirectory;
if (appData == null)
appData = Path.GetTempPath();
return Path.Combine(appData, "LinkGlossary");
}
}
private static string _glossaryFile
{
get
{
return Path.Combine(_glossaryDirectory, "linkglossary.xml");
}
}
public int MaxLengthHint
{
get { return finder.MaxLengthHint; }
}
private void SaveGlossary()
{
glossaryDocument.Save(_glossaryFile);
}
private static string NodeText(XmlNode node)
{
if ( node != null )
return node.InnerText.Trim();
else
return String.Empty ;
}
#endregion
}
public class GlossaryLinkItem : IComparable
{
private readonly string _text;
private readonly string _url;
private readonly string _title;
private readonly bool _openInNewWindow;
private readonly string _rel;
public GlossaryLinkItem(string text, string url, string title, string rel, bool openInNewWindow)
{
if (text == null)
{
throw new ArgumentException("text cannot be null");
}
if (url == null)
{
throw new ArgumentException("url cannot be null");
}
if (title == null)
{
throw new ArgumentException("title cannot be null");
}
_text = text.Trim();
_url = url.Trim();
_title = title.Trim();
_rel = rel;
_openInNewWindow = openInNewWindow;
}
public string Text
{
get
{
return _text;
}
}
public string Url
{
get
{
return _url;
}
}
public string Title
{
get
{
return _title;
}
}
public bool OpenInNewWindow
{
get
{
return _openInNewWindow;
}
}
public string Rel
{
get
{
return _rel;
}
}
#region IComparable Members
public int CompareTo(object obj)
{
return String.Compare(Text, ((GlossaryLinkItem)obj).Text, StringComparison.CurrentCultureIgnoreCase);
}
#endregion
}
public class GlossaryUrlSuggester
{
public void Add(string text, GlossaryLinkItem value)
{
_maxLengthHint = Math.Max(text.Length, _maxLengthHint);
_trie.AddReverse(text.ToLower(CultureInfo.CurrentCulture
), value);
}
public GlossaryLinkItem FindMatch(string text, out int length)
{
if (text == null)
{
length = -1;
return null;
}
return _trie.Find(StringHelper.Reverse(text).ToLower(CultureInfo.CurrentCulture), IsAtWordBreak, out length);
}
public int MaxLengthHint
{
get
{
return _maxLengthHint + 1;
}
}
private int _maxLengthHint = -1;
private readonly Trie<GlossaryLinkItem> _trie = new Trie<GlossaryLinkItem>();
private static bool IsAtWordBreak(string text, int charactersMatched)
{
return (charactersMatched >= text.Length || !char.IsLetterOrDigit(text[charactersMatched]));
}
}
}
| |
/*
* WaitHandle.cs - Implementation of the "System.Threading.WaitHandle" class.
*
* Copyright (C) 2001, 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 System.Threading
{
using System.Runtime.CompilerServices;
public abstract class WaitHandle : MarshalByRefObject, IDisposable
{
// Private data used by the runtime engine to
// represent the underlying wait object handle.
// This must be the first field in the object.
private IntPtr privateData;
/// <summary>
/// Constant that specifies a timeout occured within the
/// WaitAny or WaitAll methods.
/// </summary>
public const int WaitTimeout = 258;
// Constructors.
public WaitHandle()
{
privateData = IntPtr.Zero;
}
// Destructor.
~WaitHandle()
{
if(privateData != IntPtr.Zero)
{
Dispose(false);
}
}
// Close the handle and release all resources.
public virtual void Close()
{
Dispose(true);
}
// Internal version of "Close".
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static void InternalClose(IntPtr privateData);
// Dispose this wait handle.
protected virtual void Dispose(bool explicitDisposing)
{
lock(this)
{
if(privateData != IntPtr.Zero)
{
InternalClose(privateData);
privateData = IntPtr.Zero;
}
}
}
// Implement the IDisposable interface.
void IDisposable.Dispose()
{
Dispose(true);
}
// Validate the contents of a "waitHandles" array and
// return a new array of low-level handles.
private static IntPtr[] ValidateHandles(WaitHandle[] waitHandles)
{
int posn, posn2;
WaitHandle handle;
IntPtr[] lowLevel;
if(waitHandles == null)
{
throw new ArgumentNullException("waitHandles");
}
if(waitHandles.Length > 64)
{
throw new NotSupportedException
(_("NotSupp_MaxWaitHandles"));
}
lowLevel = new IntPtr [waitHandles.Length];
for(posn = waitHandles.Length - 1; posn >= 0; --posn)
{
if((handle = waitHandles[posn]) == null ||
handle.privateData == IntPtr.Zero)
{
throw new ArgumentNullException
("waitHandles[" + posn + "]");
}
for(posn2 = posn - 1; posn2 >= 0; --posn2)
{
if(handle == waitHandles[posn2])
{
throw new DuplicateWaitObjectException();
}
}
lowLevel[posn] = handle.privateData;
}
return lowLevel;
}
// Wait for all elements in an array to receive a signal.
public static bool WaitAll(WaitHandle[] waitHandles)
{
IntPtr[] lowLevel = ValidateHandles(waitHandles);
return InternalWaitAll(lowLevel, -1, true);
}
public static bool WaitAll(WaitHandle[] waitHandles,
int millisecondsTimeout,
bool exitContext)
{
IntPtr[] lowLevel = ValidateHandles(waitHandles);
if(millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException
("millisecondsTimeout",
_("ArgRange_NonNegOrNegOne"));
}
return InternalWaitAll(lowLevel, millisecondsTimeout,
exitContext);
}
public static bool WaitAll(WaitHandle[] waitHandles,
TimeSpan timeout, bool exitContext)
{
IntPtr[] lowLevel = ValidateHandles(waitHandles);
return InternalWaitAll(lowLevel,
Monitor.TimeSpanToMS(timeout),
exitContext);
}
// Internal version of "WaitAll". A timeout of -1 indicates infinite,
// and zero indicates "test and return immediately".
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static bool InternalWaitAll
(IntPtr[] waitHandles, int timeout, bool exitContext);
// Wait for any element in an array to receive a signal.
public static int WaitAny(WaitHandle[] waitHandles)
{
IntPtr[] lowLevel = ValidateHandles(waitHandles);
return InternalWaitAny(lowLevel, -1, true);
}
public static int WaitAny(WaitHandle[] waitHandles,
int millisecondsTimeout,
bool exitContext)
{
IntPtr[] lowLevel = ValidateHandles(waitHandles);
if(millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException
("millisecondsTimeout",
_("ArgRange_NonNegOrNegOne"));
}
return InternalWaitAny(lowLevel, millisecondsTimeout,
exitContext);
}
public static int WaitAny(WaitHandle[] waitHandles,
TimeSpan timeout, bool exitContext)
{
IntPtr[] lowLevel = ValidateHandles(waitHandles);
return InternalWaitAny(lowLevel,
Monitor.TimeSpanToMS(timeout),
exitContext);
}
// Internal version of "WaitAny". A timeout of -1 indicates
// infinite, and zero indicates "test and return immediately".
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static int InternalWaitAny
(IntPtr[] waitHandles, int timeout, bool exitContext);
// Wait until this handle receives a signal.
public virtual bool WaitOne()
{
return InternalWaitOne(privateData, -1);
}
public virtual bool WaitOne(int millisecondsTimeout,bool exitContext)
{
if(millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException
("millisecondsTimeout",
_("ArgRange_NonNegOrNegOne"));
}
return InternalWaitOne(privateData, millisecondsTimeout);
}
public virtual bool WaitOne(TimeSpan timeout, bool exitContext)
{
return InternalWaitOne(privateData,
Monitor.TimeSpanToMS(timeout));
}
// Internal version of "WaitOne". A timeout of -1 indicates
// infinite, and zero indicates "test and return immediately".
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static bool InternalWaitOne(IntPtr privateData,
int timeout);
// Value of an invalid handle.
protected static readonly IntPtr InvalidHandle = IntPtr.Zero;
// Get the private handle associated with this object.
// Note: Microsoft's implementation allows the handle
// to be set here, but that's too dangerous to allow.
public virtual IntPtr Handle
{
get
{
return privateData;
}
set
{
throw new NotSupportedException
(_("NotSupp_SetWaitHandle"));
}
}
// Set the handle from a subclass.
internal void SetHandle(IntPtr handle)
{
privateData = handle;
}
}; // class WaitHandle
}; // namespace System.Threading
| |
// 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.Runtime.InteropServices;
using Xunit;
namespace System.Reflection.Tests
{
public class ParameterInfoTests
{
public static IEnumerable<object[]> Parameters_TestData()
{
yield return new object[] { typeof(ParameterInfoMetadata), "Method1", new string[] { "str", "iValue", "lValue" }, new Type[] { typeof(string), typeof(int), typeof(long) } };
yield return new object[] { typeof(ParameterInfoMetadata), "Method2", new string[0], new Type[0] };
yield return new object[] { typeof(ParameterInfoMetadata), "MethodWithArray", new string[] { "strArray" }, new Type[] { typeof(string[]) } };
yield return new object[] { typeof(ParameterInfoMetadata), "VirtualMethod", new string[] { "data" }, new Type[] { typeof(long) } };
yield return new object[] { typeof(ParameterInfoMetadata), "MethodWithRefParameter", new string[] { "str" }, new Type[] { typeof(string).MakeByRefType() } };
yield return new object[] { typeof(ParameterInfoMetadata), "MethodWithOutParameter", new string[] { "i", "str" }, new Type[] { typeof(int), typeof(string).MakeByRefType() } };
yield return new object[] { typeof(GenericClass<string>), "GenericMethod", new string[] { "t" }, new Type[] { typeof(string) } };
}
[Theory]
[MemberData(nameof(Parameters_TestData))]
public void Name(Type type, string methodName, string[] expectedNames, Type[] expectedTypes)
{
MethodInfo methodInfo = GetMethod(type, methodName);
ParameterInfo[] parameters = methodInfo.GetParameters();
Assert.Equal(expectedNames.Length, parameters.Length);
for (int i = 0; i < expectedNames.Length; i++)
{
Assert.Equal(expectedNames[i], parameters[i].Name);
Assert.Equal(expectedTypes[i], parameters[i].ParameterType);
Assert.Equal(i, parameters[i].Position);
Assert.Equal(methodInfo, parameters[i].Member);
}
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "Method1", 0)]
[InlineData(typeof(ParameterInfoMetadata), "VirtualMethod", 0)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithRefParameter", 0)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithOutParameter", 0)]
[InlineData(typeof(GenericClass<string>), "GenericMethod", 0)]
public void Member(Type type, string name, int index)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
Assert.NotNull(parameterInfo.Member);
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithDefault1", 1, true)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithDefault2", 0, true)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithDefault3", 0, true)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithDefault4", 0, true)]
[InlineData(typeof(GenericClass<int>), "GenericMethodWithDefault", 1, true)]
[InlineData(typeof(ParameterInfoMetadata), "Method1", 1, false)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithRefParameter", 0, false)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithOutParameter", 1, false)]
[InlineData(typeof(GenericClass<int>), "GenericMethod", 0, false)]
public void HasDefaultValue(Type type, string name, int index, bool expected)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
Assert.Equal(expected, parameterInfo.HasDefaultValue);
}
[Fact]
public void HasDefaultValue_ReturnParam()
{
ParameterInfo parameterInfo = GetMethod(typeof(ParameterInfoMetadata), "Method1").ReturnParameter;
Assert.True(parameterInfo.HasDefaultValue);
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "Method1", 0)]
[InlineData(typeof(ParameterInfoMetadata), "VirtualMethod", 0)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithRefParameter", 0)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithOutParameter", 0)]
[InlineData(typeof(GenericClass<string>), "GenericMethod", 0)]
public void RawDefaultValue(Type type, string name, int index)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
Assert.NotNull(parameterInfo.RawDefaultValue);
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithRefParameter", 0, false)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithOutParameter", 1, true)]
[InlineData(typeof(ParameterInfoMetadata), "Method1", 1, false)]
public void IsOut(Type type, string name, int index, bool expected)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
Assert.Equal(expected, parameterInfo.IsOut);
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithOutParameter", 1, false)]
public void IsIn(Type type, string name, int index, bool expected)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
Assert.Equal(expected, parameterInfo.IsIn);
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithDefault1", 1, 0)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithDefault2", 0, "abc")]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithDefault3", 0, false)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithDefault4", 0, '\0')]
public void DefaultValue(Type type, string name, int index, object expected)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
Assert.Equal(expected, parameterInfo.DefaultValue);
}
[Fact]
public void DefaultValue_NoDefaultValue()
{
ParameterInfo parameterInfo = GetParameterInfo(typeof(ParameterInfoMetadata), "MethodWithOptionalAndNoDefault", 0);
Assert.Equal(Missing.Value, parameterInfo.DefaultValue);
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "Method1", 1, false)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithOutParameter", 1, false)]
public void IsOptional(Type type, string name, int index, bool expected)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
Assert.Equal(expected, parameterInfo.IsOptional);
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "Method1", 1, false)]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithDefault2", 0, false)]
public void IsRetval(Type type, string name, int index, bool expected)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
Assert.Equal(expected, parameterInfo.IsRetval);
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithOptionalDefaultOutInMarshalParam", 0,
new ParameterAttributes[] { ParameterAttributes.Optional, ParameterAttributes.HasDefault, ParameterAttributes.HasFieldMarshal, ParameterAttributes.Out, ParameterAttributes.In })]
public void Attributes(Type type, string name, int index, ParameterAttributes[] expected)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
foreach (ParameterAttributes attribute in expected)
{
Assert.True(parameterInfo.Attributes.HasFlag(attribute));
}
}
[Theory]
[InlineData(typeof(OptionalAttribute))]
[InlineData(typeof(MarshalAsAttribute))]
[InlineData(typeof(OutAttribute))]
[InlineData(typeof(InAttribute))]
public void CustomAttributesTest(Type attrType)
{
ParameterInfo parameterInfo = GetParameterInfo(typeof(ParameterInfoMetadata), "MethodWithOptionalDefaultOutInMarshalParam", 0);
CustomAttributeData attribute = parameterInfo.CustomAttributes.SingleOrDefault(a => a.AttributeType.Equals(attrType));
Assert.NotNull(attribute);
Assert.NotNull(attribute);
ICustomAttributeProvider prov = parameterInfo as ICustomAttributeProvider;
Assert.NotNull(prov.GetCustomAttributes(attrType, false).SingleOrDefault());
Assert.NotNull(prov.GetCustomAttributes(attrType, true).SingleOrDefault());
Assert.NotNull(prov.GetCustomAttributes(false).SingleOrDefault(a => a.GetType().Equals(attrType)));
Assert.NotNull(prov.GetCustomAttributes(true).SingleOrDefault(a => a.GetType().Equals(attrType)));
Assert.True(prov.IsDefined(attrType, false));
Assert.True(prov.IsDefined(attrType, true));
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "Method1", 0, new Type[0])]
[InlineData(typeof(ParameterInfoMetadata), "VirtualMethod", 0, new Type[0])]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithRefParameter", 0, new Type[0])]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithOutParameter", 0, new Type[0])]
[InlineData(typeof(GenericClass<string>), "GenericMethod", 0, new Type[0])]
public void GetOptionalCustomModifiers(Type type, string name, int index, Type[] expected)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
Assert.Equal(expected, parameterInfo.GetOptionalCustomModifiers());
}
[Theory]
[InlineData(typeof(ParameterInfoMetadata), "Method1", 0, new Type[0])]
[InlineData(typeof(ParameterInfoMetadata), "VirtualMethod", 0, new Type[0])]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithRefParameter", 0, new Type[0])]
[InlineData(typeof(ParameterInfoMetadata), "MethodWithOutParameter", 0, new Type[0])]
[InlineData(typeof(GenericClass<string>), "GenericMethod", 0, new Type[0])]
public void GetRequiredCustomModifiers(Type type, string name, int index, Type[] expected)
{
ParameterInfo parameterInfo = GetParameterInfo(type, name, index);
Assert.Equal(expected, parameterInfo.GetRequiredCustomModifiers());
}
private static ParameterInfo GetParameterInfo(Type type, string name, int index)
{
ParameterInfo[] parameters = GetMethod(type, name).GetParameters();
return parameters[index];
}
private static MethodInfo GetMethod(Type type, string name)
{
return type.GetTypeInfo().DeclaredMethods.FirstOrDefault(methodInfo => methodInfo.Name.Equals(name));
}
// Metadata for reflection
public class ParameterInfoMetadata
{
public void Method1(string str, int iValue, long lValue) { }
public void Method2() { }
public void MethodWithArray(string[] strArray) { }
public virtual void VirtualMethod(long data) { }
public void MethodWithRefParameter(ref string str) { str = "newstring"; }
public void MethodWithOutParameter(int i, out string str) { str = "newstring"; }
public int MethodWithDefault1(long lValue, int iValue = 0) { return 1; }
public int MethodWithDefault2(string str = "abc") { return 1; }
public int MethodWithDefault3(bool result = false) { return 1; }
public int MethodWithDefault4(char c = '\0') { return 1; }
public int MethodWithOptionalAndNoDefault([Optional] object o) { return 1; }
public int MethodWithOptionalDefaultOutInMarshalParam([MarshalAs(UnmanagedType.LPWStr)][Out][In] string str = "") { return 1; }
}
public class GenericClass<T>
{
public void GenericMethod(T t) { }
public string GenericMethodWithDefault(int i, T t = default(T)) { return "somestring"; }
}
}
}
| |
namespace Nancy
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
using Nancy.ModelBinding;
using Nancy.Responses.Negotiation;
using Nancy.Routing;
using Nancy.Session;
using Nancy.Validation;
using Nancy.ViewEngines;
/// <summary>
/// Basic class containing the functionality for defining routes and actions in Nancy.
/// </summary>
public abstract class NancyModule : INancyModule, IHideObjectMembers
{
private readonly List<Route> routes;
/// <summary>
/// Initializes a new instance of the <see cref="NancyModule"/> class.
/// </summary>
protected NancyModule()
: this(String.Empty)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="NancyModule"/> class.
/// </summary>
/// <param name="modulePath">A <see cref="string"/> containing the root relative path that all paths in the module will be a subset of.</param>
protected NancyModule(string modulePath)
{
this.After = new AfterPipeline();
this.Before = new BeforePipeline();
this.OnError = new ErrorPipeline();
this.ModulePath = modulePath;
this.routes = new List<Route>();
}
/// <summary>
/// Non-model specific data for rendering in the response
/// </summary>
public dynamic ViewBag
{
get
{
return this.Context == null ? null : this.Context.ViewBag;
}
}
public dynamic Text
{
get { return this.Context.Text; }
}
/// <summary>
/// Gets <see cref="RouteBuilder"/> for declaring actions for DELETE requests.
/// </summary>
/// <value>A <see cref="RouteBuilder"/> instance.</value>
public RouteBuilder Delete
{
get { return new RouteBuilder("DELETE", this); }
}
/// <summary>
/// Gets <see cref="RouteBuilder"/> for declaring actions for GET requests.
/// </summary>
/// <value>A <see cref="RouteBuilder"/> instance.</value>
/// <remarks>These actions will also be used when a HEAD request is recieved.</remarks>
public RouteBuilder Get
{
get { return new RouteBuilder("GET", this); }
}
/// <summary>
/// Gets <see cref="RouteBuilder"/> for declaring actions for OPTIONS requests.
/// </summary>
/// <value>A <see cref="RouteBuilder"/> instance.</value>
public RouteBuilder Options
{
get { return new RouteBuilder("OPTIONS", this); }
}
/// <summary>
/// Gets <see cref="RouteBuilder"/> for declaring actions for PATCH requests.
/// </summary>
/// <value>A <see cref="RouteBuilder"/> instance.</value>
public RouteBuilder Patch
{
get { return new RouteBuilder("PATCH", this); }
}
/// <summary>
/// Gets <see cref="RouteBuilder"/> for declaring actions for POST requests.
/// </summary>
/// <value>A <see cref="RouteBuilder"/> instance.</value>
public RouteBuilder Post
{
get { return new RouteBuilder("POST", this); }
}
/// <summary>
/// Gets <see cref="RouteBuilder"/> for declaring actions for PUT requests.
/// </summary>
/// <value>A <see cref="RouteBuilder"/> instance.</value>
public RouteBuilder Put
{
get { return new RouteBuilder("PUT", this); }
}
/// <summary>
/// Get the root path of the routes in the current module.
/// </summary>
/// <value>
/// A <see cref="T:System.String" /> containing the root path of the module or <see langword="null" />
/// if no root path should be used.</value><remarks>All routes will be relative to this root path.
/// </remarks>
public string ModulePath { get; protected set; }
/// <summary>
/// Gets all declared routes by the module.
/// </summary>
/// <value>A <see cref="IEnumerable{T}"/> instance, containing all <see cref="Route"/> instances declared by the module.</value>
/// <remarks>This is automatically set by Nancy at runtime.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual IEnumerable<Route> Routes
{
get { return this.routes.AsReadOnly(); }
}
/// <summary>
/// Gets the current session.
/// </summary>
public ISession Session
{
get { return this.Request.Session; }
}
/// <summary>
/// Renders a view from inside a route handler.
/// </summary>
/// <value>A <see cref="ViewRenderer"/> instance that is used to determin which view that should be rendered.</value>
public ViewRenderer View
{
get { return new ViewRenderer(this); }
}
/// <summary>
/// Used to negotiate the content returned based on Accepts header.
/// </summary>
/// <value>A <see cref="Negotiator"/> instance that is used to negotiate the content returned.</value>
public Negotiator Negotiate
{
get { return new Negotiator(this.Context); }
}
/// <summary>
/// Gets or sets the validator locator.
/// </summary>
/// <remarks>This is automatically set by Nancy at runtime.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public IModelValidatorLocator ValidatorLocator { get; set; }
/// <summary>
/// Gets or sets an <see cref="Request"/> instance that represents the current request.
/// </summary>
/// <value>An <see cref="Request"/> instance.</value>
public virtual Request Request
{
get { return this.Context.Request; }
set { this.Context.Request = value; }
}
/// <summary>
/// The extension point for accessing the view engines in Nancy.
/// </summary><value>An <see cref="IViewFactory" /> instance.</value>
/// <remarks>This is automatically set by Nancy at runtime.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public IViewFactory ViewFactory { get; set; }
/// <summary><para>
/// The post-request hook
/// </para><para>
/// The post-request hook is called after the response is created by the route execution.
/// It can be used to rewrite the response or add/remove items from the context.
/// </para>
/// <remarks>This is automatically set by Nancy at runtime.</remarks>
/// </summary>
public AfterPipeline After { get; set; }
/// <summary>
/// <para>
/// The pre-request hook
/// </para>
/// <para>
/// The PreRequest hook is called prior to executing a route. If any item in the
/// pre-request pipeline returns a response then the route is not executed and the
/// response is returned.
/// </para>
/// <remarks>This is automatically set by Nancy at runtime.</remarks>
/// </summary>
public BeforePipeline Before { get; set; }
/// <summary>
/// <para>
/// The error hook
/// </para>
/// <para>
/// The error hook is called if an exception is thrown at any time during executing
/// the PreRequest hook, a route and the PostRequest hook. It can be used to set
/// the response and/or finish any ongoing tasks (close database session, etc).
/// </para>
/// <remarks>This is automatically set by Nancy at runtime.</remarks>
/// </summary>
public ErrorPipeline OnError { get; set; }
/// <summary>
/// Gets or sets the current Nancy context
/// </summary>
/// <value>A <see cref="NancyContext" /> instance.</value>
/// <remarks>This is automatically set by Nancy at runtime.</remarks>
public NancyContext Context { get; set; }
/// <summary>
/// An extension point for adding support for formatting response contents.
/// </summary><value>This property will always return <see langword="null" /> because it acts as an extension point.</value><remarks>Extension methods to this property should always return <see cref="P:Nancy.NancyModuleBase.Response" /> or one of the types that can implicitly be types into a <see cref="P:Nancy.NancyModuleBase.Response" />.</remarks>
public IResponseFormatter Response { get; set; }
/// <summary>
/// Gets or sets the model binder locator
/// </summary>
/// <remarks>This is automatically set by Nancy at runtime.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public IModelBinderLocator ModelBinderLocator { get; set; }
/// <summary>
/// Gets or sets the model validation result
/// </summary>
/// <remarks>This is automatically set by Nancy at runtime when you run validation.</remarks>
public virtual ModelValidationResult ModelValidationResult
{
get { return this.Context == null ? null : this.Context.ModelValidationResult; }
set
{
if (this.Context != null)
{
this.Context.ModelValidationResult = value;
}
}
}
/// <summary>
/// Helper class for configuring a route handler in a module.
/// </summary>
public class RouteBuilder : IHideObjectMembers
{
private readonly string method;
private readonly NancyModule parentModule;
/// <summary>
/// Initializes a new instance of the <see cref="RouteBuilder"/> class.
/// </summary>
/// <param name="method">The HTTP request method that the route should be available for.</param>
/// <param name="parentModule">The <see cref="INancyModule"/> that the route is being configured for.</param>
public RouteBuilder(string method, NancyModule parentModule)
{
this.method = method;
this.parentModule = parentModule;
}
/// <summary>
/// Defines a Nancy route for the specified <paramref name="path"/>.
/// </summary>
/// <value>A delegate that is used to invoke the route.</value>
public Func<dynamic, dynamic> this[string path]
{
set { this.AddRoute(string.Empty, path, null, value); }
}
/// <summary>
/// Defines a Nancy route for the specified <paramref name="path"/> and <paramref name="condition"/>.
/// </summary>
/// <value>A delegate that is used to invoke the route.</value>
public Func<dynamic, dynamic> this[string path, Func<NancyContext, bool> condition]
{
set { this.AddRoute(string.Empty, path, condition, value); }
}
/// <summary>
/// Defines an async route for the specified <paramref name="path"/>
/// </summary>
public Func<dynamic, CancellationToken, Task<dynamic>> this[string path, bool runAsync]
{
set { this.AddRoute(string.Empty, path, null, value); }
}
/// <summary>
/// Defines an async route for the specified <paramref name="path"/> and <paramref name="condition"/>.
/// </summary>
public Func<dynamic, CancellationToken, Task<dynamic>> this[string path, Func<NancyContext, bool> condition, bool runAsync]
{
set { this.AddRoute(string.Empty, path, condition, value); }
}
/// <summary>
/// Defines a Nancy route for the specified <paramref name="path"/> and <paramref name="name"/>
/// </summary>
/// <value>A delegate that is used to invoke the route.</value>
public Func<dynamic, dynamic> this[string name, string path]
{
set { this.AddRoute(name, path, null, value); }
}
/// <summary>
/// Defines a Nancy route for the specified <paramref name="path"/>, <paramref name="condition"/> and <paramref name="name"/>
/// </summary>
/// <value>A delegate that is used to invoke the route.</value>
public Func<dynamic, dynamic> this[string name, string path, Func<NancyContext, bool> condition]
{
set { this.AddRoute(name, path, condition, value); }
}
/// <summary>
/// Defines an async route for the specified <paramref name="path"/> and <paramref name="name"/>
/// </summary>
public Func<dynamic, CancellationToken, Task<dynamic>> this[string name, string path, bool runAsync]
{
set { this.AddRoute(name, path, null, value); }
}
/// <summary>
/// Defines an async route for the specified <paramref name="path"/>, <paramref name="condition"/> and <paramref name="name"/>
/// </summary>
public Func<dynamic, CancellationToken, Task<dynamic>> this[string name, string path, Func<NancyContext, bool> condition, bool runAsync]
{
set { this.AddRoute(name, path, condition, value); }
}
protected void AddRoute(string name, string path, Func<NancyContext, bool> condition, Func<dynamic, dynamic> value)
{
var fullPath = GetFullPath(path);
this.parentModule.routes.Add(Route.FromSync(name, this.method, fullPath, condition, value));
}
protected void AddRoute(string name, string path, Func<NancyContext, bool> condition, Func<dynamic, CancellationToken, Task<dynamic>> value)
{
var fullPath = GetFullPath(path);
this.parentModule.routes.Add(new Route(name, this.method, fullPath, condition, value));
}
private string GetFullPath(string path)
{
var relativePath = (path ?? string.Empty).Trim('/');
var parentPath = (this.parentModule.ModulePath ?? string.Empty).Trim('/');
if (string.IsNullOrEmpty(parentPath))
{
return string.Concat("/", relativePath);
}
if (string.IsNullOrEmpty(relativePath))
{
return string.Concat("/", parentPath);
}
return string.Concat("/", parentPath, "/", relativePath);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.ExceptionServices;
using Xunit;
using Xunit.NetCore.Extensions;
namespace System.Tests
{
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #18718")]
public class AppDomainTests : RemoteExecutorTestBase
{
public AppDomainTests()
{
string sourceTestAssemblyPath = Path.Combine(Environment.CurrentDirectory, "AssemblyResolveTests.dll");
string destTestAssemblyPath = Path.Combine(Environment.CurrentDirectory, "AssemblyResolveTests", "AssemblyResolveTests.dll");
if (File.Exists(sourceTestAssemblyPath))
{
Directory.CreateDirectory(Path.GetDirectoryName(destTestAssemblyPath));
File.Copy(sourceTestAssemblyPath, destTestAssemblyPath, true);
File.Delete(sourceTestAssemblyPath);
}
sourceTestAssemblyPath = Path.Combine(Environment.CurrentDirectory, "TestAppOutsideOfTPA.exe");
destTestAssemblyPath = Path.Combine(Environment.CurrentDirectory, "TestAppOutsideOfTPA", "TestAppOutsideOfTPA.exe");
if (File.Exists(sourceTestAssemblyPath))
{
Directory.CreateDirectory(Path.GetDirectoryName(destTestAssemblyPath));
File.Copy(sourceTestAssemblyPath, destTestAssemblyPath, true);
File.Delete(sourceTestAssemblyPath);
}
}
[Fact]
public void CurrentDomain_Not_Null()
{
Assert.NotNull(AppDomain.CurrentDomain);
}
[Fact]
public void CurrentDomain_Idempotent()
{
Assert.Equal(AppDomain.CurrentDomain, AppDomain.CurrentDomain);
}
[Fact]
public void BaseDirectory_Same_As_AppContext()
{
Assert.Equal(AppDomain.CurrentDomain.BaseDirectory, AppContext.BaseDirectory);
}
[Fact]
public void RelativeSearchPath_Is_Null()
{
Assert.Null(AppDomain.CurrentDomain.RelativeSearchPath);
}
[Fact]
public void UnhandledException_Add_Remove()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
AppDomain.CurrentDomain.UnhandledException -= new UnhandledExceptionEventHandler(MyHandler);
}
[Fact]
public void UnhandledException_NotCalled_When_Handled()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(NotExpectedToBeCalledHandler);
try {
throw new Exception();
}
catch
{
}
AppDomain.CurrentDomain.UnhandledException -= new UnhandledExceptionEventHandler(NotExpectedToBeCalledHandler);
}
[ActiveIssue(12716)]
[PlatformSpecific(~TestPlatforms.OSX)] // Unhandled exception on a separate process causes xunit to crash on osx
[Fact]
public void UnhandledException_Called()
{
System.IO.File.Delete("success.txt");
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.CheckExitCode = false;
RemoteInvoke(() =>
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
throw new Exception("****This Unhandled Exception is Expected****");
#pragma warning disable 0162
return SuccessExitCode;
#pragma warning restore 0162
}, options).Dispose();
Assert.True(System.IO.File.Exists("success.txt"));
}
static void NotExpectedToBeCalledHandler(object sender, UnhandledExceptionEventArgs args)
{
Assert.True(false, "UnhandledException handler not expected to be called");
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
System.IO.File.Create("success.txt");
}
[Fact]
public void DynamicDirectory_Null()
{
Assert.Null(AppDomain.CurrentDomain.DynamicDirectory);
}
[Fact]
public void FriendlyName()
{
string s = AppDomain.CurrentDomain.FriendlyName;
Assert.NotNull(s);
string expected = Assembly.GetEntryAssembly().GetName().Name;
Assert.Equal(expected, s);
}
[Fact]
public void Id()
{
Assert.Equal(1, AppDomain.CurrentDomain.Id);
}
[Fact]
public void IsFullyTrusted()
{
Assert.True(AppDomain.CurrentDomain.IsFullyTrusted);
}
[Fact]
public void IsHomogenous()
{
Assert.True(AppDomain.CurrentDomain.IsHomogenous);
}
[Fact]
public void FirstChanceException_Add_Remove()
{
EventHandler<FirstChanceExceptionEventArgs> handler = (sender, e) =>
{
};
AppDomain.CurrentDomain.FirstChanceException += handler;
AppDomain.CurrentDomain.FirstChanceException -= handler;
}
[Fact]
public void FirstChanceException_Called()
{
bool flag = false;
EventHandler<FirstChanceExceptionEventArgs> handler = (sender, e) =>
{
Exception ex = (Exception) e.Exception;
if (ex is FirstChanceTestException)
{
flag = !flag;
}
};
AppDomain.CurrentDomain.FirstChanceException += handler;
try {
throw new FirstChanceTestException("testing");
}
catch
{
}
AppDomain.CurrentDomain.FirstChanceException -= handler;
Assert.True(flag, "FirstChanceHandler not called");
}
class FirstChanceTestException : Exception
{
public FirstChanceTestException(string message) : base(message)
{ }
}
[Fact]
public void ProcessExit_Add_Remove()
{
EventHandler handler = (sender, e) =>
{
};
AppDomain.CurrentDomain.ProcessExit += handler;
AppDomain.CurrentDomain.ProcessExit -= handler;
}
[Fact]
public void ProcessExit_Called()
{
string path = GetTestFilePath();
RemoteInvoke((pathToFile) =>
{
EventHandler handler = (sender, e) =>
{
File.Create(pathToFile);
};
AppDomain.CurrentDomain.ProcessExit += handler;
return SuccessExitCode;
}, path).Dispose();
Assert.True(File.Exists(path));
}
[Fact]
public void ApplyPolicy()
{
AssertExtensions.Throws<ArgumentNullException>("assemblyName", () => { AppDomain.CurrentDomain.ApplyPolicy(null); });
Assert.Throws<ArgumentException>(() => { AppDomain.CurrentDomain.ApplyPolicy(""); });
Assert.Equal(AppDomain.CurrentDomain.ApplyPolicy(Assembly.GetEntryAssembly().FullName), Assembly.GetEntryAssembly().FullName);
}
[Fact]
public void CreateDomain()
{
AssertExtensions.Throws<ArgumentNullException>("friendlyName", () => { AppDomain.CreateDomain(null); });
Assert.Throws<PlatformNotSupportedException>(() => { AppDomain.CreateDomain("test"); });
}
[Fact]
public void ExecuteAssemblyByName()
{
string name = "TestApp";
var assembly = Assembly.Load(name);
Assert.Equal(5, AppDomain.CurrentDomain.ExecuteAssemblyByName(assembly.FullName));
Assert.Equal(10, AppDomain.CurrentDomain.ExecuteAssemblyByName(assembly.FullName, new string[2] {"2", "3"}));
Assert.Throws<FormatException>(() => AppDomain.CurrentDomain.ExecuteAssemblyByName(assembly.FullName, new string[1] {"a"}));
AssemblyName assemblyName = assembly.GetName();
assemblyName.CodeBase = null;
Assert.Equal(105, AppDomain.CurrentDomain.ExecuteAssemblyByName(assemblyName, new string[3] {"50", "25", "25"}));
}
[Fact]
public void ExecuteAssembly()
{
string name = Path.Combine(Environment.CurrentDirectory, "TestAppOutsideOfTPA", "TestAppOutsideOfTPA.exe");
AssertExtensions.Throws<ArgumentNullException>("assemblyFile", () => AppDomain.CurrentDomain.ExecuteAssembly(null));
Assert.Throws<FileNotFoundException>(() => AppDomain.CurrentDomain.ExecuteAssembly("NonExistentFile.exe"));
Assert.Throws<PlatformNotSupportedException>(() => AppDomain.CurrentDomain.ExecuteAssembly(name, new string[2] {"2", "3"}, null, Configuration.Assemblies.AssemblyHashAlgorithm.SHA1));
Assert.Equal(5, AppDomain.CurrentDomain.ExecuteAssembly(name));
Assert.Equal(10, AppDomain.CurrentDomain.ExecuteAssembly(name, new string[2] { "2", "3" }));
}
[Fact]
public void GetData_SetData()
{
AssertExtensions.Throws<ArgumentNullException>("name", () => { AppDomain.CurrentDomain.SetData(null, null); });
AppDomain.CurrentDomain.SetData("", null);
Assert.Null(AppDomain.CurrentDomain.GetData(""));
AppDomain.CurrentDomain.SetData("randomkey", 4);
Assert.Equal(4, AppDomain.CurrentDomain.GetData("randomkey"));
}
[Fact]
public void IsCompatibilitySwitchSet()
{
Assert.Throws<ArgumentNullException>(() => { AppDomain.CurrentDomain.IsCompatibilitySwitchSet(null); });
Assert.Throws<ArgumentException>(() => { AppDomain.CurrentDomain.IsCompatibilitySwitchSet("");});
Assert.Null(AppDomain.CurrentDomain.IsCompatibilitySwitchSet("randomSwitch"));
}
[Fact]
public void IsDefaultAppDomain()
{
Assert.True(AppDomain.CurrentDomain.IsDefaultAppDomain());
}
[Fact]
public void IsFinalizingForUnload()
{
Assert.False(AppDomain.CurrentDomain.IsFinalizingForUnload());
}
[Fact]
public void toString()
{
string actual = AppDomain.CurrentDomain.ToString();
string expected = "Name:" + AppDomain.CurrentDomain.FriendlyName + Environment.NewLine + "There are no context policies.";
Assert.Equal(expected, actual);
}
[Fact]
public void Unload()
{
AssertExtensions.Throws<ArgumentNullException>("domain", () => { AppDomain.Unload(null);});
Assert.Throws<CannotUnloadAppDomainException>(() => { AppDomain.Unload(AppDomain.CurrentDomain); });
}
[Fact]
public void Load()
{
AssemblyName assemblyName = typeof(AppDomainTests).Assembly.GetName();
assemblyName.CodeBase = null;
Assert.NotNull(AppDomain.CurrentDomain.Load(assemblyName));
Assert.NotNull(AppDomain.CurrentDomain.Load(typeof(AppDomainTests).Assembly.FullName));
Assembly assembly = typeof(AppDomainTests).Assembly;
byte[] aBytes = System.IO.File.ReadAllBytes(assembly.Location);
Assert.NotNull(AppDomain.CurrentDomain.Load(aBytes));
}
[Fact]
public void ReflectionOnlyGetAssemblies()
{
Assert.Equal(Array.Empty<Assembly>(), AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies());
}
[Fact]
public void MonitoringIsEnabled()
{
Assert.False(AppDomain.MonitoringIsEnabled);
Assert.Throws<ArgumentException>(() => {AppDomain.MonitoringIsEnabled = false;});
Assert.Throws<PlatformNotSupportedException>(() => {AppDomain.MonitoringIsEnabled = true;});
}
[Fact]
public void MonitoringSurvivedMemorySize()
{
Assert.Throws<InvalidOperationException>(() => { var t = AppDomain.CurrentDomain.MonitoringSurvivedMemorySize; });
}
[Fact]
public void MonitoringSurvivedProcessMemorySize()
{
Assert.Throws<InvalidOperationException>(() => { var t = AppDomain.MonitoringSurvivedProcessMemorySize; });
}
[Fact]
public void MonitoringTotalAllocatedMemorySize()
{
Assert.Throws<InvalidOperationException>(() => { var t = AppDomain.CurrentDomain.MonitoringTotalAllocatedMemorySize; } );
}
[Fact]
public void MonitoringTotalProcessorTime()
{
Assert.Throws<InvalidOperationException>(() => { var t = AppDomain.CurrentDomain.MonitoringTotalProcessorTime; } );
}
#pragma warning disable 618
[Fact]
public void GetCurrentThreadId()
{
Assert.True(AppDomain.GetCurrentThreadId() == Environment.CurrentManagedThreadId);
}
[Fact]
public void ShadowCopyFiles()
{
Assert.False(AppDomain.CurrentDomain.ShadowCopyFiles);
}
[Fact]
public void AppendPrivatePath()
{
AppDomain.CurrentDomain.AppendPrivatePath("test");
}
[Fact]
public void ClearPrivatePath()
{
AppDomain.CurrentDomain.ClearPrivatePath();
}
[Fact]
public void ClearShadowCopyPath()
{
AppDomain.CurrentDomain.ClearShadowCopyPath();
}
[Fact]
public void SetCachePath()
{
AppDomain.CurrentDomain.SetCachePath("test");
}
[Fact]
public void SetShadowCopyFiles()
{
AppDomain.CurrentDomain.SetShadowCopyFiles();
}
[Fact]
public void SetShadowCopyPath()
{
AppDomain.CurrentDomain.SetShadowCopyPath("test");
}
#pragma warning restore 618
[Fact]
public void GetAssemblies()
{
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
Assert.NotNull(assemblies);
Assert.True(assemblies.Length > 0, "There must be assemblies already loaded in the process");
AppDomain.CurrentDomain.Load(typeof(AppDomainTests).Assembly.GetName().FullName);
Assembly[] assemblies1 = AppDomain.CurrentDomain.GetAssemblies();
// Another thread could have loaded an assembly hence not checking for equality
Assert.True(assemblies1.Length >= assemblies.Length, "Assembly.Load of an already loaded assembly should not cause another load");
Assembly.LoadFile(typeof(AppDomain).Assembly.Location);
Assembly[] assemblies2 = AppDomain.CurrentDomain.GetAssemblies();
Assert.True(assemblies2.Length > assemblies.Length, "Assembly.LoadFile should cause an increase in GetAssemblies list");
int ctr = 0;
foreach (var a in assemblies2)
{
if (a.Location == typeof(AppDomain).Assembly.Location)
ctr++;
}
foreach (var a in assemblies)
{
if (a.Location == typeof(AppDomain).Assembly.Location)
ctr--;
}
Assert.True(ctr > 0, "Assembly.LoadFile should cause file to be loaded again");
}
[Fact]
public void AssemblyLoad()
{
bool AssemblyLoadFlag = false;
AssemblyLoadEventHandler handler = (sender, args) =>
{
if (args.LoadedAssembly.FullName.Equals(typeof(AppDomainTests).Assembly.FullName))
{
AssemblyLoadFlag = !AssemblyLoadFlag;
}
};
AppDomain.CurrentDomain.AssemblyLoad += handler;
try
{
Assembly.LoadFile(typeof(AppDomainTests).Assembly.Location);
}
finally
{
AppDomain.CurrentDomain.AssemblyLoad -= handler;
}
Assert.True(AssemblyLoadFlag);
}
[Fact]
public void AssemblyResolve()
{
RemoteInvoke(() =>
{
ResolveEventHandler handler = (sender, e) =>
{
return Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, "AssemblyResolveTests", "AssemblyResolveTests.dll"));
};
AppDomain.CurrentDomain.AssemblyResolve += handler;
Type t = Type.GetType("AssemblyResolveTests.Class1, AssemblyResolveTests", true);
Assert.NotNull(t);
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void AssemblyResolve_RequestingAssembly()
{
RemoteInvoke(() =>
{
Assembly a = Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, "TestAppOutsideOfTPA", "TestAppOutsideOfTPA.exe"));
ResolveEventHandler handler = (sender, e) =>
{
Assert.Equal(e.RequestingAssembly, a);
return Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, "AssemblyResolveTests", "AssemblyResolveTests.dll"));
};
AppDomain.CurrentDomain.AssemblyResolve += handler;
Type ptype = a.GetType("Program");
MethodInfo myMethodInfo = ptype.GetMethod("foo");
object ret = myMethodInfo.Invoke(null, null);
Assert.NotNull(ret);
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void TypeResolve()
{
Assert.Throws<TypeLoadException>(() => Type.GetType("Program", true));
ResolveEventHandler handler = (sender, args) =>
{
return Assembly.Load("TestApp");
};
AppDomain.CurrentDomain.TypeResolve += handler;
Type t;
try
{
t = Type.GetType("Program", true);
}
finally
{
AppDomain.CurrentDomain.TypeResolve -= handler;
}
Assert.NotNull(t);
}
[Fact]
public void ResourceResolve()
{
ResourceManager res = new ResourceManager(typeof(FxResources.TestApp.SR));
Assert.Throws<MissingManifestResourceException>(() => res.GetString("Message"));
ResolveEventHandler handler = (sender, args) =>
{
return Assembly.Load("TestApp");
};
AppDomain.CurrentDomain.ResourceResolve += handler;
String s;
try
{
s = res.GetString("Message");
}
finally
{
AppDomain.CurrentDomain.ResourceResolve -= handler;
}
Assert.Equal(s, "Happy Halloween");
}
[Fact]
public void SetThreadPrincipal()
{
Assert.Throws<ArgumentNullException>(() => {AppDomain.CurrentDomain.SetThreadPrincipal(null);});
var identity = new System.Security.Principal.GenericIdentity("NewUser");
var principal = new System.Security.Principal.GenericPrincipal(identity, null);
AppDomain.CurrentDomain.SetThreadPrincipal(principal);
}
}
}
namespace FxResources.TestApp
{
class SR { }
}
| |
using System;
using System.Drawing;
using System.Drawing.Imaging;
namespace Hydra.Framework.ImageProcessing.Analysis.Filters
{
//
//**********************************************************************
/// <summary>
/// SimpleSkeletonization filter
/// </summary>
//**********************************************************************
//
public class SimpleSkeletonization
: IFilter
{
#region Private Constants
//
//**********************************************************************
/// <summary>
/// Default Background Bit
/// </summary>
//**********************************************************************
//
private const byte DefaultBackgroundColour_sc = 0;
//
//**********************************************************************
/// <summary>
/// Default Forground Bit
/// </summary>
//**********************************************************************
//
private const byte DefaultForgroundColour_sc = 255;
#endregion
#region Private Member Variables
//
//**********************************************************************
/// <summary>
/// Background
/// </summary>
//**********************************************************************
//
private byte background_m = DefaultBackgroundColour_sc;
//
//**********************************************************************
/// <summary>
/// Forground
/// </summary>
//**********************************************************************
//
private byte forground_m = DefaultForgroundColour_sc;
#endregion
#region Constructors
//
//**********************************************************************
/// <summary>
/// Initialises a new instance of the <see cref="T:SimpleSkeletonization"/> class.
/// </summary>
//**********************************************************************
//
public SimpleSkeletonization()
{
}
//
//**********************************************************************
/// <summary>
/// Initialises a new instance of the <see cref="T:SimpleSkeletonization"/> class.
/// </summary>
/// <param name="bg">The bg.</param>
/// <param name="fg">The fg.</param>
//**********************************************************************
//
public SimpleSkeletonization(byte bg, byte fg)
{
this.background_m = bg;
this.forground_m = fg;
}
#endregion
#region Properties
//
//**********************************************************************
/// <summary>
/// Gets or sets the background property.
/// </summary>
/// <value>The background.</value>
//**********************************************************************
//
public byte Background
{
get
{
return background_m;
}
set
{
background_m = value;
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets the forgroundproperty .
/// </summary>
/// <value>The foreground.</value>
//**********************************************************************
//
public byte Foreground
{
get
{
return forground_m;
}
set
{
forground_m = value;
}
}
#endregion
#region Public Methods
//
//**********************************************************************
/// <summary>
/// Apply filter
/// </summary>
/// <param name="srcImg">The SRC img.</param>
/// <returns></returns>
//**********************************************************************
//
public Bitmap Apply(Bitmap srcImg)
{
if (srcImg.PixelFormat != PixelFormat.Format8bppIndexed)
throw new ArgumentException();
//
// get source image size
//
int width = srcImg.Width;
int height = srcImg.Height;
//
// lock source bitmap data
//
BitmapData srcData = srcImg.LockBits(
new Rectangle(0, 0, width, height),
ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
//
// create new grayscale image
//
Bitmap dstImg = Hydra.Framework.ImageProcessing.Analysis.Image.CreateGrayscaleImage(width, height);
//
// lock destination bitmap data
//
BitmapData dstData = dstImg.LockBits(
new Rectangle(0, 0, width, height),
ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
int stride = dstData.Stride;
int offset = stride - width;
int start;
//
// make destination image filled with background color
//
Win32.memset(dstData.Scan0, background_m, stride * height);
//
// do the job (Warning Unsafe Code)
//
unsafe
{
byte * src0 = (byte *) srcData.Scan0.ToPointer();
byte * dst0 = (byte *) dstData.Scan0.ToPointer();
byte * src = src0;
byte * dst = dst0;
//
// horizontal pass
//
// for each line
for (int y = 0; y < height; y++)
{
start = -1;
//
// for each pixel
//
for (int x = 0; x < width; x++, src ++)
{
//
// looking for foreground pixel
//
if (start == -1)
{
if (*src == forground_m)
start = x;
continue;
}
//
// looking for non black pixel (white)
//
if (*src != forground_m)
{
dst[start + ((x - start) >> 1)] = (byte) forground_m;
start = -1;
}
}
if (start != -1)
{
dst[start + ((width - start) >> 1)] = (byte) forground_m;
}
src += offset;
dst += stride;
}
//
// vertical pass
//
// for each column
for (int x = 0; x < width; x++)
{
src = src0 + x;
dst = dst0 + x;
start = -1;
//
// for each row
//
for (int y = 0; y < height; y++, src += stride)
{
//
// looking for foreground pixel
//
if (start == -1)
{
if (*src == forground_m)
start = y;
continue;
}
//
// looking for non black pixel (white)
//
if (*src != forground_m)
{
dst[stride * (start + ((y - start) >> 1))] = (byte) forground_m;
start = -1;
}
}
if (start != -1)
{
dst[stride * (start + ((height - start) >> 1))] = (byte) forground_m;
}
}
}
//
// unlock both images
//
dstImg.UnlockBits(dstData);
srcImg.UnlockBits(srcData);
return dstImg;
}
#endregion
}
}
| |
using FlatRedBall.Instructions;
using FlatRedBall.ManagedSpriteGroups;
using FlatRedBall.Math;
using FlatRedBall.Math.Geometry;
using FlatRedBall.Utilities;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using Matrix = Microsoft.Xna.Framework.Matrix;
using Vector3 = Microsoft.Xna.Framework.Vector3;
namespace FlatRedBall.Graphics
{
#region Enums
public enum SetCameraOptions
{
PerformZRotation,
ApplyMatrix
}
#endregion
#region Other Classes
public class LayerCameraSettings
{
public float FieldOfView = (float)System.Math.PI / 4.0f;
public bool Orthogonal = false;
public float OrthogonalWidth = 800;
public float OrthogonalHeight = 600;
public float ExtraRotationZ = 0;
/// <summary>
/// Sets the top destination for this Layer.
/// </summary>
/// <remarks>
/// By default, this value is set to -1,
/// which means that the Layer will use its parent Camera's destination. All four destination
/// values must be greater than or equal to 0 to be applied. If any are less than -1, then the Camera's
/// destination values are used.
/// </remarks>
public float TopDestination = -1;
/// <summary>
/// Sets the bottom destination for this Layer. Destination Y values increase when moving down the screen, so this value should be greater than TopDestination (if it is not -1).
/// </summary>
/// <remarks>
/// By default, this value is set to -1,
/// which means that the Layer will use its parent Camera's destination. All four destination
/// values must be greater than or equal to 0 to be applied. If any are less than -1, then the Camera's
/// destination values are used.
/// </remarks>
public float BottomDestination = -1;
/// <summary>
/// Sets the left destination for this Layer.
/// </summary>
/// <remarks>
/// By default, this value is set to -1,
/// which means that the Layer will use its parent Camera's destination. All four destination
/// values must be greater than or equal to 0 to be applied. If any are less than -1, then the Camera's
/// destination values are used.
/// </remarks>
public float LeftDestination = -1;
/// <summary>
/// Sets the right destination for this Layer.
/// </summary>
/// <remarks>
/// By default, this value is set to -1,
/// which means that the Layer will use its parent Camera's destination. All four destination
/// values must be greater than or equal to 0 to be applied. If any are less than -1, then the Camera's
/// destination values are used.
/// </remarks>
public float RightDestination = -1;
public PositionedObject OffsetParent { get; set; }
Vector3 mOldUpVector;
// We used to have
// a RotationMatrix
// but this caused a
// bug in Camera rotation.
// I'm not 100% certain what
// the issue is, but setting the
// individual rotation values seems
// to fix it.
// Update July 20, 2016
// In the current game I'm working on,
// saving and resetting the individual rotation
// components was resulting in a rotation matrix
// that wasn't quite right. To fix this, we're going
// to save and set both sets of values to make sure it
// works perfectly.
float storedRotationX;
float storedRotationY;
float storedRotationZ;
Matrix storedRotationMatrix;
public LayerCameraSettings Clone()
{
return (LayerCameraSettings)this.MemberwiseClone();
}
public void SetFromCamera(Camera camera)
{
mOldUpVector = camera.UpVector;
Orthogonal = camera.Orthogonal;
OrthogonalHeight = camera.OrthogonalHeight;
OrthogonalWidth = camera.OrthogonalWidth;
FieldOfView = camera.FieldOfView;
storedRotationX = camera.RotationX;
storedRotationY = camera.RotationY;
storedRotationZ = camera.RotationZ;
storedRotationMatrix = camera.RotationMatrix;
}
//public void SetCamera(Camera camera, SetCameraOptions options)
//{
//}
public void ApplyValuesToCamera(Camera camera, SetCameraOptions options, LayerCameraSettings lastToModify)
{
var viewport = camera.GetViewport(this);
Renderer.GraphicsDevice.Viewport = viewport;
camera.Orthogonal = Orthogonal;
camera.OrthogonalHeight = OrthogonalHeight;
camera.OrthogonalWidth = OrthogonalWidth;
if (lastToModify == null)
{
// January 11, 2014
// We used to only do
// offsets if the Layer
// was both orthogonal and
// if its orthogonal width and
// height matched the destination.
// Baron runs on multiple resolutions
// and introduced situations where the
// ortho width/height may not match the
// destination rectangles because we may
// scale everything up on larrger resolutions.
// In that situation we still want to have the layers
// offset properly.
// bool offsetOrthogonal = Orthogonal && OrthogonalWidth == RightDestination - LeftDestination &&
// OrthogonalHeight == BottomDestination - TopDestination;
bool offsetOrthogonal = Orthogonal;
if (offsetOrthogonal)
{
int differenceX;
int differenceY;
DetermineOffsetDifference(camera, this, out differenceX, out differenceY);
camera.X += differenceX;
camera.Y -= differenceY;
}
}
else
{
bool offsetOrthogonal = lastToModify.Orthogonal;
// Undo what we did before
if (offsetOrthogonal)
{
int differenceX;
int differenceY;
DetermineOffsetDifference(camera, lastToModify, out differenceX, out differenceY);
camera.X -= differenceX;
camera.Y += differenceY;
}
}
if (options == SetCameraOptions.ApplyMatrix)
{
// This will set the matrix and individual values...
camera.RotationMatrix = storedRotationMatrix;
// ...now set individual values to make sure they dont change:
camera.mRotationX = storedRotationX;
camera.mRotationY = storedRotationY;
camera.mRotationZ = storedRotationZ;
camera.UpVector = mOldUpVector;
}
else
{
if (ExtraRotationZ != 0)
{
camera.RotationMatrix *= Matrix.CreateFromAxisAngle(camera.RotationMatrix.Backward, ExtraRotationZ);
}
camera.UpVector = camera.RotationMatrix.Up;
}
if (this.OffsetParent != null)
{
camera.Position -= this.OffsetParent.Position;
}
// Set FieldOfView last so it updates the matrices
camera.FieldOfView = FieldOfView;
}
private static void DetermineOffsetDifference(Camera camera, LayerCameraSettings settingsToUse, out int differenceX, out int differenceY)
{
int desiredCenterX = camera.DestinationRectangle.Width / 2;
int actualCenterX = (int)((settingsToUse.LeftDestination + settingsToUse.RightDestination) / 2);
differenceX = actualCenterX - desiredCenterX;
if (settingsToUse.RightDestination != settingsToUse.LeftDestination)
{
float xDifferenceMultipier = settingsToUse.OrthogonalWidth / (settingsToUse.RightDestination - settingsToUse.LeftDestination);
differenceX = (int)(differenceX * xDifferenceMultipier);
}
else
{
differenceX = 0;
}
int desiredCenterY = camera.DestinationRectangle.Height / 2;
int actualCenterY = (int)((settingsToUse.BottomDestination + settingsToUse.TopDestination) / 2);
differenceY = actualCenterY - desiredCenterY;
if (settingsToUse.TopDestination != settingsToUse.BottomDestination)
{
float yDifferenceMultipier = settingsToUse.OrthogonalHeight / (settingsToUse.BottomDestination - settingsToUse.TopDestination);
differenceY = (int)(differenceY * yDifferenceMultipier);
}
else
{
differenceY = 0;
}
}
public void UsePixelCoordinates(Camera valuesToPullFrom)
{
Orthogonal = true;
OrthogonalWidth = valuesToPullFrom.DestinationRectangle.Width;
OrthogonalHeight = valuesToPullFrom.DestinationRectangle.Height;
}
public override string ToString()
{
if (Orthogonal)
{
return "Orthogonal, Destination(" +
TopDestination +", " + LeftDestination + ", " + BottomDestination + ", " + RightDestination + ")";
}
else
{
return "Not Orthogonal";
}
}
}
#endregion
#region XML Docs
/// <summary>
/// Layers are objects which can contain other graphical objects for drawing. Layers
/// are used to create specific ordering and can be used to override depth buffer and
/// z-sorted ordering.
/// </summary>
#endregion
public partial class Layer : INameable, IEquatable<Layer>
{
#region Fields
#region XML Docs
/// <summary>
/// List of Sprites that belong to this layer. Sprites should be added
/// through SpriteManager.AddToLayer or the AddSprite overloads which
/// include a Layer argument.
/// </summary>
#endregion
internal SpriteList mSprites = new SpriteList();
internal SpriteList mZBufferedSprites = new SpriteList();
internal PositionedObjectList<Text> mTexts = new PositionedObjectList<Text>();
internal List<IDrawableBatch> mBatches = new List<IDrawableBatch>();
ReadOnlyCollection<Sprite> mSpritesReadOnlyCollection;
ReadOnlyCollection<Sprite> mZBufferedSpritesReadOnly;
ReadOnlyCollection<Text> mTextsReadOnlyCollection;
ReadOnlyCollection<IDrawableBatch> mBatchesReadOnlyCollection;
// internal so the Renderer can access the lists for drawing
internal PositionedObjectList<AxisAlignedRectangle> mRectangles;
internal PositionedObjectList<Circle> mCircles;
internal PositionedObjectList<Polygon> mPolygons;
internal PositionedObjectList<Line> mLines;
internal PositionedObjectList<Sphere> mSpheres;
internal PositionedObjectList<AxisAlignedCube> mCubes;
internal PositionedObjectList<Capsule2D> mCapsule2Ds;
//ListBuffer<Sprite> mSpriteBuffer;
//ListBuffer<Text> mTextBuffer;
//ListBuffer<PositionedModel> mModelBuffer;
//ListBuffer<IDrawableBatch> mBatchBuffer;
bool mVisible;
bool mRelativeToCamera;
internal SortType mSortType = SortType.Z;
internal Camera mCameraBelongingTo = null;
#region XML Docs
/// <summary>
/// Used by the Renderer to override the camera's FieldOfView
/// when drawing the layer. This can be used to give each layer
/// a different field of view.
/// </summary>
#endregion
internal float mOverridingFieldOfView = float.NaN;
string mName;
#endregion
#region Properties
#region XML Docs
/// <summary>
/// The Batches referenced by and drawn on the Layer.
/// </summary>
/// <remarks>
/// The Layer stores a regular IDrawableBatch PositionedObjectList
/// internally. Since this internal list is used for drawing
/// the layer the engine sorts it every frame.
///
/// For efficiency purposes the internal IDrawableBatch PositionedObjectList
/// cannot be sorted.
/// </remarks>
#endregion
public ReadOnlyCollection<IDrawableBatch> Batches
{
get { return mBatchesReadOnlyCollection; }
}
public LayerCameraSettings LayerCameraSettings
{
get;
set;
}
public Camera CameraBelongingTo
{
get { return mCameraBelongingTo; }
}
public bool IsEmpty
{
get
{
return mSprites.Count == 0 &&
mTexts.Count == 0 &&
mBatches.Count == 0 &&
mRectangles.Count == 0 &&
mCircles.Count == 0 &&
mPolygons.Count == 0 &&
mLines.Count == 0 &&
mSpheres.Count == 0 &&
mCubes.Count == 0 &&
mCapsule2Ds.Count == 0;
}
}
public string Name
{
get { return mName; }
set
{
mName = value;
mSprites.Name = value + " Sprites";
mTexts.Name = value + " Texts";
}
}
//#region XML Docs
///// <summary>
///// The FieldOfView to use when drawing this Layer. If the value is
///// float.NaN (default) then the Camera's FieldOfView is used.
///// </summary>
//#endregion
//public float OverridingFieldOfView
//{
// get { return mOverridingFieldOfView; }
// set { mOverridingFieldOfView = value; }
//}
public bool RelativeToCamera
{
get { return mRelativeToCamera; }
set { mRelativeToCamera = value; }
}
#region XML Docs
/// <summary>
/// The Sprites referenced by and drawn on the Layer.
/// </summary>
/// <remarks>
/// The Layer stores a regular SpriteList internally. Since
/// this internal list is used for drawing the layer the engine
/// sorts it every frame.
///
/// For efficiency purposes the internal SpriteList cannot be sorted.
/// </remarks>
#endregion
public ReadOnlyCollection<Sprite> Sprites
{
get { return mSpritesReadOnlyCollection; }
}
public ReadOnlyCollection<Sprite> ZBufferedSprites
{
get { return mZBufferedSpritesReadOnly; }
set { mZBufferedSpritesReadOnly = value; }
}
#region XML Docs
/// <summary>
/// The Texts referenced by and drawn on the Layer.
/// </summary>
/// <remarks>
/// The Layer stores a regular Text PositionedObjectList
/// internally. Since this internal list is used for drawing
/// the layer the engine sorts it every frame.
///
/// For efficiency purposes the internal Text PositionedObjectList
/// cannot be sorted.
/// </remarks>
#endregion
public ReadOnlyCollection<Text> Texts
{
get { return mTextsReadOnlyCollection; }
}
public IEnumerable<AxisAlignedCube> AxisAlignedCubes
{
get
{
return mCubes;
}
}
public IEnumerable<AxisAlignedRectangle> AxisAlignedRectangles
{
get
{
return mRectangles;
}
}
public IEnumerable<Capsule2D> Capsule2Ds
{
get
{
return mCapsule2Ds;
}
}
public IEnumerable<Circle> Circles
{
get
{
return mCircles;
}
}
public IEnumerable<Line> Lines
{
get
{
return mLines;
}
}
public IEnumerable<Polygon> Polygons
{
get
{
return mPolygons;
}
}
public IEnumerable<Sphere> Spheres
{
get
{
return mSpheres;
}
}
public SortType SortType
{
get { return mSortType; }
set { mSortType = value; }
}
#region XML Docs
/// <summary>
/// Whether the SpriteLayer is visible.
/// </summary>
/// <remarks>
/// This does not set the contained Sprite's visible value to false.
/// </remarks>
#endregion
public bool Visible
{
get { return mVisible; }
set { mVisible = value; }
}
/// <summary>
/// The render target to render to. If this is null (default), then the layer
/// will render to whatever render target has been set before FlatRedBall's drawing
/// code starts. If this is non-null, then the layer will render to the RenderTarget.
/// If multiple layers use the same RenderTarget, they will all render to it without clearing
/// it.
/// </summary>
/// <remarks>
/// If a Layer uses a RenderTarge, it will clear the render target if:
/// - It is the UnderAll layer
/// - It is the first Layer on a camera
/// - It uses a different RenderTarget than the previous Layer.
/// </remarks>
public RenderTarget2D RenderTarget
{
get;
set;
}
#endregion
#region Methods
#region Constructor
// This used to be internal, but
// Glue needs to be able to instantiate
// Layers before adding them to managers
// so that it can be done in Initialize before
// we set properties on the Layer like Visible.
public Layer()
{
mSprites.Name = "Layer SpriteList";
mZBufferedSprites.Name = "Layered ZBuffered SpriteList";
mTexts.Name = "Layer Text PositionedObjectList";
mSpritesReadOnlyCollection = new ReadOnlyCollection<Sprite>(mSprites);
mZBufferedSpritesReadOnly = new ReadOnlyCollection<Sprite>(mZBufferedSprites);
mTextsReadOnlyCollection = new ReadOnlyCollection<Text>(mTexts);
mBatchesReadOnlyCollection = new ReadOnlyCollection<IDrawableBatch>(mBatches);
//mSpriteBuffer = new ListBuffer<Sprite>(mSprites);
//mTextBuffer = new ListBuffer<Text>(mTexts);
//mModelBuffer = new ListBuffer<PositionedModel>(mModels);
//mBatchBuffer = new ListBuffer<IDrawableBatch>(mBatches);
mRectangles = new PositionedObjectList<AxisAlignedRectangle>();
mRectangles.Name = "Layered AxisAlignedRectangles";
mCircles = new PositionedObjectList<Circle>();
mCircles.Name = "Layered Circles";
mPolygons = new PositionedObjectList<Polygon>();
mPolygons.Name = "Layered Polygons";
mLines = new PositionedObjectList<Line>();
mLines.Name = "Layered Lines";
mSpheres = new PositionedObjectList<Sphere>();
mSpheres.Name = "Layered Spheres";
mCubes = new PositionedObjectList<AxisAlignedCube>();
mCubes.Name = "Layered Cubes";
mCapsule2Ds = new PositionedObjectList<Capsule2D>();
mCapsule2Ds.Name = "Layered Capsule2Ds";
mVisible = true;
}
#endregion
#region Public Methods
public float PixelsPerUnitAt(float absoluteZ)
{
Camera camera = Camera.Main;
if (this.mCameraBelongingTo != null)
{
camera = this.mCameraBelongingTo;
}
if (this.LayerCameraSettings != null)
{
Vector3 position = new Vector3();
position.Z = absoluteZ;
return camera.PixelsPerUnitAt(ref position, LayerCameraSettings.FieldOfView, LayerCameraSettings.Orthogonal, LayerCameraSettings.OrthogonalHeight);
}
else
{
return camera.PixelsPerUnitAt(absoluteZ);
}
}
public void SortYSpritesSecondary()
{
mSprites.SortYInsertionDescendingOnZBreaks();
}
public void Remove(Sprite spriteToRemove)
{
if (spriteToRemove.ListsBelongingTo.Contains(mSprites))
{
mSprites.Remove(spriteToRemove);
}
else
{
mZBufferedSprites.Remove(spriteToRemove);
}
}
public void Remove(SpriteFrame spriteFrame)
{
if (spriteFrame.mLayerBelongingTo == this)
{
if (spriteFrame.mCenter != null)
spriteFrame.mLayerBelongingTo.Remove(spriteFrame.mCenter);
if (spriteFrame.mTop != null)
spriteFrame.mLayerBelongingTo.Remove(spriteFrame.mTop);
if (spriteFrame.mBottom != null)
spriteFrame.mLayerBelongingTo.Remove(spriteFrame.mBottom);
if (spriteFrame.mLeft != null)
spriteFrame.mLayerBelongingTo.Remove(spriteFrame.mLeft);
if (spriteFrame.mRight != null)
spriteFrame.mLayerBelongingTo.Remove(spriteFrame.mRight);
if (spriteFrame.mTopLeft != null)
spriteFrame.mLayerBelongingTo.Remove(spriteFrame.mTopLeft);
if (spriteFrame.mTopRight != null)
spriteFrame.mLayerBelongingTo.Remove(spriteFrame.mTopRight);
if (spriteFrame.mBottomLeft != null)
spriteFrame.mLayerBelongingTo.Remove(spriteFrame.mBottomLeft);
if (spriteFrame.mBottomRight != null)
spriteFrame.mLayerBelongingTo.Remove(spriteFrame.mBottomRight);
}
}
public void Remove(Text textToRemove)
{
mTexts.Remove(textToRemove);
}
public void Remove(Scene scene)
{
for (int i = scene.Sprites.Count-1; i > -1; i--)
{
Remove(scene.Sprites[i]);
}
for (int i = scene.SpriteGrids.Count - 1; i > -1 ; i--)
{
SpriteGrid spriteGrid = scene.SpriteGrids[i];
spriteGrid.Layer = null;
}
for (int i = scene.SpriteFrames.Count - 1; i > -1; i--)
{
Remove(scene.SpriteFrames[i]);
}
for (int i = scene.Texts.Count - 1; i > -1; i--)
{
Remove(scene.Texts[i]);
}
}
public void Remove(Circle circle)
{
this.mCircles.Remove(circle);
circle.mLayerBelongingTo = null;
}
public void Remove(AxisAlignedRectangle rectangle)
{
this.mRectangles.Remove(rectangle);
rectangle.mLayerBelongingTo = null;
}
public void Remove(Polygon polygon)
{
this.mPolygons.Remove(polygon);
polygon.mLayerBelongingTo = null;
}
public void Remove(Line line)
{
this.mLines.Remove(line);
line.mLayerBelongingTo = null;
}
public void Remove(Sphere sphere)
{
this.mSpheres.Remove(sphere);
sphere.mLayerBelongingTo = null;
}
public void Remove(AxisAlignedCube cube)
{
this.mCubes.Remove(cube);
cube.mLayerBelongingTo = null;
}
public void Remove(Capsule2D capsule2D)
{
this.mCapsule2Ds.Remove(capsule2D);
capsule2D.mLayerBelongingTo = null;
}
public void Remove(ShapeCollection shapeCollection)
{
foreach (var item in shapeCollection.AxisAlignedCubes) Remove(item);
foreach (var item in shapeCollection.AxisAlignedRectangles) Remove(item);
foreach (var item in shapeCollection.Capsule2Ds) Remove(item);
foreach (var item in shapeCollection.Circles) Remove(item);
foreach (var item in shapeCollection.Lines) Remove(item);
foreach (var item in shapeCollection.Polygons) Remove(item);
foreach (var item in shapeCollection.Spheres) Remove(item);
}
public void Remove(IDrawableBatch batchToRemove)
{
mBatches.Remove(batchToRemove);
}
public void SetLayer(Layer otherLayerToSetPropertiesOn)
{
mSortType = otherLayerToSetPropertiesOn.SortType;
mOverridingFieldOfView = otherLayerToSetPropertiesOn.mOverridingFieldOfView;
if (otherLayerToSetPropertiesOn.LayerCameraSettings == null)
{
LayerCameraSettings = null;
}
else
{
LayerCameraSettings = otherLayerToSetPropertiesOn.LayerCameraSettings.Clone();
}
}
public override string ToString()
{
return "Name: " + mName;
}
public void UsePixelCoordinates()
{
if (LayerCameraSettings == null)
{
LayerCameraSettings = new LayerCameraSettings();
}
if (mCameraBelongingTo != null)
{
LayerCameraSettings.UsePixelCoordinates(mCameraBelongingTo);
}
else
{
LayerCameraSettings.UsePixelCoordinates(SpriteManager.Camera);
}
}
public void WorldToLayerCoordinates(float worldX, float worldY, float worldZ, out float xOnLayer, out float yOnLayer)
{
xOnLayer = 0;
yOnLayer = 0;
int screenX = 0;
int screenY = 0;
MathFunctions.AbsoluteToWindow(worldX, worldY, worldZ, ref screenX, ref screenY, SpriteManager.Camera);
if(this.LayerCameraSettings == null)
{
MathFunctions.WindowToAbsolute(screenX, screenY, ref xOnLayer, ref yOnLayer, worldZ, SpriteManager.Camera, Camera.CoordinateRelativity.RelativeToWorld);
}
else
{
float xEdge = 0;
float yEdge = 0;
if (LayerCameraSettings.Orthogonal)
{
xEdge = LayerCameraSettings.OrthogonalWidth / 2.0f;
yEdge = LayerCameraSettings.OrthogonalHeight / 2.0f;
}
else
{
xEdge = (float)(100 * System.Math.Tan(LayerCameraSettings.FieldOfView / 2.0));
// Right now we just assume the same aspect ratio, but we may want the LayerCamerasettings
// to have its own AspectRatio - if so, this needs to be modified
yEdge = (float)(xEdge * SpriteManager.Camera.AspectRatio);
}
Rectangle destinationRectangle;
if (LayerCameraSettings.LeftDestination > 0 && LayerCameraSettings.TopDestination > 0)
{
destinationRectangle = new Rectangle(
MathFunctions.RoundToInt(LayerCameraSettings.LeftDestination),
MathFunctions.RoundToInt(LayerCameraSettings.RightDestination),
MathFunctions.RoundToInt(LayerCameraSettings.RightDestination - LayerCameraSettings.LeftDestination),
MathFunctions.RoundToInt(LayerCameraSettings.BottomDestination - LayerCameraSettings.TopDestination));
}
else
{
destinationRectangle = SpriteManager.Camera.DestinationRectangle;
}
if (LayerCameraSettings.Orthogonal)
{
Camera camera = SpriteManager.Camera;
float top = camera.Y + LayerCameraSettings.OrthogonalHeight/2.0f;
float left = camera.X - LayerCameraSettings.OrthogonalWidth/2.0f;
float distanceFromLeft = LayerCameraSettings.OrthogonalWidth * screenX / (float)camera.DestinationRectangle.Width;
float distanceFromTop = -LayerCameraSettings.OrthogonalHeight * screenY / (float)camera.DestinationRectangle.Height;
xOnLayer = left + distanceFromLeft;
yOnLayer = top + distanceFromTop;
}
else
{
MathFunctions.WindowToAbsolute(screenX, screenY,
ref xOnLayer, ref yOnLayer, worldZ,
SpriteManager.Camera.Position,
xEdge,
yEdge,
destinationRectangle,
Camera.CoordinateRelativity.RelativeToWorld);
}
}
}
#endregion
#region Internal Methods
internal void Add(Sprite sprite)
{
if (sprite.mOrdered)
{
#if DEBUG
if (mSprites.Contains(sprite))
{
throw new InvalidOperationException("Can't add the Sprite to this layer because it's already added");
}
#endif
mSprites.Add(sprite);
}
else
{
#if DEBUG
if (mZBufferedSprites.Contains(sprite))
{
throw new InvalidOperationException("Can't add the Sprite to this layer because it's already added");
}
#endif
mZBufferedSprites.Add(sprite);
}
}
internal void Add(Text text)
{
#if DEBUG
if (text.mListsBelongingTo.Contains(mTexts))
{
throw new InvalidOperationException("This text is already part of this layer.");
}
#endif
mTexts.Add(text);
}
internal void Add(IDrawableBatch drawableBatch)
{
mBatches.Add(drawableBatch);
}
//internal void Flush()
//{
// mSpriteBuffer.Flush();
// mTextBuffer.Flush();
// mModelBuffer.Flush();
// mBatchBuffer.Flush();
//}
#endregion
#endregion
#region IEquatable<Layer> Members
bool IEquatable<Layer>.Equals(Layer other)
{
return this == other;
}
#endregion
}
}
| |
using BTDB.IL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BTDB.Collections;
using BTDB.KVDBLayer;
namespace BTDB.IOC;
class GenerationContext : IGenerationContext
{
readonly ContainerImpl _container;
readonly ICRegILGen _registration;
IBuildContext? _buildContext;
readonly Dictionary<Type, object> _specifics = new Dictionary<Type, object>();
readonly ParameterInfo[]? _parameterInfos;
readonly List<Tuple<object, Type>> _constants = new List<Tuple<object, Type>>();
readonly Stack<Tuple<ICReg, string>> _cycleDetectionStack = new Stack<Tuple<ICReg, string>>();
public GenerationContext(ContainerImpl container, ICRegILGen registration, IBuildContext buildContext)
{
_container = container;
_registration = registration;
_buildContext = buildContext;
_parameterInfos = null;
}
public GenerationContext(ContainerImpl container, ICRegILGen registration, IBuildContext buildContext,
ParameterInfo[] parameterInfos)
{
_container = container;
_registration = registration;
_buildContext = buildContext;
_parameterInfos = parameterInfos;
}
public IILGen? IL { get; private set; }
public ContainerImpl Container => _container;
public IBuildContext? BuildContext
{
get => _buildContext;
set => _buildContext = value;
}
public T GetSpecific<T>() where T : class, new()
{
if (!_specifics.TryGetValue(typeof(T), out var specific))
{
specific = new T();
if (specific is IGenerationContextSetter contextSetter)
contextSetter.Set(this);
_specifics.Add(typeof(T), specific);
}
return (T)specific;
}
public IEnumerable<INeed> NeedsForConstructor(ConstructorInfo constructor)
{
foreach (var parameter in constructor.GetParameters())
{
yield return new Need
{
Kind = NeedKind.ConstructorParameter,
ParentType = constructor.ReflectedType,
ClrType = parameter.ParameterType,
Optional = parameter.IsOptional,
OptionalValue = parameter.RawDefaultValue,
ForcedKey = false,
Key = string.Intern(parameter.Name ?? "")
};
}
}
public IEnumerable<INeed> NeedsForProperties(Type type, bool autowired)
{
foreach (var propertyInfo in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (propertyInfo.GetAnySetMethod() == null) continue;
var dependencyAttribute = propertyInfo.GetCustomAttribute<DependencyAttribute>();
if (dependencyAttribute == null && !autowired) continue;
yield return new Need
{
Kind = NeedKind.Property,
ParentType = type,
ClrType = propertyInfo.PropertyType,
Optional = EmitHelpers.IsNullable(type, propertyInfo),
ForcedKey = false,
Key = string.Intern(dependencyAttribute?.Name ?? propertyInfo.Name),
PropertyInfo = propertyInfo
};
}
}
public void PushToILStack(INeed need)
{
var regIL = ResolveNeed(need);
var local = regIL.GenMain(this);
if (local != null)
{
IL!.Ldloc(local);
}
}
public void PushToILStack(IEnumerable<INeed> needsEnumerable)
{
var needs = needsEnumerable.ToArray();
var regs = needs.Select(ResolveNeed).ToArray();
var parsLocals = new StructList<IILLocal?>();
parsLocals.Reserve((uint)regs.Length);
var index = 0;
foreach (var reg in regs)
{
if (reg.IsCorruptingILStack(this))
{
var local = reg.GenMain(this);
if (local == null)
{
local = IL!.DeclareLocal(needs[index].ClrType);
IL.Stloc(local);
}
parsLocals.Add(local);
}
else
{
parsLocals.Add(null);
}
index++;
}
for (var i = 0; i < regs.Length; i++)
{
var local = parsLocals[i];
if (local != null)
{
IL!.Ldloc(local);
}
else
{
local = regs[i].GenMain(this);
if (local != null)
{
IL!.Ldloc(local);
}
}
if (local == null) continue;
if (local.LocalType != needs[i].ClrType && local.LocalType.IsClass)
{
IL.UnboxAny(needs[i].ClrType);
}
}
}
public bool AnyCorruptingStack(IEnumerable<INeed> needs)
{
foreach (var regILGen in needs.Select(ResolveNeed))
{
if (regILGen.IsCorruptingILStack(this)) return true;
}
return false;
}
public bool IsResolvableNeed(INeed need)
{
return _resolvers.ContainsKey(new Tuple<IBuildContext, INeed>(_buildContext, need));
}
public ICRegILGen ResolveNeed(INeed need)
{
return _resolvers[new Tuple<IBuildContext, INeed>(_buildContext, need)];
}
public void PushToCycleDetector(ICReg reg, string name)
{
if (_cycleDetectionStack.Any(t => t.Item1 == reg))
{
throw new InvalidOperationException("Cycle detected in registrations: " +
string.Join(", ", _cycleDetectionStack.Select(t => t.Item2)) +
". Consider using Lazy<> to break cycle.");
}
_cycleDetectionStack.Push(new Tuple<ICReg, string>(reg, name));
}
public void PopFromCycleDetector()
{
_cycleDetectionStack.Pop();
}
readonly Dictionary<Tuple<IBuildContext, INeed>, ICRegILGen> _resolvers =
new Dictionary<Tuple<IBuildContext, INeed>, ICRegILGen>(Comparer.Instance);
class Comparer : IEqualityComparer<Tuple<IBuildContext, INeed>>
{
internal static readonly Comparer Instance = new Comparer();
public bool Equals(Tuple<IBuildContext, INeed> x, Tuple<IBuildContext, INeed> y)
{
if (x.Item1 != y.Item1) return false;
var nx = x.Item2;
var ny = y.Item2;
if (nx.Kind != ny.Kind) return false;
if (nx.ClrType != ny.ClrType) return false;
if (nx.Key != ny.Key) return false;
if (nx.ForcedKey != ny.ForcedKey) return false;
if (nx.Optional != ny.Optional) return false;
return true;
}
public int GetHashCode(Tuple<IBuildContext, INeed> obj)
{
return obj.Item1.GetHashCode() * 33 + obj.Item2.ClrType.GetHashCode();
}
}
class ComparerConst : IEqualityComparer<Tuple<object, Type>>
{
internal static readonly ComparerConst Instance = new ComparerConst();
public bool Equals(Tuple<object, Type> x, Tuple<object, Type> y)
{
return x.Item1 == y.Item1 && x.Item2 == y.Item2;
}
public int GetHashCode(Tuple<object, Type> obj)
{
return obj.Item1.GetHashCode() * 33 + obj.Item2.GetHashCode();
}
}
class ComparerProcessingContext : IEqualityComparer<Tuple<IBuildContext, ICRegILGen>>
{
internal static readonly ComparerProcessingContext Instance = new ComparerProcessingContext();
public bool Equals(Tuple<IBuildContext, ICRegILGen> x, Tuple<IBuildContext, ICRegILGen> y)
{
return x.Item1 == y.Item1 && x.Item2 == y.Item2;
}
public int GetHashCode(Tuple<IBuildContext, ICRegILGen> obj)
{
return obj.Item1.GetHashCode() * 33 + obj.Item2.GetHashCode();
}
}
void GatherNeeds(ICRegILGen regILGen, HashSet<Tuple<IBuildContext, ICRegILGen>> processed)
{
var processingContext = new Tuple<IBuildContext, ICRegILGen>(_buildContext, regILGen);
if (processed.Contains(processingContext)) return;
processed.Add(processingContext);
foreach (var need in regILGen.GetNeeds(this))
{
if (need.Kind == NeedKind.CReg)
{
GatherNeeds(((ICRegILGen)need.Key)!, processed);
continue;
}
var k = new Tuple<IBuildContext, INeed>(_buildContext, need);
if (_resolvers.ContainsKey(k))
continue;
if (need == Need.ContainerNeed)
{
_resolvers.Add(k, AddConstant(_container, need.ClrType));
continue;
}
if (need.Kind == NeedKind.Constant)
{
_resolvers.Add(k, AddConstant(need.Key, need.ClrType));
continue;
}
if (need.Kind == NeedKind.ConstructorParameter)
{
var reg = ResolveNeedBy(need.ClrType, need.Key);
if (reg == null && !need.ForcedKey)
reg = ResolveNeedBy(need.ClrType, null);
if (reg == null && need.Optional)
reg = new OptionalImpl(need.OptionalValue!, need.ClrType);
if (reg == null)
{
throw new ArgumentException(
$"Cannot resolve {need.ClrType.ToSimpleName()} with key {need.Key}");
}
_resolvers.Add(new Tuple<IBuildContext, INeed>(_buildContext, need), reg);
GatherNeeds(reg, processed);
}
if (need.Kind == NeedKind.Property)
{
var reg = ResolveNeedBy(need.ClrType, need.Key);
if (reg == null && !need.ForcedKey)
reg = ResolveNeedBy(need.ClrType, null);
if (reg == null)
{
if (!need.Optional)
throw new ArgumentException(
$"Cannot resolve {need.ClrType.ToSimpleName()} with key {need.Key}");
return;
}
_resolvers.Add(new Tuple<IBuildContext, INeed>(_buildContext, need), reg);
GatherNeeds(reg, processed);
}
}
}
class OptionalImpl : ICRegILGen
{
readonly object? _value;
readonly Type _type;
public OptionalImpl(object value, Type type)
{
_type = type;
_value = value;
}
public string GenFuncName(IGenerationContext context)
{
throw new InvalidOperationException();
}
public void GenInitialization(IGenerationContext context)
{
}
public bool IsCorruptingILStack(IGenerationContext context)
{
return false;
}
public IILLocal? GenMain(IGenerationContext context)
{
// For some reason struct's RawDefaultValue is null
// Partial explanation is that structs are not really compile time constants
// so they are nullable during compilation and then assigned at runtime
if (_type.IsValueType && _value == null)
{
var local = context.IL.DeclareLocal(_type);
context.IL
.Ldloca(local)
.InitObj(_type)
.Ldloc(local);
}
else if (_type.IsValueType && _value != null && !_type.IsPrimitive && !_type.IsEnum)
{
var ctor = _type.GetConstructors()[0];
context.IL
.Ld(_value)
.Newobj(ctor);
}
else
context.IL.Ld(_value);
return null;
}
public IEnumerable<INeed> GetNeeds(IGenerationContext context)
{
yield break;
}
public bool IsSingletonSafe()
{
return true;
}
}
ICRegILGen AddConstant(object? obj, Type type)
{
var tuple = new Tuple<object, Type>(obj, type);
var comp = ComparerConst.Instance;
foreach (var constant in _constants)
{
if (comp.Equals(constant, tuple))
{
tuple = constant;
goto found;
}
}
_constants.Add(tuple);
found:
return new ConstantImpl(tuple);
}
class ConstantImpl : ICRegILGen
{
readonly Tuple<object, Type> _tuple;
public ConstantImpl(Tuple<object, Type> tuple)
{
_tuple = tuple;
}
public string GenFuncName(IGenerationContext context)
{
throw new InvalidOperationException();
}
public void GenInitialization(IGenerationContext context)
{
}
public bool IsCorruptingILStack(IGenerationContext context)
{
return false;
}
public IILLocal? GenMain(IGenerationContext context)
{
var constants = ((GenerationContext)context)._constants;
if (constants.Count == 1)
{
context.IL.Ldarg(0);
return null;
}
var idx = constants.FindIndex(t => ReferenceEquals(t, _tuple));
context.IL.Ldarg(0).LdcI4(idx).LdelemRef().Castclass(_tuple.Item2);
return null;
}
public IEnumerable<INeed> GetNeeds(IGenerationContext context)
{
yield break;
}
public bool IsSingletonSafe()
{
return true;
}
}
class SimpleParamImpl : ICRegILGen
{
readonly int _idx;
public SimpleParamImpl(int idx)
{
_idx = idx;
}
public string GenFuncName(IGenerationContext context)
{
throw new InvalidOperationException();
}
public void GenInitialization(IGenerationContext context)
{
}
public bool IsCorruptingILStack(IGenerationContext context)
{
return false;
}
public IILLocal? GenMain(IGenerationContext context)
{
var constants = ((GenerationContext)context)._constants;
context.IL.Ldarg((ushort)(_idx + (constants.Count > 0 ? 1 : 0)));
return null;
}
public IEnumerable<INeed> GetNeeds(IGenerationContext context)
{
yield break;
}
public bool IsSingletonSafe()
{
return true;
}
}
ICRegILGen? ResolveNeedBy(Type clrType, object? key)
{
if (_parameterInfos != null)
{
foreach (var parameterInfo in _parameterInfos)
{
if (clrType == parameterInfo.ParameterType && (key as string == parameterInfo.Name || key == null))
{
return new SimpleParamImpl(parameterInfo.Position);
}
}
}
return _buildContext!.ResolveNeedBy(clrType, key);
}
public object GenerateFunc(Type funcType)
{
GatherNeeds(_registration,
new HashSet<Tuple<IBuildContext, ICRegILGen>>(ComparerProcessingContext.Instance));
if (_constants.Count == 0)
{
var method = ILBuilder.Instance.NewMethod(_registration.GenFuncName(this), funcType);
IL = method.Generator;
GenerateBody();
return method.Create();
}
if (_constants.Count == 1)
{
var method =
ILBuilder.Instance.NewMethod(_registration.GenFuncName(this), funcType, _constants[0].Item2);
IL = method.Generator;
GenerateBody();
return method.Create(_constants[0].Item1);
}
else
{
var method = ILBuilder.Instance.NewMethod(_registration.GenFuncName(this), funcType, typeof(object[]));
IL = method.Generator;
GenerateBody();
return method.Create(_constants.Select(t => t.Item1).ToArray());
}
}
void GenerateBody()
{
_registration.GenInitialization(this);
var local = _registration.GenMain(this);
if (local != null)
{
IL!.Ldloc(local);
}
IL!.Ret();
}
public void VerifySingletonUsingOnlySingletons(Type singletonType)
{
GatherNeeds(_registration,
new HashSet<Tuple<IBuildContext, ICRegILGen>>(ComparerProcessingContext.Instance));
foreach (var need in _registration.GetNeeds(this))
{
if (need.Kind == NeedKind.CReg)
{
continue;
}
var k = new Tuple<IBuildContext, INeed>(_buildContext, need);
if (!_resolvers[k].IsSingletonSafe())
{
throw new BTDBException("Singleton " + singletonType.ToSimpleName() + " dependency " +
need.ClrType.ToSimpleName() + " is not singleton");
}
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
namespace SimpleErrorHandler
{
/// <summary>
/// An <see cref="ErrorLog"/> implementation that uses XML files stored on disk as its backing store.
/// </summary>
public class XmlErrorLog : ErrorLog
{
private string _logPath;
private int _maxFiles = 200;
/// <summary>
/// When set in config, any new exceptions will be compared to existing exceptions within this time window. If new exceptions match, they will be discarded.
/// Useful for when a deluge of errors comes down upon your head.
/// </summary>
private TimeSpan? _ignoreSimilarExceptionsThreshold;
public string LogPath
{
get { return _logPath; }
set
{
if (value.StartsWith(@"~\"))
{
_logPath = AppDomain.CurrentDomain.GetData("APPBASE").ToString() + value.Substring(2);
}
else
{
_logPath = value;
}
}
}
public override bool DeleteError(string id)
{
FileInfo f;
if (!TryGetErrorFile(id, out f))
return false;
// remove the read-only before deletion
if (f.IsReadOnly)
f.Attributes ^= FileAttributes.ReadOnly;
f.Delete();
return true;
}
public override bool ProtectError(string id)
{
FileInfo f;
if (!TryGetErrorFile(id, out f))
return false;
f.Attributes |= FileAttributes.ReadOnly;
return true;
}
/// <summary>
/// Initializes a new instance of the <see cref="ErrorLog"/> class
/// using a dictionary of configured settings.
/// </summary>
public XmlErrorLog(IDictionary config)
{
if (config["LogPath"] != null)
{
LogPath = (string)config["LogPath"];
}
else
{
throw new Exception("Log Path is missing for the XML error log.");
}
if (config["MaxFiles"] != null)
{
_maxFiles = Convert.ToInt32(config["MaxFiles"]);
}
if (config["IgnoreSimilarExceptionsThreshold"] != null)
{
// the config file value will be a positive time span, but we'll be subtracting this value from "Now" - negate it
_ignoreSimilarExceptionsThreshold = TimeSpan.Parse(config["IgnoreSimilarExceptionsThreshold"].ToString()).Negate();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ErrorLog"/> class to use a specific path to store/load XML files.
/// </summary>
public XmlErrorLog(string logPath)
{
LogPath = logPath;
}
/// <summary>
/// Gets the name of this error log implementation.
/// </summary>
public override string Name
{
get { return "Xml File Error Log"; }
}
/// <summary>
/// Logs an error to the database.
/// </summary>
/// <remarks>
/// Logs an error as a single XML file stored in a folder. XML files are named with a
/// sortable date and a unique identifier. Currently the XML files are stored indefinately.
/// As they are stored as files, they may be managed using standard scheduled jobs.
/// </remarks>
public override void Log(Error error)
{
// will allow fast comparisons of messages to see if we can ignore an incoming exception
string messageHash = error.Detail;
messageHash = messageHash.HasValue() ? messageHash.GetHashCode().ToString() : "no-stack-trace";
Error original;
// before we persist 'error', see if there are any existing errors that it could be a duplicate of
if (_ignoreSimilarExceptionsThreshold.HasValue && TryFindOriginalError(error, messageHash, out original))
{
// just update the existing file after incrementing its "duplicate count"
original.DuplicateCount = original.DuplicateCount.GetValueOrDefault(0) + 1;
UpdateError(original);
}
else
{
LogNewError(error, messageHash);
}
}
private void UpdateError(Error error)
{
FileInfo f;
if (!TryGetErrorFile(error.Id, out f))
throw new ArgumentOutOfRangeException("Unable to find a file for error with Id = " + error.Id);
using (var stream = f.OpenWrite())
using (var writer = new StreamWriter(stream))
{
LogError(error, writer);
}
}
private void LogNewError(Error error, string messageHash)
{
error.Id = FriendlyGuid(Guid.NewGuid());
string timeStamp = DateTime.Now.ToString("u").Replace(":", "").Replace(" ", "");
string fileName = string.Format(@"{0}\error-{1}-{2}-{3}.xml", _logPath, timeStamp, messageHash, error.Id);
FileInfo outfile = new FileInfo(fileName);
using (StreamWriter outstream = outfile.CreateText())
{
LogError(error, outstream);
}
// we added a new file, so clean up old smack over our max errors limit
RemoveOldErrors();
}
private void LogError(Error error, StreamWriter outstream)
{
using (XmlTextWriter w = new XmlTextWriter(outstream))
{
w.Formatting = Formatting.Indented;
w.WriteStartElement("error");
error.ToXml(w);
w.WriteEndElement();
w.Flush();
}
}
/// <summary>
/// Answers the older exception that 'possibleDuplicate' matches, returning null if no match is found.
/// </summary>
private bool TryFindOriginalError(SimpleErrorHandler.Error possibleDuplicate, string messageHash, out SimpleErrorHandler.Error original)
{
string[] files = Directory.GetFiles(LogPath);
if (files.Length > 0)
{
var earliestDate = DateTime.Now.Add(_ignoreSimilarExceptionsThreshold.Value);
// order by newest
Array.Sort(files);
Array.Reverse(files);
foreach (var filename in files)
{
if (File.GetCreationTime(filename) >= earliestDate)
{
var match = Regex.Match(filename, @"error[-\d]+Z-(?<hashCode>((?<!\d)-|\d)+)-(?<id>.+)\.xml", RegexOptions.IgnoreCase);
if (match.Success)
{
var existingHash = match.Groups["hashCode"].Value;
if (messageHash.Equals(existingHash))
{
original = GetError(match.Groups["id"].Value).Error;
return true;
}
}
}
else
break; // no other files are newer, no use checking
}
}
original = null;
return false;
}
private string FriendlyGuid(Guid g)
{
string s = Convert.ToBase64String(g.ToByteArray());
return s
.Replace("/", "")
.Replace("+", "")
.Replace("=", "");
}
private void RemoveOldErrors()
{
string[] fileList = Directory.GetFiles(LogPath, "error*.*");
// we'll start deleting once we're over the max
if (fileList.Length <= _maxFiles) return;
// file name contains timestamp - sort by creation date, ascending
Array.Sort(fileList);
// we'll remove any errors with index less than this upper bound
int upperBound = fileList.Length - _maxFiles;
for (int i = 0; i < upperBound && i < fileList.Length; i++)
{
var file = new FileInfo(fileList[i]);
// have we protected this error from deletion?
if ((file.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// we'll skip this error file and raise our search bounds up one
upperBound++;
}
else
{
file.Delete();
}
}
}
/// <summary>
/// Returns a page of errors from the folder in descending order of logged time as defined by the sortable filenames.
/// </summary>
public override int GetErrors(int pageIndex, int pageSize, IList errorEntryList)
{
if (pageIndex < 0) pageIndex = 0;
if (pageSize < 0) pageSize = 25;
string[] fileList = Directory.GetFiles(LogPath, "*.xml");
if (fileList.Length < 1) return 0;
Array.Sort(fileList);
Array.Reverse(fileList);
int currentItem = pageIndex * pageSize;
int lastItem = (currentItem + pageSize < fileList.Length) ? currentItem + pageSize : fileList.Length;
for (int i = currentItem; i < lastItem; i++)
{
FileInfo f = new FileInfo(fileList[i]);
FileStream s = f.OpenRead();
XmlTextReader r = new XmlTextReader(s);
try
{
while (r.IsStartElement("error"))
{
SimpleErrorHandler.Error error = new SimpleErrorHandler.Error();
error.FromXml(r);
error.IsProtected = f.IsReadOnly; // have we "protected" this file from deletion?
errorEntryList.Add(new ErrorLogEntry(this, error.Id, error));
}
}
finally
{
r.Close();
}
}
return fileList.Length;
}
/// <summary>
/// Returns the specified error from the filesystem, or throws an exception if it does not exist.
/// </summary>
public override ErrorLogEntry GetError(string id)
{
string[] fileList = Directory.GetFiles(LogPath, string.Format("*{0}.xml", id));
if (fileList.Length < 1)
throw new Exception(string.Format("Can't locate error file for errorId {0}", id));
FileInfo f = new FileInfo(fileList[0]);
FileStream s = f.OpenRead();
XmlTextReader r = new XmlTextReader(s);
SimpleErrorHandler.Error error = new SimpleErrorHandler.Error();
error.FromXml(r);
r.Close();
return new ErrorLogEntry(this, id, error);
}
private bool TryGetErrorFile(string id, out FileInfo file)
{
string[] fileList = Directory.GetFiles(LogPath, string.Format("*{0}.xml", id));
if (fileList.Length != 1)
{
file = null;
return false;
}
file = new FileInfo(fileList[0]);
return true;
}
}
}
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.14.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Google Cloud Speech API Version v1beta1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://cloud.google.com/speech/'>Google Cloud Speech API</a>
* <tr><th>API Version<td>v1beta1
* <tr><th>API Rev<td>20160726 (572)
* <tr><th>API Docs
* <td><a href='https://cloud.google.com/speech/'>
* https://cloud.google.com/speech/</a>
* <tr><th>Discovery Name<td>speech
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Google Cloud Speech API can be found at
* <a href='https://cloud.google.com/speech/'>https://cloud.google.com/speech/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.CloudSpeechAPI.v1beta1
{
/// <summary>The CloudSpeechAPI Service.</summary>
public class CloudSpeechAPIService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1beta1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public CloudSpeechAPIService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public CloudSpeechAPIService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
operations = new OperationsResource(this);
speech = new SpeechResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "speech"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://speech.googleapis.com/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return ""; }
}
/// <summary>Available OAuth 2.0 scopes for use with the Google Cloud Speech API.</summary>
public class Scope
{
/// <summary>View and manage your data across Google Cloud Platform services</summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
private readonly OperationsResource operations;
/// <summary>Gets the Operations resource.</summary>
public virtual OperationsResource Operations
{
get { return operations; }
}
private readonly SpeechResource speech;
/// <summary>Gets the Speech resource.</summary>
public virtual SpeechResource Speech
{
get { return speech; }
}
}
///<summary>A base abstract class for CloudSpeechAPI requests.</summary>
public abstract class CloudSpeechAPIBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new CloudSpeechAPIBaseServiceRequest instance.</summary>
protected CloudSpeechAPIBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto,
}
/// <summary>OAuth bearer token.</summary>
[Google.Apis.Util.RequestParameterAttribute("bearer_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string BearerToken { get; set; }
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Pretty-print response.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("pp", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> Pp { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes CloudSpeechAPI parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"bearer_token", new Google.Apis.Discovery.Parameter
{
Name = "bearer_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pp", new Google.Apis.Discovery.Parameter
{
Name = "pp",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "operations" collection of methods.</summary>
public class OperationsResource
{
private const string Resource = "operations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public OperationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Starts asynchronous cancellation on a long-running operation. The server makes a best effort to
/// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns
/// `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether
/// the cancellation succeeded or whether the operation completed despite cancellation.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">The name of the operation resource to be cancelled.</param>
public virtual CancelRequest Cancel(Google.Apis.CloudSpeechAPI.v1beta1.Data.CancelOperationRequest body, string name)
{
return new CancelRequest(service, body, name);
}
/// <summary>Starts asynchronous cancellation on a long-running operation. The server makes a best effort to
/// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns
/// `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether
/// the cancellation succeeded or whether the operation completed despite cancellation.</summary>
public class CancelRequest : CloudSpeechAPIBaseServiceRequest<Google.Apis.CloudSpeechAPI.v1beta1.Data.Empty>
{
/// <summary>Constructs a new Cancel request.</summary>
public CancelRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudSpeechAPI.v1beta1.Data.CancelOperationRequest body, string name)
: base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>The name of the operation resource to be cancelled.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudSpeechAPI.v1beta1.Data.CancelOperationRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "cancel"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1beta1/operations/{+name}:cancel"; }
}
/// <summary>Initializes Cancel parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^[^/]*$",
});
}
}
/// <summary>Deletes a long-running operation. This method indicates that the client is no longer interested in
/// the operation result. It does not cancel the operation. If the server doesn't support this method, it
/// returns `google.rpc.Code.UNIMPLEMENTED`.</summary>
/// <param name="name">The name of the operation resource to be deleted.</param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes a long-running operation. This method indicates that the client is no longer interested in
/// the operation result. It does not cancel the operation. If the server doesn't support this method, it
/// returns `google.rpc.Code.UNIMPLEMENTED`.</summary>
public class DeleteRequest : CloudSpeechAPIBaseServiceRequest<Google.Apis.CloudSpeechAPI.v1beta1.Data.Empty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation resource to be deleted.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "delete"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "DELETE"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1beta1/operations/{+name}"; }
}
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^[^/]*$",
});
}
}
/// <summary>Gets the latest state of a long-running operation. Clients can use this method to poll the
/// operation result at intervals as recommended by the API service.</summary>
/// <param name="name">The name of the operation resource.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets the latest state of a long-running operation. Clients can use this method to poll the
/// operation result at intervals as recommended by the API service.</summary>
public class GetRequest : CloudSpeechAPIBaseServiceRequest<Google.Apis.CloudSpeechAPI.v1beta1.Data.Operation>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation resource.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1beta1/operations/{+name}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^[^/]*$",
});
}
}
/// <summary>Lists operations that match the specified filter in the request. If the server doesn't support this
/// method, it returns `UNIMPLEMENTED`.
///
/// NOTE: the `name` binding below allows API services to override the binding to use different resource name
/// schemes, such as `users/operations`.</summary>
public virtual ListRequest List()
{
return new ListRequest(service);
}
/// <summary>Lists operations that match the specified filter in the request. If the server doesn't support this
/// method, it returns `UNIMPLEMENTED`.
///
/// NOTE: the `name` binding below allows API services to override the binding to use different resource name
/// schemes, such as `users/operations`.</summary>
public class ListRequest : CloudSpeechAPIBaseServiceRequest<Google.Apis.CloudSpeechAPI.v1beta1.Data.ListOperationsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
/// <summary>The standard list page size.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>The standard list filter.</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>The name of the operation collection.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Name { get; set; }
/// <summary>The standard list page token.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1beta1/operations"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>The "speech" collection of methods.</summary>
public class SpeechResource
{
private const string Resource = "speech";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public SpeechResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Perform asynchronous speech-recognition: receive results via the google.longrunning.Operations
/// interface. Returns either an `Operation.error` or an `Operation.response` which contains an
/// `AsyncRecognizeResponse` message.</summary>
/// <param name="body">The body of the request.</param>
public virtual AsyncrecognizeRequest Asyncrecognize(Google.Apis.CloudSpeechAPI.v1beta1.Data.AsyncRecognizeRequest body)
{
return new AsyncrecognizeRequest(service, body);
}
/// <summary>Perform asynchronous speech-recognition: receive results via the google.longrunning.Operations
/// interface. Returns either an `Operation.error` or an `Operation.response` which contains an
/// `AsyncRecognizeResponse` message.</summary>
public class AsyncrecognizeRequest : CloudSpeechAPIBaseServiceRequest<Google.Apis.CloudSpeechAPI.v1beta1.Data.Operation>
{
/// <summary>Constructs a new Asyncrecognize request.</summary>
public AsyncrecognizeRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudSpeechAPI.v1beta1.Data.AsyncRecognizeRequest body)
: base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudSpeechAPI.v1beta1.Data.AsyncRecognizeRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "asyncrecognize"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1beta1/speech:asyncrecognize"; }
}
/// <summary>Initializes Asyncrecognize parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
/// <summary>Perform synchronous speech-recognition: receive results after all audio has been sent and
/// processed.</summary>
/// <param name="body">The body of the request.</param>
public virtual SyncrecognizeRequest Syncrecognize(Google.Apis.CloudSpeechAPI.v1beta1.Data.SyncRecognizeRequest body)
{
return new SyncrecognizeRequest(service, body);
}
/// <summary>Perform synchronous speech-recognition: receive results after all audio has been sent and
/// processed.</summary>
public class SyncrecognizeRequest : CloudSpeechAPIBaseServiceRequest<Google.Apis.CloudSpeechAPI.v1beta1.Data.SyncRecognizeResponse>
{
/// <summary>Constructs a new Syncrecognize request.</summary>
public SyncrecognizeRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudSpeechAPI.v1beta1.Data.SyncRecognizeRequest body)
: base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudSpeechAPI.v1beta1.Data.SyncRecognizeRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "syncrecognize"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1beta1/speech:syncrecognize"; }
}
/// <summary>Initializes Syncrecognize parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
}
}
namespace Google.Apis.CloudSpeechAPI.v1beta1.Data
{
/// <summary>`AsyncRecognizeRequest` is the top-level message sent by the client for the `AsyncRecognize`
/// method.</summary>
public class AsyncRecognizeRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>[Required] The audio data to be recognized.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("audio")]
public virtual RecognitionAudio Audio { get; set; }
/// <summary>[Required] The `config` message provides information to the recognizer that specifies how to
/// process the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("config")]
public virtual RecognitionConfig Config { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for Operations.CancelOperation.</summary>
public class CancelOperationRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A
/// typical example is to use it as the request or the response type of an API method. For instance:
///
/// service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); }
///
/// The JSON representation for `Empty` is empty JSON object `{}`.</summary>
public class Empty : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for Operations.ListOperations.</summary>
public class ListOperationsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The standard List next-page token.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>A list of operations that matches the specified filter in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("operations")]
public virtual System.Collections.Generic.IList<Operation> Operations { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>This resource represents a long-running operation that is the result of a network API call.</summary>
public class Operation : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>If the value is `false`, it means the operation is still in progress. If true, the operation is
/// completed, and either `error` or `response` is available.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("done")]
public virtual System.Nullable<bool> Done { get; set; }
/// <summary>The error result of the operation in case of failure.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("error")]
public virtual Status Error { get; set; }
/// <summary>Service-specific metadata associated with the operation. It typically contains progress
/// information and common metadata such as create time. Some services might not provide such metadata. Any
/// method that returns a long-running operation should document the metadata type, if any.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual System.Collections.Generic.IDictionary<string,object> Metadata { get; set; }
/// <summary>The server-assigned name, which is only unique within the same service that originally returns it.
/// If you use the default HTTP mapping, the `name` should have the format of
/// `operations/some/unique/name`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The normal response of the operation in case of success. If the original method returns no data on
/// success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard
/// `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have
/// the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name
/// is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("response")]
public virtual System.Collections.Generic.IDictionary<string,object> Response { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Contains audio data in the encoding specified in the `RecognitionConfig`. Either `content` or `uri`
/// must be supplied. Supplying both or neither returns google.rpc.Code.INVALID_ARGUMENT.</summary>
public class RecognitionAudio : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The audio data bytes encoded as specified in `RecognitionConfig`. Note: as with all bytes fields,
/// protobuffers use a pure binary representation, whereas JSON representations use base64.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("content")]
public virtual string Content { get; set; }
/// <summary>URI that points to a file that contains audio data bytes as specified in `RecognitionConfig`.
/// Currently, only Google Cloud Storage URIs are supported, which must be specified in the following format:
/// `gs://bucket_name/object_name` (other URI formats return google.rpc.Code.INVALID_ARGUMENT). For more
/// information, see [Request URIs](/storage/docs/reference-uris).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("uri")]
public virtual string Uri { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The `RecognitionConfig` message provides information to the recognizer that specifies how to process
/// the request.</summary>
public class RecognitionConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>[Required] Encoding of audio data sent in all `RecognitionAudio` messages.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("encoding")]
public virtual string Encoding { get; set; }
/// <summary>[Optional] The language of the supplied audio as a BCP-47 language tag. Example: "en-GB"
/// https://www.rfc-editor.org/rfc/bcp/bcp47.txt If omitted, defaults to "en-US". See [Language
/// Support](/speech/docs/best-practices#language_support) for a list of the currently supported language
/// codes.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("languageCode")]
public virtual string LanguageCode { get; set; }
/// <summary>[Optional] Maximum number of recognition hypotheses to be returned. Specifically, the maximum
/// number of `SpeechRecognitionAlternative` messages within each `SpeechRecognitionResult`. The server may
/// return fewer than `max_alternatives`. Valid values are `0`-`30`. A value of `0` or `1` will return a maximum
/// of `1`. If omitted, defaults to `1`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("maxAlternatives")]
public virtual System.Nullable<int> MaxAlternatives { get; set; }
/// <summary>[Optional] If set to `true`, the server will attempt to filter out profanities, replacing all but
/// the initial character in each filtered word with asterisks, e.g. "f***". If set to `false` or omitted,
/// profanities won't be filtered out.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("profanityFilter")]
public virtual System.Nullable<bool> ProfanityFilter { get; set; }
/// <summary>[Required] Sample rate in Hertz of the audio data sent in all `RecognitionAudio` messages. Valid
/// values are: 8000-48000. 16000 is optimal. For best results, set the sampling rate of the audio source to
/// 16000 Hz. If that's not possible, use the native sample rate of the audio source (instead of re-
/// sampling).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sampleRate")]
public virtual System.Nullable<int> SampleRate { get; set; }
/// <summary>[Optional] A means to provide context to assist the speech recognition.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("speechContext")]
public virtual SpeechContext SpeechContext { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Provides "hints" to the speech recognizer to favor specific words and phrases in the results.</summary>
public class SpeechContext : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>[Optional] A list of up to 50 phrases of up to 100 characters each to provide words and phrases
/// "hints" to the speech recognition so that it is more likely to recognize them.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("phrases")]
public virtual System.Collections.Generic.IList<string> Phrases { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Alternative hypotheses (a.k.a. n-best list).</summary>
public class SpeechRecognitionAlternative : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>[Output-only] The confidence estimate between 0.0 and 1.0. A higher number means the system is more
/// confident that the recognition is correct. This field is typically provided only for the top hypothesis, and
/// only for `is_final=true` results. The default of 0.0 is a sentinel value indicating confidence was not
/// set.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("confidence")]
public virtual System.Nullable<float> Confidence { get; set; }
/// <summary>[Output-only] Transcript text representing the words that the user spoke.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("transcript")]
public virtual string Transcript { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A speech recognition result corresponding to a portion of the audio.</summary>
public class SpeechRecognitionResult : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>[Output-only] May contain one or more recognition hypotheses (up to the maximum specified in
/// `max_alternatives`).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("alternatives")]
public virtual System.Collections.Generic.IList<SpeechRecognitionAlternative> Alternatives { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The `Status` type defines a logical error model that is suitable for different programming
/// environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). The error model
/// is designed to be:
///
/// - Simple to use and understand for most users - Flexible enough to meet unexpected needs
///
/// # Overview
///
/// The `Status` message contains three pieces of data: error code, error message, and error details. The error code
/// should be an enum value of google.rpc.Code, but it may accept additional error codes if needed. The error
/// message should be a developer-facing English message that helps developers *understand* and *resolve* the error.
/// If a localized user-facing error message is needed, put the localized message in the error details or localize
/// it in the client. The optional error details may contain arbitrary information about the error. There is a
/// predefined set of error detail types in the package `google.rpc` which can be used for common error conditions.
///
/// # Language mapping
///
/// The `Status` message is the logical representation of the error model, but it is not necessarily the actual wire
/// format. When the `Status` message is exposed in different client libraries and different wire protocols, it can
/// be mapped differently. For example, it will likely be mapped to some exceptions in Java, but more likely mapped
/// to some error codes in C.
///
/// # Other uses
///
/// The error model and the `Status` message can be used in a variety of environments, either with or without APIs,
/// to provide a consistent developer experience across different environments.
///
/// Example uses of this error model include:
///
/// - Partial errors. If a service needs to return partial errors to the client, it may embed the `Status` in the
/// normal response to indicate the partial errors.
///
/// - Workflow errors. A typical workflow has multiple steps. Each step may have a `Status` message for error
/// reporting purpose.
///
/// - Batch operations. If a client uses batch request and batch response, the `Status` message should be used
/// directly inside batch response, one for each error sub-response.
///
/// - Asynchronous operations. If an API call embeds asynchronous operation results in its response, the status of
/// those operations should be represented directly using the `Status` message.
///
/// - Logging. If some API errors are stored in logs, the message `Status` could be used directly after any
/// stripping needed for security/privacy reasons.</summary>
public class Status : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The status code, which should be an enum value of google.rpc.Code.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual System.Nullable<int> Code { get; set; }
/// <summary>A list of messages that carry the error details. There will be a common set of message types for
/// APIs to use.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("details")]
public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string,object>> Details { get; set; }
/// <summary>A developer-facing error message, which should be in English. Any user-facing error message should
/// be localized and sent in the google.rpc.Status.details field, or localized by the client.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("message")]
public virtual string Message { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>`SyncRecognizeRequest` is the top-level message sent by the client for the `SyncRecognize`
/// method.</summary>
public class SyncRecognizeRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>[Required] The audio data to be recognized.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("audio")]
public virtual RecognitionAudio Audio { get; set; }
/// <summary>[Required] The `config` message provides information to the recognizer that specifies how to
/// process the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("config")]
public virtual RecognitionConfig Config { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>`SyncRecognizeResponse` is the only message returned to the client by `SyncRecognize`. It contains the
/// result as zero or more sequential `SpeechRecognitionResult` messages.</summary>
public class SyncRecognizeResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>[Output-only] Sequential list of transcription results corresponding to sequential portions of
/// audio.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("results")]
public virtual System.Collections.Generic.IList<SpeechRecognitionResult> Results { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="CslaDesignerDataSourceView.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>Object responsible for providing details about</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.Web.UI.Design;
using System.ComponentModel.Design;
using System.Data;
using System.ComponentModel;
namespace Csla.Web.Design
{
/// <summary>
/// Object responsible for providing details about
/// data binding to a specific CSLA .NET object.
/// </summary>
public class CslaDesignerDataSourceView : DesignerDataSourceView
{
private CslaDataSourceDesigner _owner = null;
/// <summary>
/// Creates an instance of the object.
/// </summary>
public CslaDesignerDataSourceView(CslaDataSourceDesigner owner, string viewName)
: base(owner, viewName)
{
_owner = owner;
}
/// <summary>
/// Returns a set of sample data used to populate
/// controls at design time.
/// </summary>
/// <param name="minimumRows">Minimum number of sample rows
/// to create.</param>
/// <param name="isSampleData">Returns True if the data
/// is sample data.</param>
public override IEnumerable GetDesignTimeData(int minimumRows, out bool isSampleData)
{
IDataSourceViewSchema schema = this.Schema;
DataTable result = new DataTable();
// create the columns
foreach (IDataSourceFieldSchema item in schema.GetFields())
{
result.Columns.Add(item.Name, item.DataType);
}
// create sample data
for (int index = 1; index <= minimumRows; index++)
{
object[] values = new object[result.Columns.Count];
int colIndex = 0;
foreach (DataColumn col in result.Columns)
{
if (col.DataType.Equals(typeof(string)))
values[colIndex] = "abc";
else if (col.DataType.Equals(typeof(System.DateTime)))
values[colIndex] = System.DateTime.Today.ToShortDateString();
else if (col.DataType.Equals(typeof(System.DateTimeOffset)))
values[colIndex] = System.DateTime.Today.ToShortDateString();
else if (col.DataType.Equals(typeof(bool)))
values[colIndex] = false;
else if (col.DataType.IsPrimitive)
values[colIndex] = index;
else if (col.DataType.Equals(typeof(Guid)))
values[colIndex] = Guid.Empty;
else if (col.DataType.IsValueType)
values[colIndex] = Activator.CreateInstance(col.DataType);
else
values[colIndex] = null;
colIndex += 1;
}
result.LoadDataRow(values, LoadOption.OverwriteChanges);
}
isSampleData = true;
return (IEnumerable)result.DefaultView;
}
/// <summary>
/// Returns schema information corresponding to the properties
/// of the CSLA .NET business object.
/// </summary>
/// <remarks>
/// All public properties are returned except for those marked
/// with the <see cref="BrowsableAttribute">Browsable attribute</see>
/// as False.
/// </remarks>
public override IDataSourceViewSchema Schema
{
get
{
return new ObjectSchema(
_owner,
_owner.DataSourceControl.TypeName).GetViews()[0];
}
}
/// <summary>
/// Get a value indicating whether data binding can retrieve
/// the total number of rows of data.
/// </summary>
public override bool CanRetrieveTotalRowCount
{
get
{
return true;
}
}
private Type GetObjectType()
{
Type result;
try
{
ITypeResolutionService typeService = null;
typeService = (ITypeResolutionService)(_owner.Site.GetService(typeof(ITypeResolutionService)));
result = typeService.GetType(this._owner.DataSourceControl.TypeName, true, false);
}
catch
{
result = typeof(object);
}
return result;
}
/// <summary>
/// Get a value indicating whether data binding can directly
/// delete the object.
/// </summary>
/// <remarks>
/// If this returns true, the web page must handle the
/// <see cref="CslaDataSource.DeleteObject">DeleteObject</see>
/// event.
/// </remarks>
public override bool CanDelete
{
get
{
Type objectType = GetObjectType();
if (typeof(Csla.Core.IUndoableObject).IsAssignableFrom(objectType))
{
return true;
}
else if (objectType.GetMethod("Remove") != null)
{
return true;
}
else
{
return false;
}
}
}
/// <summary>
/// Get a value indicating whether data binding can directly
/// insert an instance of the object.
/// </summary>
/// <remarks>
/// If this returns true, the web page must handle the
/// <see cref="CslaDataSource.InsertObject">InsertObject</see>
/// event.
/// </remarks>
public override bool CanInsert
{
get
{
Type objectType = GetObjectType();
if (typeof(Csla.Core.IUndoableObject).IsAssignableFrom(objectType))
{
return true;
}
else
{
return false;
}
}
}
/// <summary>
/// Get a value indicating whether data binding can directly
/// update or edit the object.
/// </summary>
/// <remarks>
/// If this returns true, the web page must handle the
/// <see cref="CslaDataSource.UpdateObject">UpdateObject</see>
/// event.
/// </remarks>
public override bool CanUpdate
{
get
{
Type objectType = GetObjectType();
if (typeof(Csla.Core.IUndoableObject).IsAssignableFrom(objectType))
{
return true;
}
else
{
return false;
}
}
}
/// <summary>
/// Gets a value indicating whether the data source supports
/// paging.
/// </summary>
public override bool CanPage
{
get
{
return _owner.DataSourceControl.TypeSupportsPaging;
}
}
/// <summary>
/// Gets a value indicating whether the data source supports
/// sorting.
/// </summary>
public override bool CanSort
{
get
{
return _owner.DataSourceControl.TypeSupportsSorting;
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Automation;
using Microsoft.PythonTools;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Project;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudioTools;
using TestUtilities;
using TestUtilities.Python;
using TestUtilities.UI;
using TestUtilities.UI.Python;
namespace PythonToolsUITests {
[TestClass]
public class BuildTasksUI27Tests {
static BuildTasksUI27Tests() {
AssertListener.Initialize();
PythonTestData.Deploy();
}
internal virtual PythonVersion PythonVersion {
get {
return PythonPaths.Python27 ?? PythonPaths.Python27_x64;
}
}
internal void Execute(PythonProjectNode projectNode, string commandName) {
Console.WriteLine("Executing command {0}", commandName);
var t = projectNode.Site.GetUIThread().InvokeTask(() => projectNode._customCommands.First(cc => cc.DisplayLabel == commandName).ExecuteAsync(projectNode));
t.GetAwaiter().GetResult();
}
internal Task ExecuteAsync(PythonProjectNode projectNode, string commandName) {
Console.WriteLine("Executing command {0} asynchronously", commandName);
return projectNode.Site.GetUIThread().InvokeTask(() => projectNode._customCommands.First(cc => cc.DisplayLabel == commandName).ExecuteAsync(projectNode));
}
internal void OpenProject(VisualStudioApp app, string slnName, out PythonProjectNode projectNode, out EnvDTE.Project dteProject) {
PythonVersion.AssertInstalled();
dteProject = app.OpenProject("TestData\\Targets\\" + slnName);
projectNode = dteProject.GetPythonProject();
var fact = projectNode.InterpreterFactories.Where(x => x.Configuration.Id == PythonVersion.Id).FirstOrDefault();
Assert.IsNotNull(fact, "Project does not contain expected interpreter");
projectNode.ActiveInterpreter = fact;
dteProject.Save();
}
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void CustomCommandsAdded() {
using (var app = new VisualStudioApp()) {
PythonProjectNode node;
EnvDTE.Project proj;
OpenProject(app, "Commands1.sln", out node, out proj);
AssertUtil.ContainsExactly(
node._customCommands.Select(cc => cc.DisplayLabel),
"Test Command 1",
"Test Command 2"
);
app.OpenSolutionExplorer().FindItem("Solution 'Commands1' (1 project)", "Commands1").Select();
var menuBar = app.FindByAutomationId("MenuBar").AsWrapper();
Assert.IsNotNull(menuBar, "Unable to find menu bar");
var projectMenu = menuBar.FindByName("Project").AsWrapper();
Assert.IsNotNull(projectMenu, "Unable to find Project menu");
projectMenu.Element.EnsureExpanded();
try {
foreach (var name in node._customCommands.Select(cc => cc.DisplayLabelWithoutAccessKeys)) {
Assert.IsNotNull(projectMenu.FindByName(name), name + " not found");
}
} finally {
try {
// Try really really hard to collapse and deselect the
// Project menu, since VS will keep it selected and it
// may not come back for some reason...
projectMenu.Element.Collapse();
Keyboard.PressAndRelease(System.Windows.Input.Key.Escape);
Keyboard.PressAndRelease(System.Windows.Input.Key.Escape);
} catch {
// ...but don't try so hard that we fail if we can't
// simulate keypresses.
}
}
}
}
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void CustomCommandsWithResourceLabel() {
using (var app = new VisualStudioApp()) {
PythonProjectNode node;
EnvDTE.Project proj;
OpenProject(app, "Commands2.sln", out node, out proj);
AssertUtil.ContainsExactly(
node._customCommands.Select(cc => cc.Label),
"resource:PythonToolsUITests;PythonToolsUITests.Resources;CommandName"
);
AssertUtil.ContainsExactly(
node._customCommands.Select(cc => cc.DisplayLabel),
"Command from Resource"
);
}
}
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void CustomCommandsReplWithResourceLabel() {
using (var app = new PythonVisualStudioApp()) {
PythonProjectNode node;
EnvDTE.Project proj;
OpenProject(app, "Commands2.sln", out node, out proj);
Execute(node, "Command from Resource");
using (var repl = app.GetInteractiveWindow("Repl from Resource")) {
Assert.IsNotNull(repl, "Could not find repl window");
repl.WaitForTextEnd(
"Program.py completed",
">"
);
}
using (var repl = app.GetInteractiveWindow("resource:PythonToolsUITests;PythonToolsUITests.Resources;ReplName")) {
Assert.IsNull(repl);
}
}
}
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void CustomCommandsRunInRepl() {
using (var app = new PythonVisualStudioApp()) {
PythonProjectNode node;
EnvDTE.Project proj;
OpenProject(app, "Commands1.sln", out node, out proj);
Execute(node, "Test Command 2");
using (var repl = app.GetInteractiveWindow("Test Repl")) {
Assert.IsNotNull(repl, "Could not find repl window");
repl.WaitForTextEnd(
"Program.py completed",
">"
);
}
app.Dte.Solution.Close();
using (var repl = app.GetInteractiveWindow("Test Repl")) {
Assert.IsNull(repl, "Repl window was not closed");
}
}
}
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void CustomCommandsRunProcessInRepl() {
using (var app = new PythonVisualStudioApp()) {
PythonProjectNode node;
EnvDTE.Project proj;
OpenProject(app, "Commands3.sln", out node, out proj);
Execute(node, "Write to Repl");
using (var repl = app.GetInteractiveWindow("Test Repl")) {
Assert.IsNotNull(repl, "Could not find repl window");
repl.WaitForTextEnd(
string.Format("({0}, {1})", PythonVersion.Configuration.Version.Major, PythonVersion.Configuration.Version.Minor),
">"
);
}
}
}
private static void ExpectOutputWindowText(VisualStudioApp app, string expected) {
var outputWindow = app.Element.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(AutomationElement.ClassNameProperty, "GenericPane"),
new PropertyCondition(AutomationElement.NameProperty, "Output")
)
);
Assert.IsNotNull(outputWindow, "Output Window was not opened");
var outputText = "";
for (int retries = 100; !outputText.Contains(expected) && retries > 0; --retries) {
Thread.Sleep(100);
outputText = outputWindow.FindFirst(TreeScope.Descendants,
new PropertyCondition(AutomationElement.ClassNameProperty, "WpfTextView")
).AsWrapper().GetValue();
}
Console.WriteLine("Output Window: " + outputText);
Assert.IsTrue(outputText.Contains(expected), string.Format("Expected to see:\r\n\r\n{0}\r\n\r\nActual content:\r\n\r\n{1}", expected, outputText));
}
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void CustomCommandsRunProcessInOutput() {
using (var app = new PythonVisualStudioApp()) {
PythonProjectNode node;
EnvDTE.Project proj;
OpenProject(app, "Commands3.sln", out node, out proj);
Execute(node, "Write to Output");
var outputWindow = app.Element.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(AutomationElement.ClassNameProperty, "GenericPane"),
new PropertyCondition(AutomationElement.NameProperty, "Output")
)
);
Assert.IsNotNull(outputWindow, "Output Window was not opened");
ExpectOutputWindowText(app, string.Format("({0}, {1})", PythonVersion.Configuration.Version.Major, PythonVersion.Configuration.Version.Minor));
}
}
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void CustomCommandsRunProcessInConsole() {
using (var app = new PythonVisualStudioApp()) {
PythonProjectNode node;
EnvDTE.Project proj;
OpenProject(app, "Commands3.sln", out node, out proj);
var existingProcesses = new HashSet<int>(Process.GetProcessesByName("cmd").Select(p => p.Id));
Execute(node, "Write to Console");
Process newProcess = null;
for (int retries = 100; retries > 0 && newProcess == null; --retries) {
Thread.Sleep(100);
newProcess = Process.GetProcessesByName("cmd").Where(p => !existingProcesses.Contains(p.Id)).FirstOrDefault();
}
Assert.IsNotNull(newProcess, "Process did not start");
try {
Keyboard.PressAndRelease(System.Windows.Input.Key.Space);
newProcess.WaitForExit(1000);
if (newProcess.HasExited) {
newProcess = null;
}
} finally {
if (newProcess != null) {
newProcess.Kill();
}
}
}
}
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void CustomCommandsErrorList() {
using (var app = new PythonVisualStudioApp()) {
PythonProjectNode node;
EnvDTE.Project proj;
OpenProject(app, "ErrorCommand.sln", out node, out proj);
var expectedItems = new[] {
new { Document = "Program.py", Line = 0, Column = 1, Category = __VSERRORCATEGORY.EC_ERROR, Message = "This is an error with a relative path." },
new { Document = Path.Combine(node.ProjectHome, "Program.py"), Line = 2, Column = 3, Category = __VSERRORCATEGORY.EC_WARNING, Message = "This is a warning with an absolute path." },
new { Document = ">>>", Line = 4, Column = -1, Category = __VSERRORCATEGORY.EC_ERROR, Message = "This is an error with an invalid path." },
};
Execute(node, "Produce Errors");
var items = app.WaitForErrorListItems(3);
Console.WriteLine("Got errors:");
foreach (var item in items) {
string document, text;
Assert.AreEqual(0, item.Document(out document), "HRESULT getting document");
Assert.AreEqual(0, item.get_Text(out text), "HRESULT getting message");
Console.WriteLine(" {0}: {1}", document ?? "(null)", text ?? "(null)");
}
Assert.AreEqual(expectedItems.Length, items.Count);
// Second invoke should replace the error items in the list, not add new ones to those already existing.
Execute(node, "Produce Errors");
items = app.WaitForErrorListItems(3);
Assert.AreEqual(expectedItems.Length, items.Count);
items.Sort(Comparer<IVsTaskItem>.Create((x, y) => {
int lx, ly;
x.Line(out lx);
y.Line(out ly);
return lx.CompareTo(ly);
}));
for (int i = 0; i < expectedItems.Length; ++i) {
var item = items[i];
var expectedItem = expectedItems[i];
string document, message;
item.get_Text(out message);
item.Document(out document);
int line, column;
item.Line(out line);
item.Column(out column);
uint category;
((IVsErrorItem)item).GetCategory(out category);
Assert.AreEqual(expectedItem.Document, document);
Assert.AreEqual(expectedItem.Line, line);
Assert.AreEqual(expectedItem.Column, column);
Assert.AreEqual(expectedItem.Message, message);
Assert.AreEqual(expectedItem.Category, (__VSERRORCATEGORY)category);
}
app.ServiceProvider.GetUIThread().Invoke((Action)delegate { items[0].NavigateTo(); });
var doc = app.Dte.ActiveDocument;
Assert.IsNotNull(doc);
Assert.AreEqual("Program.py", doc.Name);
var textDoc = (EnvDTE.TextDocument)doc.Object("TextDocument");
Assert.AreEqual(1, textDoc.Selection.ActivePoint.Line);
Assert.AreEqual(2, textDoc.Selection.ActivePoint.DisplayColumn);
}
}
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void CustomCommandsRequiredPackages() {
using (var app = new PythonVisualStudioApp())
using (var dis = app.SelectDefaultInterpreter(PythonVersion, "virtualenv")) {
PythonProjectNode node;
EnvDTE.Project proj;
OpenProject(app, "CommandRequirePackages.sln", out node, out proj);
string envName;
var env = app.CreateVirtualEnvironment(proj, out envName);
env.Select();
app.Dte.ExecuteCommand("Python.ActivateEnvironment");
// Ensure that no error dialog appears
app.WaitForNoDialog(TimeSpan.FromSeconds(5.0));
// First, execute the command and cancel it.
var task = ExecuteAsync(node, "Require Packages");
try {
var dialogHandle = app.WaitForDialog(task);
if (dialogHandle == IntPtr.Zero) {
if (task.IsFaulted && task.Exception != null) {
Assert.Fail("Unexpected exception in package install confirmation dialog:\n{0}", task.Exception);
} else {
Assert.AreNotEqual(IntPtr.Zero, dialogHandle);
}
}
using (var dialog = new AutomationDialog(app, AutomationElement.FromHandle(dialogHandle))) {
var label = dialog.FindByAutomationId("CommandLink_1000");
Assert.IsNotNull(label);
string expectedLabel =
"The following packages will be installed using pip:\r\n" +
"\r\n" +
"ptvsd\r\n" +
"azure==0.1"; ;
Assert.AreEqual(expectedLabel, label.Current.HelpText);
dialog.Cancel();
try {
task.Wait(1000);
Assert.Fail("Command was not canceled after dismissing the package install confirmation dialog");
} catch (AggregateException ex) {
if (!(ex.InnerException is TaskCanceledException)) {
throw;
}
}
}
} finally {
if (!task.IsCanceled && !task.IsCompleted && !task.IsFaulted) {
if (task.Wait(10000)) {
task.Dispose();
}
} else {
task.Dispose();
}
}
// Then, execute command and allow it to proceed.
task = ExecuteAsync(node, "Require Packages");
try {
var dialogHandle = app.WaitForDialog(task);
if (dialogHandle == IntPtr.Zero) {
if (task.IsFaulted && task.Exception != null) {
Assert.Fail("Unexpected exception in package install confirmation dialog:\n{0}", task.Exception);
} else {
Assert.AreNotEqual(IntPtr.Zero, dialogHandle);
}
}
using (var dialog = new AutomationDialog(app, AutomationElement.FromHandle(dialogHandle))) {
dialog.ClickButtonAndClose("CommandLink_1000", nameIsAutomationId: true);
}
task.Wait();
var ver = PythonVersion.Version.ToVersion();
ExpectOutputWindowText(app, string.Format("pass {0}.{1}", ver.Major, ver.Minor));
} finally {
if (!task.IsCanceled && !task.IsCompleted && !task.IsFaulted) {
if (task.Wait(10000)) {
task.Dispose();
}
} else {
task.Dispose();
}
}
}
}
[TestMethod, Priority(1)]
[HostType("VSTestHost"), TestCategory("Installed")]
public void CustomCommandsSearchPath() {
var expectedSearchPath = string.Format("['{0}', '{1}', '{2}']",
// Includes CWD (ProjectHome) first
TestData.GetPath(@"TestData\Targets\Package\Subpackage").Replace("\\", "\\\\"),
// Specified as '..\..' from ProjectHome
TestData.GetPath(@"TestData\Targets").Replace("\\", "\\\\"),
// Specified as '..' from ProjectHome
TestData.GetPath(@"TestData\Targets\Package").Replace("\\", "\\\\")
);
using (var app = new PythonVisualStudioApp()) {
PythonProjectNode node;
EnvDTE.Project proj;
OpenProject(app, "CommandSearchPath.sln", out node, out proj);
Execute(node, "Import From Search Path");
var outputWindow = app.Element.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(AutomationElement.ClassNameProperty, "GenericPane"),
new PropertyCondition(AutomationElement.NameProperty, "Output")
)
);
Assert.IsNotNull(outputWindow, "Output Window was not opened");
ExpectOutputWindowText(app, expectedSearchPath);
}
}
}
[TestClass]
public class BuildTasksUI26Tests : BuildTasksUI27Tests {
internal override PythonVersion PythonVersion {
get {
return PythonPaths.Python26 ?? PythonPaths.Python26_x64;
}
}
}
[TestClass]
public class BuildTasksUI35Tests : BuildTasksUI27Tests {
internal override PythonVersion PythonVersion {
get {
return PythonPaths.Python35 ?? PythonPaths.Python35_x64;
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Cache.Query.Continuous
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Event;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Cache.Query.Continuous;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Cache.Event;
using Apache.Ignite.Core.Resource;
using NUnit.Framework;
/// <summary>
/// Tests for continuous query.
/// </summary>
[SuppressMessage("ReSharper", "InconsistentNaming")]
[SuppressMessage("ReSharper", "PossibleNullReferenceException")]
[SuppressMessage("ReSharper", "StaticMemberInGenericType")]
public abstract class ContinuousQueryAbstractTest
{
/** Cache name: ATOMIC, backup. */
protected const string CACHE_ATOMIC_BACKUP = "atomic_backup";
/** Cache name: ATOMIC, no backup. */
protected const string CACHE_ATOMIC_NO_BACKUP = "atomic_no_backup";
/** Cache name: TRANSACTIONAL, backup. */
protected const string CACHE_TX_BACKUP = "transactional_backup";
/** Cache name: TRANSACTIONAL, no backup. */
protected const string CACHE_TX_NO_BACKUP = "transactional_no_backup";
/** Listener events. */
public static BlockingCollection<CallbackEvent> CB_EVTS = new BlockingCollection<CallbackEvent>();
/** Listener events. */
public static BlockingCollection<FilterEvent> FILTER_EVTS = new BlockingCollection<FilterEvent>();
/** First node. */
private IIgnite grid1;
/** Second node. */
private IIgnite grid2;
/** Cache on the first node. */
private ICache<int, BinarizableEntry> cache1;
/** Cache on the second node. */
private ICache<int, BinarizableEntry> cache2;
/** Cache name. */
private readonly string cacheName;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="cacheName">Cache name.</param>
protected ContinuousQueryAbstractTest(string cacheName)
{
this.cacheName = cacheName;
}
/// <summary>
/// Set-up routine.
/// </summary>
[TestFixtureSetUp]
public void SetUp()
{
GC.Collect();
TestUtils.JvmDebug = true;
IgniteConfiguration cfg = new IgniteConfiguration();
BinaryConfiguration portCfg = new BinaryConfiguration();
ICollection<BinaryTypeConfiguration> portTypeCfgs = new List<BinaryTypeConfiguration>();
portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableEntry)));
portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableFilter)));
portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(KeepBinaryFilter)));
portCfg.TypeConfigurations = portTypeCfgs;
cfg.BinaryConfiguration = portCfg;
cfg.JvmClasspath = TestUtils.CreateTestClasspath();
cfg.JvmOptions = TestUtils.TestJavaOptions();
cfg.SpringConfigUrl = "config\\cache-query-continuous.xml";
cfg.GridName = "grid-1";
grid1 = Ignition.Start(cfg);
cache1 = grid1.GetCache<int, BinarizableEntry>(cacheName);
cfg.GridName = "grid-2";
grid2 = Ignition.Start(cfg);
cache2 = grid2.GetCache<int, BinarizableEntry>(cacheName);
}
/// <summary>
/// Tear-down routine.
/// </summary>
[TestFixtureTearDown]
public void TearDown()
{
Ignition.StopAll(true);
}
/// <summary>
/// Before-test routine.
/// </summary>
[SetUp]
public void BeforeTest()
{
CB_EVTS = new BlockingCollection<CallbackEvent>();
FILTER_EVTS = new BlockingCollection<FilterEvent>();
AbstractFilter<BinarizableEntry>.res = true;
AbstractFilter<BinarizableEntry>.err = false;
AbstractFilter<BinarizableEntry>.marshErr = false;
AbstractFilter<BinarizableEntry>.unmarshErr = false;
cache1.Remove(PrimaryKey(cache1));
cache1.Remove(PrimaryKey(cache2));
Assert.AreEqual(0, cache1.GetSize());
Assert.AreEqual(0, cache2.GetSize());
Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name);
}
/// <summary>
/// Test arguments validation.
/// </summary>
[Test]
public void TestValidation()
{
Assert.Throws<ArgumentException>(() => { cache1.QueryContinuous(new ContinuousQuery<int, BinarizableEntry>(null)); });
}
/// <summary>
/// Test multiple closes.
/// </summary>
[Test]
public void TestMultipleClose()
{
int key1 = PrimaryKey(cache1);
int key2 = PrimaryKey(cache2);
Assert.AreNotEqual(key1, key2);
ContinuousQuery<int, BinarizableEntry> qry =
new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
IDisposable qryHnd;
using (qryHnd = cache1.QueryContinuous(qry))
{
// Put from local node.
cache1.GetAndPut(key1, Entry(key1));
CheckCallbackSingle(key1, null, Entry(key1));
// Put from remote node.
cache2.GetAndPut(key2, Entry(key2));
CheckCallbackSingle(key2, null, Entry(key2));
}
qryHnd.Dispose();
}
/// <summary>
/// Test regular callback operations.
/// </summary>
[Test]
public void TestCallback()
{
CheckCallback(false);
}
/// <summary>
/// Check regular callback execution.
/// </summary>
/// <param name="loc"></param>
protected void CheckCallback(bool loc)
{
int key1 = PrimaryKey(cache1);
int key2 = PrimaryKey(cache2);
ContinuousQuery<int, BinarizableEntry> qry = loc ?
new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>(), true) :
new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
using (cache1.QueryContinuous(qry))
{
// Put from local node.
cache1.GetAndPut(key1, Entry(key1));
CheckCallbackSingle(key1, null, Entry(key1));
cache1.GetAndPut(key1, Entry(key1 + 1));
CheckCallbackSingle(key1, Entry(key1), Entry(key1 + 1));
cache1.Remove(key1);
CheckCallbackSingle(key1, Entry(key1 + 1), null);
// Put from remote node.
cache2.GetAndPut(key2, Entry(key2));
if (loc)
CheckNoCallback(100);
else
CheckCallbackSingle(key2, null, Entry(key2));
cache1.GetAndPut(key2, Entry(key2 + 1));
if (loc)
CheckNoCallback(100);
else
CheckCallbackSingle(key2, Entry(key2), Entry(key2 + 1));
cache1.Remove(key2);
if (loc)
CheckNoCallback(100);
else
CheckCallbackSingle(key2, Entry(key2 + 1), null);
}
cache1.Put(key1, Entry(key1));
CheckNoCallback(100);
cache1.Put(key2, Entry(key2));
CheckNoCallback(100);
}
/// <summary>
/// Test Ignite injection into callback.
/// </summary>
[Test]
public void TestCallbackInjection()
{
Listener<BinarizableEntry> cb = new Listener<BinarizableEntry>();
Assert.IsNull(cb.ignite);
using (cache1.QueryContinuous(new ContinuousQuery<int, BinarizableEntry>(cb)))
{
Assert.IsNotNull(cb.ignite);
}
}
/// <summary>
/// Test binarizable filter logic.
/// </summary>
[Test]
public void TestFilterBinarizable()
{
CheckFilter(true, false);
}
/// <summary>
/// Test serializable filter logic.
/// </summary>
[Test]
public void TestFilterSerializable()
{
CheckFilter(false, false);
}
/// <summary>
/// Check filter.
/// </summary>
/// <param name="binarizable">Binarizable.</param>
/// <param name="loc">Local cache flag.</param>
protected void CheckFilter(bool binarizable, bool loc)
{
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter =
binarizable ? (AbstractFilter<BinarizableEntry>) new BinarizableFilter() : new SerializableFilter();
ContinuousQuery<int, BinarizableEntry> qry = loc ?
new ContinuousQuery<int, BinarizableEntry>(lsnr, filter, true) :
new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
using (cache1.QueryContinuous(qry))
{
// Put from local node.
int key1 = PrimaryKey(cache1);
cache1.GetAndPut(key1, Entry(key1));
CheckFilterSingle(key1, null, Entry(key1));
CheckCallbackSingle(key1, null, Entry(key1));
// Put from remote node.
int key2 = PrimaryKey(cache2);
cache1.GetAndPut(key2, Entry(key2));
if (loc)
{
CheckNoFilter(key2);
CheckNoCallback(key2);
}
else
{
CheckFilterSingle(key2, null, Entry(key2));
CheckCallbackSingle(key2, null, Entry(key2));
}
AbstractFilter<BinarizableEntry>.res = false;
// Ignored put from local node.
cache1.GetAndPut(key1, Entry(key1 + 1));
CheckFilterSingle(key1, Entry(key1), Entry(key1 + 1));
CheckNoCallback(100);
// Ignored put from remote node.
cache1.GetAndPut(key2, Entry(key2 + 1));
if (loc)
CheckNoFilter(100);
else
CheckFilterSingle(key2, Entry(key2), Entry(key2 + 1));
CheckNoCallback(100);
}
}
/// <summary>
/// Test binarizable filter error during invoke.
/// </summary>
[Ignore("IGNITE-521")]
[Test]
public void TestFilterInvokeErrorBinarizable()
{
CheckFilterInvokeError(true);
}
/// <summary>
/// Test serializable filter error during invoke.
/// </summary>
[Ignore("IGNITE-521")]
[Test]
public void TestFilterInvokeErrorSerializable()
{
CheckFilterInvokeError(false);
}
/// <summary>
/// Check filter error handling logic during invoke.
/// </summary>
private void CheckFilterInvokeError(bool binarizable)
{
AbstractFilter<BinarizableEntry>.err = true;
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter =
binarizable ? (AbstractFilter<BinarizableEntry>) new BinarizableFilter() : new SerializableFilter();
ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
using (cache1.QueryContinuous(qry))
{
// Put from local node.
try
{
cache1.GetAndPut(PrimaryKey(cache1), Entry(1));
Assert.Fail("Should not reach this place.");
}
catch (IgniteException)
{
// No-op.
}
catch (Exception)
{
Assert.Fail("Unexpected error.");
}
// Put from remote node.
try
{
cache1.GetAndPut(PrimaryKey(cache2), Entry(1));
Assert.Fail("Should not reach this place.");
}
catch (IgniteException)
{
// No-op.
}
catch (Exception)
{
Assert.Fail("Unexpected error.");
}
}
}
/// <summary>
/// Test binarizable filter marshalling error.
/// </summary>
[Test]
public void TestFilterMarshalErrorBinarizable()
{
CheckFilterMarshalError(true);
}
/// <summary>
/// Test serializable filter marshalling error.
/// </summary>
[Test]
public void TestFilterMarshalErrorSerializable()
{
CheckFilterMarshalError(false);
}
/// <summary>
/// Check filter marshal error handling.
/// </summary>
/// <param name="binarizable">Binarizable flag.</param>
private void CheckFilterMarshalError(bool binarizable)
{
AbstractFilter<BinarizableEntry>.marshErr = true;
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter =
binarizable ? (AbstractFilter<BinarizableEntry>)new BinarizableFilter() : new SerializableFilter();
ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
Assert.Throws<Exception>(() =>
{
using (cache1.QueryContinuous(qry))
{
// No-op.
}
});
}
/// <summary>
/// Test non-serializable filter error.
/// </summary>
[Test]
public void TestFilterNonSerializable()
{
CheckFilterNonSerializable(false);
}
/// <summary>
/// Test non-serializable filter behavior.
/// </summary>
/// <param name="loc"></param>
protected void CheckFilterNonSerializable(bool loc)
{
AbstractFilter<BinarizableEntry>.unmarshErr = true;
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter = new LocalFilter();
ContinuousQuery<int, BinarizableEntry> qry = loc
? new ContinuousQuery<int, BinarizableEntry>(lsnr, filter, true)
: new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
if (loc)
{
using (cache1.QueryContinuous(qry))
{
// Local put must be fine.
int key1 = PrimaryKey(cache1);
cache1.GetAndPut(key1, Entry(key1));
CheckFilterSingle(key1, null, Entry(key1));
}
}
else
{
Assert.Throws<BinaryObjectException>(() =>
{
using (cache1.QueryContinuous(qry))
{
// No-op.
}
});
}
}
/// <summary>
/// Test binarizable filter unmarshalling error.
/// </summary>
[Ignore("IGNITE-521")]
[Test]
public void TestFilterUnmarshalErrorBinarizable()
{
CheckFilterUnmarshalError(true);
}
/// <summary>
/// Test serializable filter unmarshalling error.
/// </summary>
[Ignore("IGNITE-521")]
[Test]
public void TestFilterUnmarshalErrorSerializable()
{
CheckFilterUnmarshalError(false);
}
/// <summary>
/// Check filter unmarshal error handling.
/// </summary>
/// <param name="binarizable">Binarizable flag.</param>
private void CheckFilterUnmarshalError(bool binarizable)
{
AbstractFilter<BinarizableEntry>.unmarshErr = true;
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter =
binarizable ? (AbstractFilter<BinarizableEntry>) new BinarizableFilter() : new SerializableFilter();
ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
using (cache1.QueryContinuous(qry))
{
// Local put must be fine.
int key1 = PrimaryKey(cache1);
cache1.GetAndPut(key1, Entry(key1));
CheckFilterSingle(key1, null, Entry(key1));
// Remote put must fail.
try
{
cache1.GetAndPut(PrimaryKey(cache2), Entry(1));
Assert.Fail("Should not reach this place.");
}
catch (IgniteException)
{
// No-op.
}
catch (Exception)
{
Assert.Fail("Unexpected error.");
}
}
}
/// <summary>
/// Test Ignite injection into filters.
/// </summary>
[Test]
public void TestFilterInjection()
{
Listener<BinarizableEntry> cb = new Listener<BinarizableEntry>();
BinarizableFilter filter = new BinarizableFilter();
Assert.IsNull(filter.ignite);
using (cache1.QueryContinuous(new ContinuousQuery<int, BinarizableEntry>(cb, filter)))
{
// Local injection.
Assert.IsNotNull(filter.ignite);
// Remote injection.
cache1.GetAndPut(PrimaryKey(cache2), Entry(1));
FilterEvent evt;
Assert.IsTrue(FILTER_EVTS.TryTake(out evt, 500));
Assert.IsNotNull(evt.ignite);
}
}
/// <summary>
/// Test "keep-binary" scenario.
/// </summary>
[Test]
public void TestKeepBinary()
{
var cache = cache1.WithKeepBinary<int, IBinaryObject>();
ContinuousQuery<int, IBinaryObject> qry = new ContinuousQuery<int, IBinaryObject>(
new Listener<IBinaryObject>(), new KeepBinaryFilter());
using (cache.QueryContinuous(qry))
{
// 1. Local put.
cache1.GetAndPut(PrimaryKey(cache1), Entry(1));
CallbackEvent cbEvt;
FilterEvent filterEvt;
Assert.IsTrue(FILTER_EVTS.TryTake(out filterEvt, 500));
Assert.AreEqual(PrimaryKey(cache1), filterEvt.entry.Key);
Assert.AreEqual(null, filterEvt.entry.OldValue);
Assert.AreEqual(Entry(1), (filterEvt.entry.Value as IBinaryObject)
.Deserialize<BinarizableEntry>());
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
Assert.AreEqual(1, cbEvt.entries.Count);
Assert.AreEqual(PrimaryKey(cache1), cbEvt.entries.First().Key);
Assert.AreEqual(null, cbEvt.entries.First().OldValue);
Assert.AreEqual(Entry(1), (cbEvt.entries.First().Value as IBinaryObject)
.Deserialize<BinarizableEntry>());
// 2. Remote put.
ClearEvents();
cache1.GetAndPut(PrimaryKey(cache2), Entry(2));
Assert.IsTrue(FILTER_EVTS.TryTake(out filterEvt, 500));
Assert.AreEqual(PrimaryKey(cache2), filterEvt.entry.Key);
Assert.AreEqual(null, filterEvt.entry.OldValue);
Assert.AreEqual(Entry(2), (filterEvt.entry.Value as IBinaryObject)
.Deserialize<BinarizableEntry>());
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
Assert.AreEqual(1, cbEvt.entries.Count);
Assert.AreEqual(PrimaryKey(cache2), cbEvt.entries.First().Key);
Assert.AreEqual(null, cbEvt.entries.First().OldValue);
Assert.AreEqual(Entry(2),
(cbEvt.entries.First().Value as IBinaryObject).Deserialize<BinarizableEntry>());
}
}
/// <summary>
/// Test value types (special handling is required for nulls).
/// </summary>
[Test]
public void TestValueTypes()
{
var cache = grid1.GetCache<int, int>(cacheName);
var qry = new ContinuousQuery<int, int>(new Listener<int>());
var key = PrimaryKey(cache);
using (cache.QueryContinuous(qry))
{
// First update
cache.Put(key, 1);
CallbackEvent cbEvt;
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
var cbEntry = cbEvt.entries.Single();
Assert.IsFalse(cbEntry.HasOldValue);
Assert.IsTrue(cbEntry.HasValue);
Assert.AreEqual(key, cbEntry.Key);
Assert.AreEqual(null, cbEntry.OldValue);
Assert.AreEqual(1, cbEntry.Value);
// Second update
cache.Put(key, 2);
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
cbEntry = cbEvt.entries.Single();
Assert.IsTrue(cbEntry.HasOldValue);
Assert.IsTrue(cbEntry.HasValue);
Assert.AreEqual(key, cbEntry.Key);
Assert.AreEqual(1, cbEntry.OldValue);
Assert.AreEqual(2, cbEntry.Value);
// Remove
cache.Remove(key);
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
cbEntry = cbEvt.entries.Single();
Assert.IsTrue(cbEntry.HasOldValue);
Assert.IsFalse(cbEntry.HasValue);
Assert.AreEqual(key, cbEntry.Key);
Assert.AreEqual(2, cbEntry.OldValue);
Assert.AreEqual(null, cbEntry.Value);
}
}
/// <summary>
/// Test whether buffer size works fine.
/// </summary>
[Test]
public void TestBufferSize()
{
// Put two remote keys in advance.
List<int> rmtKeys = PrimaryKeys(cache2, 2);
ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
qry.BufferSize = 2;
qry.TimeInterval = TimeSpan.FromMilliseconds(1000000);
using (cache1.QueryContinuous(qry))
{
qry.BufferSize = 2;
cache1.GetAndPut(rmtKeys[0], Entry(rmtKeys[0]));
CheckNoCallback(100);
cache1.GetAndPut(rmtKeys[1], Entry(rmtKeys[1]));
CallbackEvent evt;
Assert.IsTrue(CB_EVTS.TryTake(out evt, 1000));
Assert.AreEqual(2, evt.entries.Count);
var entryRmt0 = evt.entries.Single(entry => { return entry.Key.Equals(rmtKeys[0]); });
var entryRmt1 = evt.entries.Single(entry => { return entry.Key.Equals(rmtKeys[1]); });
Assert.AreEqual(rmtKeys[0], entryRmt0.Key);
Assert.IsNull(entryRmt0.OldValue);
Assert.AreEqual(Entry(rmtKeys[0]), entryRmt0.Value);
Assert.AreEqual(rmtKeys[1], entryRmt1.Key);
Assert.IsNull(entryRmt1.OldValue);
Assert.AreEqual(Entry(rmtKeys[1]), entryRmt1.Value);
}
cache1.Remove(rmtKeys[0]);
cache1.Remove(rmtKeys[1]);
}
/// <summary>
/// Test whether timeout works fine.
/// </summary>
[Test]
public void TestTimeout()
{
int key1 = PrimaryKey(cache1);
int key2 = PrimaryKey(cache2);
ContinuousQuery<int, BinarizableEntry> qry =
new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
qry.BufferSize = 2;
qry.TimeInterval = TimeSpan.FromMilliseconds(500);
using (cache1.QueryContinuous(qry))
{
// Put from local node.
cache1.GetAndPut(key1, Entry(key1));
CheckCallbackSingle(key1, null, Entry(key1));
// Put from remote node.
cache1.GetAndPut(key2, Entry(key2));
CheckNoCallback(100);
CheckCallbackSingle(key2, null, Entry(key2), 1000);
}
}
/// <summary>
/// Test whether nested Ignite API call from callback works fine.
/// </summary>
[Test]
public void TestNestedCallFromCallback()
{
var cache = cache1.WithKeepBinary<int, IBinaryObject>();
int key = PrimaryKey(cache1);
NestedCallListener cb = new NestedCallListener();
using (cache.QueryContinuous(new ContinuousQuery<int, IBinaryObject>(cb)))
{
cache1.GetAndPut(key, Entry(key));
cb.countDown.Wait();
}
cache.Remove(key);
}
/// <summary>
/// Tests the initial query.
/// </summary>
[Test]
public void TestInitialQuery()
{
// Scan query, GetAll
TestInitialQuery(new ScanQuery<int, BinarizableEntry>(new InitialQueryScanFilter()), cur => cur.GetAll());
// Scan query, iterator
TestInitialQuery(new ScanQuery<int, BinarizableEntry>(new InitialQueryScanFilter()), cur => cur.ToList());
// Sql query, GetAll
TestInitialQuery(new SqlQuery(typeof(BinarizableEntry), "val < 33"), cur => cur.GetAll());
// Sql query, iterator
TestInitialQuery(new SqlQuery(typeof(BinarizableEntry), "val < 33"), cur => cur.ToList());
// Text query, GetAll
TestInitialQuery(new TextQuery(typeof(BinarizableEntry), "1*"), cur => cur.GetAll());
// Text query, iterator
TestInitialQuery(new TextQuery(typeof(BinarizableEntry), "1*"), cur => cur.ToList());
// Test exception: invalid initial query
var ex = Assert.Throws<IgniteException>(
() => TestInitialQuery(new TextQuery(typeof (BinarizableEntry), "*"), cur => cur.GetAll()));
Assert.AreEqual("Cannot parse '*': '*' or '?' not allowed as first character in WildcardQuery", ex.Message);
}
/// <summary>
/// Tests the initial query.
/// </summary>
private void TestInitialQuery(QueryBase initialQry, Func<IQueryCursor<ICacheEntry<int, BinarizableEntry>>,
IEnumerable<ICacheEntry<int, BinarizableEntry>>> getAllFunc)
{
var qry = new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
cache1.Put(11, Entry(11));
cache1.Put(12, Entry(12));
cache1.Put(33, Entry(33));
try
{
IContinuousQueryHandle<ICacheEntry<int, BinarizableEntry>> contQry;
using (contQry = cache1.QueryContinuous(qry, initialQry))
{
// Check initial query
var initialEntries =
getAllFunc(contQry.GetInitialQueryCursor()).Distinct().OrderBy(x => x.Key).ToList();
Assert.Throws<InvalidOperationException>(() => contQry.GetInitialQueryCursor());
Assert.AreEqual(2, initialEntries.Count);
for (int i = 0; i < initialEntries.Count; i++)
{
Assert.AreEqual(i + 11, initialEntries[i].Key);
Assert.AreEqual(i + 11, initialEntries[i].Value.val);
}
// Check continuous query
cache1.Put(44, Entry(44));
CheckCallbackSingle(44, null, Entry(44));
}
Assert.Throws<ObjectDisposedException>(() => contQry.GetInitialQueryCursor());
contQry.Dispose(); // multiple dispose calls are ok
}
finally
{
cache1.Clear();
}
}
/// <summary>
/// Check single filter event.
/// </summary>
/// <param name="expKey">Expected key.</param>
/// <param name="expOldVal">Expected old value.</param>
/// <param name="expVal">Expected value.</param>
private void CheckFilterSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal)
{
CheckFilterSingle(expKey, expOldVal, expVal, 1000);
ClearEvents();
}
/// <summary>
/// Check single filter event.
/// </summary>
/// <param name="expKey">Expected key.</param>
/// <param name="expOldVal">Expected old value.</param>
/// <param name="expVal">Expected value.</param>
/// <param name="timeout">Timeout.</param>
private static void CheckFilterSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal, int timeout)
{
FilterEvent evt;
Assert.IsTrue(FILTER_EVTS.TryTake(out evt, timeout));
Assert.AreEqual(expKey, evt.entry.Key);
Assert.AreEqual(expOldVal, evt.entry.OldValue);
Assert.AreEqual(expVal, evt.entry.Value);
ClearEvents();
}
/// <summary>
/// Clears the events collection.
/// </summary>
private static void ClearEvents()
{
while (FILTER_EVTS.Count > 0)
FILTER_EVTS.Take();
}
/// <summary>
/// Ensure that no filter events are logged.
/// </summary>
/// <param name="timeout">Timeout.</param>
private static void CheckNoFilter(int timeout)
{
FilterEvent evt;
Assert.IsFalse(FILTER_EVTS.TryTake(out evt, timeout));
}
/// <summary>
/// Check single callback event.
/// </summary>
/// <param name="expKey">Expected key.</param>
/// <param name="expOldVal">Expected old value.</param>
/// <param name="expVal">Expected new value.</param>
private static void CheckCallbackSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal)
{
CheckCallbackSingle(expKey, expOldVal, expVal, 1000);
}
/// <summary>
/// Check single callback event.
/// </summary>
/// <param name="expKey">Expected key.</param>
/// <param name="expOldVal">Expected old value.</param>
/// <param name="expVal">Expected new value.</param>
/// <param name="timeout">Timeout.</param>
private static void CheckCallbackSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal, int timeout)
{
CallbackEvent evt;
Assert.IsTrue(CB_EVTS.TryTake(out evt, timeout));
Assert.AreEqual(0, CB_EVTS.Count);
var e = evt.entries.Single();
Assert.AreEqual(expKey, e.Key);
Assert.AreEqual(expOldVal, e.OldValue);
Assert.AreEqual(expVal, e.Value);
}
/// <summary>
/// Ensure that no callback events are logged.
/// </summary>
/// <param name="timeout">Timeout.</param>
private void CheckNoCallback(int timeout)
{
CallbackEvent evt;
Assert.IsFalse(CB_EVTS.TryTake(out evt, timeout));
}
/// <summary>
/// Craate entry.
/// </summary>
/// <param name="val">Value.</param>
/// <returns>Entry.</returns>
private static BinarizableEntry Entry(int val)
{
return new BinarizableEntry(val);
}
/// <summary>
/// Get primary key for cache.
/// </summary>
/// <param name="cache">Cache.</param>
/// <returns>Primary key.</returns>
private static int PrimaryKey<T>(ICache<int, T> cache)
{
return PrimaryKeys(cache, 1)[0];
}
/// <summary>
/// Get primary keys for cache.
/// </summary>
/// <param name="cache">Cache.</param>
/// <param name="cnt">Amount of keys.</param>
/// <param name="startFrom">Value to start from.</param>
/// <returns></returns>
private static List<int> PrimaryKeys<T>(ICache<int, T> cache, int cnt, int startFrom = 0)
{
IClusterNode node = cache.Ignite.GetCluster().GetLocalNode();
ICacheAffinity aff = cache.Ignite.GetAffinity(cache.Name);
List<int> keys = new List<int>(cnt);
Assert.IsTrue(
TestUtils.WaitForCondition(() =>
{
for (int i = startFrom; i < startFrom + 100000; i++)
{
if (aff.IsPrimary(node, i))
{
keys.Add(i);
if (keys.Count == cnt)
return true;
}
}
return false;
}, 5000), "Failed to find " + cnt + " primary keys.");
return keys;
}
/// <summary>
/// Creates object-typed event.
/// </summary>
private static ICacheEntryEvent<object, object> CreateEvent<T, V>(ICacheEntryEvent<T,V> e)
{
if (!e.HasOldValue)
return new CacheEntryCreateEvent<object, object>(e.Key, e.Value);
if (!e.HasValue)
return new CacheEntryRemoveEvent<object, object>(e.Key, e.OldValue);
return new CacheEntryUpdateEvent<object, object>(e.Key, e.OldValue, e.Value);
}
/// <summary>
/// Binarizable entry.
/// </summary>
public class BinarizableEntry
{
/** Value. */
public readonly int val;
/** <inheritDot /> */
public override int GetHashCode()
{
return val;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="val">Value.</param>
public BinarizableEntry(int val)
{
this.val = val;
}
/** <inheritDoc /> */
public override bool Equals(object obj)
{
return obj != null && obj is BinarizableEntry && ((BinarizableEntry)obj).val == val;
}
/** <inheritDoc /> */
public override string ToString()
{
return string.Format("BinarizableEntry [Val: {0}]", val);
}
}
/// <summary>
/// Abstract filter.
/// </summary>
[Serializable]
public abstract class AbstractFilter<V> : ICacheEntryEventFilter<int, V>
{
/** Result. */
public static volatile bool res = true;
/** Throw error on invocation. */
public static volatile bool err;
/** Throw error during marshalling. */
public static volatile bool marshErr;
/** Throw error during unmarshalling. */
public static volatile bool unmarshErr;
/** Grid. */
[InstanceResource]
public IIgnite ignite;
/** <inheritDoc /> */
public bool Evaluate(ICacheEntryEvent<int, V> evt)
{
if (err)
throw new Exception("Filter error.");
FILTER_EVTS.Add(new FilterEvent(ignite, CreateEvent(evt)));
return res;
}
}
/// <summary>
/// Filter which cannot be serialized.
/// </summary>
public class LocalFilter : AbstractFilter<BinarizableEntry>
{
// No-op.
}
/// <summary>
/// Binarizable filter.
/// </summary>
public class BinarizableFilter : AbstractFilter<BinarizableEntry>, IBinarizable
{
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
if (marshErr)
throw new Exception("Filter marshalling error.");
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
if (unmarshErr)
throw new Exception("Filter unmarshalling error.");
}
}
/// <summary>
/// Serializable filter.
/// </summary>
[Serializable]
public class SerializableFilter : AbstractFilter<BinarizableEntry>, ISerializable
{
/// <summary>
/// Constructor.
/// </summary>
public SerializableFilter()
{
// No-op.
}
/// <summary>
/// Serialization constructor.
/// </summary>
/// <param name="info">Info.</param>
/// <param name="context">Context.</param>
protected SerializableFilter(SerializationInfo info, StreamingContext context)
{
if (unmarshErr)
throw new Exception("Filter unmarshalling error.");
}
/** <inheritDoc /> */
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (marshErr)
throw new Exception("Filter marshalling error.");
}
}
/// <summary>
/// Filter for "keep-binary" scenario.
/// </summary>
public class KeepBinaryFilter : AbstractFilter<IBinaryObject>
{
// No-op.
}
/// <summary>
/// Listener.
/// </summary>
public class Listener<V> : ICacheEntryEventListener<int, V>
{
[InstanceResource]
public IIgnite ignite;
/** <inheritDoc /> */
public void OnEvent(IEnumerable<ICacheEntryEvent<int, V>> evts)
{
CB_EVTS.Add(new CallbackEvent(evts.Select(CreateEvent).ToList()));
}
}
/// <summary>
/// Listener with nested Ignite API call.
/// </summary>
public class NestedCallListener : ICacheEntryEventListener<int, IBinaryObject>
{
/** Event. */
public readonly CountdownEvent countDown = new CountdownEvent(1);
public void OnEvent(IEnumerable<ICacheEntryEvent<int, IBinaryObject>> evts)
{
foreach (ICacheEntryEvent<int, IBinaryObject> evt in evts)
{
IBinaryObject val = evt.Value;
IBinaryType meta = val.GetBinaryType();
Assert.AreEqual(typeof(BinarizableEntry).Name, meta.TypeName);
}
countDown.Signal();
}
}
/// <summary>
/// Filter event.
/// </summary>
public class FilterEvent
{
/** Grid. */
public IIgnite ignite;
/** Entry. */
public ICacheEntryEvent<object, object> entry;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="ignite">Grid.</param>
/// <param name="entry">Entry.</param>
public FilterEvent(IIgnite ignite, ICacheEntryEvent<object, object> entry)
{
this.ignite = ignite;
this.entry = entry;
}
}
/// <summary>
/// Callbakc event.
/// </summary>
public class CallbackEvent
{
/** Entries. */
public ICollection<ICacheEntryEvent<object, object>> entries;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="entries">Entries.</param>
public CallbackEvent(ICollection<ICacheEntryEvent<object, object>> entries)
{
this.entries = entries;
}
}
/// <summary>
/// ScanQuery filter for InitialQuery test.
/// </summary>
[Serializable]
private class InitialQueryScanFilter : ICacheEntryFilter<int, BinarizableEntry>
{
/** <inheritdoc /> */
public bool Invoke(ICacheEntry<int, BinarizableEntry> entry)
{
return entry.Key < 33;
}
}
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using ParentLoadSoftDelete.DataAccess;
using ParentLoadSoftDelete.DataAccess.ERCLevel;
namespace ParentLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// F07_Country_Child (editable child object).<br/>
/// This is a generated base class of <see cref="F07_Country_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="F06_Country"/> collection.
/// </remarks>
[Serializable]
public partial class F07_Country_Child : BusinessBase<F07_Country_Child>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int country_ID1 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Country_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Country_Child_NameProperty = RegisterProperty<string>(p => p.Country_Child_Name, "Regions Child Name");
/// <summary>
/// Gets or sets the Regions Child Name.
/// </summary>
/// <value>The Regions Child Name.</value>
public string Country_Child_Name
{
get { return GetProperty(Country_Child_NameProperty); }
set { SetProperty(Country_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="F07_Country_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="F07_Country_Child"/> object.</returns>
internal static F07_Country_Child NewF07_Country_Child()
{
return DataPortal.CreateChild<F07_Country_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="F07_Country_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="F07_Country_Child"/> object.</returns>
internal static F07_Country_Child GetF07_Country_Child(SafeDataReader dr)
{
F07_Country_Child obj = new F07_Country_Child();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="F07_Country_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public F07_Country_Child()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="F07_Country_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="F07_Country_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Country_Child_NameProperty, dr.GetString("Country_Child_Name"));
// parent properties
country_ID1 = dr.GetInt32("Country_ID1");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="F07_Country_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(F06_Country parent)
{
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<IF07_Country_ChildDal>();
using (BypassPropertyChecks)
{
dal.Insert(
parent.Country_ID,
Country_Child_Name
);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="F07_Country_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(F06_Country parent)
{
if (!IsDirty)
return;
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<IF07_Country_ChildDal>();
using (BypassPropertyChecks)
{
dal.Update(
parent.Country_ID,
Country_Child_Name
);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="F07_Country_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(F06_Country parent)
{
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IF07_Country_ChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Country_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using PostSharp.Patterns.Contracts;
/// <remarks>
/// See Program.cs for license.
/// </remarks>
namespace TerrariaPixelArtHelper
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
#region GetColoredMapWallPixels
static readonly ConcurrentDictionary<(string wallName, string color), Task<int[]>> colorMapWallsPixelsCache = new ConcurrentDictionary<(string wallName, string color), Task<int[]>>();
/// <summary>
/// Gets the colored pixels of a wall on the map.
/// </summary>
/// <param name="wallName">The name of the wall to get the pixels of.</param>
/// <param name="color">The color of the wall to get the pixels of.</param>
/// <returns>The pixels of the colored map wall.</returns>
internal static async Task<int[]> GetColoredMapWallPixels([Required] string wallName, [Required] string color) => await App.colorMapWallsPixelsCache.GetOrAdd((wallName, color), async key =>
{
// Get the map color for the wall and colorize it if necessary.
var wallColor = ColorExtension.GetMapWallColor(wallName);
if (wallColor.HasValue)
wallColor = wallColor.Value.ColorizeMap(color);
// If we have a proper wall color, return the pixels, return null otherwise.
return wallColor.HasValue ? await Task.Run(() => new int[256].Populate((wallColor.Value.R << 16) | (wallColor.Value.G << 8) | wallColor.Value.B | (wallColor.Value.A << 24))) : null;
});
#endregion
#region GetColoredWallPixels
static readonly ConcurrentDictionary<(string wallName, string color), Task<int[]>> colorWallsPixelsCache = new ConcurrentDictionary<(string wallName, string color), Task<int[]>>();
/// <summary>
/// Gets the colored pixels of a wall in-game.
/// </summary>
/// <param name="wallName">The name of the wall to get the pixels of.</param>
/// <param name="color">The name of the color to get the pixels of.</param>
/// <returns>The pixels of the colored in-game wall.</returns>
internal static async Task<int[]> GetColoredWallPixels([Required] string wallName, [Required] string color) => await App.colorWallsPixelsCache.GetOrAdd((wallName, color), async key =>
{
// Get the pixels of the in-game wall.
int[] pixels = await App.GetWallPixels(wallName);
// Only colorize the wall if we are using an actual color and had pixels.
if (color != "Uncolored" && pixels != null)
await Task.Run(() =>
{
// Create a copy of the pixels so we don't muck up the original wall's pixels.
pixels = pixels.ToArray();
// Colorize all the pixels.
int index = 0;
for (int y = 0; y < App.WallPixelHeight; ++y)
for (int x = 0; x < App.WallPixelWidth; ++x)
{
int c = pixels[index];
var newColor = Color.FromArgb((byte)(c >> 24), (byte)((c >> 16) & 0xFF), (byte)((c >> 8) & 0xFF), (byte)(c & 0xFF)).ColorizeInGame(color);
pixels[index++] = (newColor.R << 16) | (newColor.G << 8) | newColor.B | (newColor.A << 24);
}
});
// Return the pixels, if any.
return pixels;
});
#endregion
#region GetWallPixels
internal const int WallPixelWidth = 48;
internal const int WallPixelHeight = 80;
static readonly ConcurrentDictionary<string, Task<int[]>> wallPixelsCache = new ConcurrentDictionary<string, Task<int[]>>();
/// <summary>
/// Gets the pixels of a wall in-game.
/// </summary>
/// <param name="wallName">The name of the wall to get the pixels of.</param>
/// <returns>The pixels of the in-game wall.</returns>
internal static async Task<int[]> GetWallPixels([Required] string wallName) => await App.wallPixelsCache.GetOrAdd(wallName, async key =>
{
try
{
// Attempt to load the image from the application's resources, returning its pixels if successful.
using (var ms = new MemoryStream())
{
await Application.GetResourceStream(new Uri($"WallImages/Wall_{wallName.Replace(" ", "")}.png", UriKind.Relative)).Stream.CopyToAsync(ms);
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = ms;
bitmap.EndInit();
bitmap.Freeze();
int[] pixels = new int[bitmap.PixelWidth * bitmap.PixelHeight];
bitmap.CopyPixels(pixels, bitmap.PixelWidth * 4, 0);
return pixels;
}
}
catch (InvalidOperationException)
{
return null;
}
catch (IOException)
{
return null;
}
});
#endregion
#region GetWallFrame
static readonly ConcurrentDictionary<(string wallName, string color, int i, int j, int frame), Task<BitmapSource>> wallFramesCache =
new ConcurrentDictionary<(string wallName, string color, int i, int j, int frame), Task<BitmapSource>>();
/// <summary>
/// Gets a bitmap of the in-game wall frame.
/// </summary>
/// <param name="wallName">The name of the wall to get the bitmap of.</param>
/// <param name="color">The color of the wall to get the bitmap of.</param>
/// <param name="i">The X coordinate of the wall frame (used to determine which frame is used).</param>
/// <param name="j">The Y coordinate of the wall frame (used to determine which frame is used).</param>
/// <param name="frame">The frame of the wall.</param>
/// <returns>The bitmap of the in-game wall frame.</returns>
internal static async Task<BitmapSource> GetWallFrame([Required] string wallName, [Required] string color, int i, int j, int frame) =>
await App.wallFramesCache.GetOrAdd((wallName, color, i, j, frame), async key =>
{
// Get the pixels of the in-game wall frame.
int[] pixels = await App.GetWallFramePixels(wallName, color, i, j, frame);
if (pixels == null)
return null;
// Create a bitmap out of the pixels.
var bitmap = PixelManip.Create(16, 16, pixels);
bitmap.Freeze();
return bitmap;
});
#endregion
#region GetWallFramePixels
static readonly ConcurrentDictionary<(string wallName, string color, int i, int j, int frame), Task<int[]>> wallFramesPixelsCache =
new ConcurrentDictionary<(string wallName, string color, int i, int j, int frame), Task<int[]>>();
/// <summary>
/// Gets the pixels of the in-game wall frame.
/// </summary>
/// <param name="wallName">The name of the wall to get the pixels of.</param>
/// <param name="color">The color of the wall to get the pixels of.</param>
/// <param name="i">The X coordinate of the wall frame (used to determine which frame is used).</param>
/// <param name="j">The Y coordinate of the wall frame (used to determine which frame is used).</param>
/// <param name="frame">The frame of the wall.</param>
/// <returns>The pixels of the in-game wall frame.</returns>
internal static async Task<int[]> GetWallFramePixels([Required] string wallName, [Required] string color, int i, int j, int frame) =>
await App.wallFramesPixelsCache.GetOrAdd((wallName, color, i, j, frame), async key =>
{
// Get the pixels of the colored in-game wall.
int[] pixels = await App.GetColoredWallPixels(wallName, color);
if (pixels == null)
return null;
// This section for picking y comes from the part of Terraria.Framing (partially the WallFrame() method) that picks a wall frame based on the X and Y coordinates of the tile.
int x = frame;
int y = i % 3 == 1 && j % 3 == 1 ? 1 : (i % 3 == 0 && j % 3 == 0 ? 2 : (i % 3 == 2 && j % 3 == 1 ? 3 : (i % 3 == 1 && j % 3 == 2 ? 4 : 0)));
// Copy the pixels specifically for the frame we want.
int[] framePixels = new int[256];
for (int y2 = 0; y2 < 16; ++y2)
Array.Copy(pixels, x * 16 + (y * 16 + y2) * App.WallPixelWidth, framePixels, y2 * 16, 16);
return framePixels;
});
#endregion
/// <summary>
/// Zooms the given bitmap to 16 times its original size.
/// </summary>
/// <param name="orig">The original bitmap to zoom.</param>
/// <returns>The zoomed bitmap.</returns>
internal static async Task<BitmapData> ZoomBy16([Required] BitmapSource orig)
{
int width = orig.PixelWidth;
int height = orig.PixelHeight;
var cachedColorPixels = new Dictionary<Color, int[]>();
var colors = new Dictionary<Color, int>();
var pixelInfo = new Dictionary<(int x, int y), PixelInfo>();
int[] zoomedPixels = new int[width * height * 256];
await Task.Run(async () =>
{
// Get the pixels of the original bitmap.
int[] pixels = new int[width * height];
orig.CopyPixels(pixels, width * 4, 0);
int index = 0;
// Loop over the pixels of the original bitmap and create 16x16 "pixels" out of them.
for (int y = 0; y < height; ++y)
for (int x = 0; x < width; ++x)
{
int c = pixels[index++];
var color = Color.FromArgb((byte)(c >> 24), (byte)((c >> 16) & 0xFF), (byte)((c >> 8) & 0xFF), (byte)(c & 0xFF));
// Replace any pixels that have 0 alpha with the transparent color, makes things more consistent if there are somehow multiple 0 alpha colors.
if (color.A == 0)
color = Colors.Transparent;
colors.TryGetValue(color, out int colorCount);
colors[color] = colorCount + 1;
pixelInfo[(x, y)] = new PixelInfo()
{
Color = color
};
if (!cachedColorPixels.TryGetValue(color, out int[] fillRowPixels))
cachedColorPixels[color] = fillRowPixels = new int[256].Populate((color.R << 16) | (color.G << 8) | color.B | (color.A << 24));
await PixelManip.CopyFrom16x16(fillRowPixels, zoomedPixels, x, y, width);
}
});
return new BitmapData()
{
CachedColorPixels = cachedColorPixels,
Colors = colors,
PixelInfo = pixelInfo,
ZoomedPixels = zoomedPixels
};
}
void Application_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
var unhandledException = new UnhandledException(e.Exception);
if (unhandledException.ShowDialog() ?? false)
this.Shutdown();
e.Handled = true;
}
}
}
| |
// "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.Collections.Generic;
using System.IO;
using TheArtOfDev.HtmlRenderer.Adapters.Entities;
using TheArtOfDev.HtmlRenderer.Core;
using TheArtOfDev.HtmlRenderer.Core.Entities;
using TheArtOfDev.HtmlRenderer.Core.Handlers;
using TheArtOfDev.HtmlRenderer.Core.Utils;
namespace TheArtOfDev.HtmlRenderer.Adapters
{
/// <summary>
/// Platform adapter to bridge platform specific objects to HTML Renderer core library.<br/>
/// Core uses abstract renderer objects (RAdapter/RControl/REtc...) to access platform specific functionality, the concrete platforms
/// implements those objects to provide concrete platform implementation. Those allowing the core library to be platform agnostic.
/// <para>
/// Platforms: WinForms, WPF, Metro, PDF renders, etc.<br/>
/// Objects: UI elements(Controls), Graphics(Render context), Colors, Brushes, Pens, Fonts, Images, Clipboard, etc.<br/>
/// </para>
/// </summary>
/// <remarks>
/// It is best to have a singleton instance of this class for concrete implementation!<br/>
/// This is because it holds caches of default CssData, Images, Fonts and Brushes.
/// </remarks>
public abstract class RAdapter
{
#region Fields/Consts
/// <summary>
/// cache of brush color to brush instance
/// </summary>
private readonly Dictionary<RColor, RBrush> _brushesCache = new Dictionary<RColor, RBrush>();
/// <summary>
/// cache of pen color to pen instance
/// </summary>
private readonly Dictionary<RColor, RPen> _penCache = new Dictionary<RColor, RPen>();
/// <summary>
/// cache of all the font used not to create same font again and again
/// </summary>
private readonly FontsHandler _fontsHandler;
/// <summary>
/// default CSS parsed data singleton
/// </summary>
private CssData _defaultCssData;
/// <summary>
/// image used to draw loading image icon
/// </summary>
private RImage _loadImage;
/// <summary>
/// image used to draw error image icon
/// </summary>
private RImage _errorImage;
#endregion
/// <summary>
/// Init.
/// </summary>
protected RAdapter()
{
_fontsHandler = new FontsHandler(this);
}
/// <summary>
/// Get the default CSS stylesheet data.
/// </summary>
public CssData DefaultCssData
{
get { return _defaultCssData ?? (_defaultCssData = CssData.Parse(this, CssDefaults.DefaultStyleSheet, false)); }
}
/// <summary>
/// Resolve color value from given color name.
/// </summary>
/// <param name="colorName">the color name</param>
/// <returns>color value</returns>
public RColor GetColor(string colorName)
{
ArgChecker.AssertArgNotNullOrEmpty(colorName, "colorName");
return GetColorInt(colorName);
}
/// <summary>
/// Get cached pen instance for the given color.
/// </summary>
/// <param name="color">the color to get pen for</param>
/// <returns>pen instance</returns>
public RPen GetPen(RColor color)
{
RPen pen;
if (!_penCache.TryGetValue(color, out pen))
{
_penCache[color] = pen = CreatePen(color);
}
return pen;
}
/// <summary>
/// Get cached solid brush instance for the given color.
/// </summary>
/// <param name="color">the color to get brush for</param>
/// <returns>brush instance</returns>
public RBrush GetSolidBrush(RColor color)
{
RBrush brush;
if (!_brushesCache.TryGetValue(color, out brush))
{
_brushesCache[color] = brush = CreateSolidBrush(color);
}
return brush;
}
/// <summary>
/// Get linear gradient color brush from <paramref name="color1"/> to <paramref name="color2"/>.
/// </summary>
/// <param name="rect">the rectangle to get the brush for</param>
/// <param name="color1">the start color of the gradient</param>
/// <param name="color2">the end color of the gradient</param>
/// <param name="angle">the angle to move the gradient from start color to end color in the rectangle</param>
/// <returns>linear gradient color brush instance</returns>
public RBrush GetLinearGradientBrush(RRect rect, RColor color1, RColor color2, double angle)
{
return CreateLinearGradientBrush(rect, color1, color2, angle);
}
/// <summary>
/// Convert image object returned from <see cref="HtmlImageLoadEventArgs"/> to <see cref="RImage"/>.
/// </summary>
/// <param name="image">the image returned from load event</param>
/// <returns>converted image or null</returns>
public RImage ConvertImage(object image)
{
// TODO:a remove this by creating better API.
return ConvertImageInt(image);
}
/// <summary>
/// Create an <see cref="RImage"/> object from the given stream.
/// </summary>
/// <param name="memoryStream">the stream to create image from</param>
/// <returns>new image instance</returns>
public RImage ImageFromStream(Stream memoryStream)
{
return ImageFromStreamInt(memoryStream);
}
/// <summary>
/// Check if the given font exists in the system by font family name.
/// </summary>
/// <param name="font">the font name to check</param>
/// <returns>true - font exists by given family name, false - otherwise</returns>
public bool IsFontExists(string font)
{
return _fontsHandler.IsFontExists(font);
}
/// <summary>
/// Adds a font family to be used.
/// </summary>
/// <param name="fontFamily">The font family to add.</param>
public void AddFontFamily(RFontFamily fontFamily)
{
_fontsHandler.AddFontFamily(fontFamily);
}
/// <summary>
/// Adds a font mapping from <paramref name="fromFamily"/> to <paramref name="toFamily"/> iff the <paramref name="fromFamily"/> is not found.<br/>
/// When the <paramref name="fromFamily"/> font is used in rendered html and is not found in existing
/// fonts (installed or added) it will be replaced by <paramref name="toFamily"/>.<br/>
/// </summary>
/// <param name="fromFamily">the font family to replace</param>
/// <param name="toFamily">the font family to replace with</param>
public void AddFontFamilyMapping(string fromFamily, string toFamily)
{
_fontsHandler.AddFontFamilyMapping(fromFamily, toFamily);
}
/// <summary>
/// Get font instance by given font family name, size and style.
/// </summary>
/// <param name="family">the font family name</param>
/// <param name="size">font size</param>
/// <param name="style">font style</param>
/// <returns>font instance</returns>
public RFont GetFont(string family, double size, RFontStyle style)
{
return _fontsHandler.GetCachedFont(family, size, style);
}
/// <summary>
/// Get image to be used while HTML image is loading.
/// </summary>
public RImage GetLoadingImage()
{
if (_loadImage == null)
{
var stream = typeof(HtmlRendererUtils).Assembly.GetManifestResourceStream("TheArtOfDev.HtmlRenderer.Core.Utils.ImageLoad.png");
if (stream != null)
_loadImage = ImageFromStream(stream);
}
return _loadImage;
}
/// <summary>
/// Get image to be used if HTML image load failed.
/// </summary>
public RImage GetLoadingFailedImage()
{
if (_errorImage == null)
{
var stream = typeof(HtmlRendererUtils).Assembly.GetManifestResourceStream("TheArtOfDev.HtmlRenderer.Core.Utils.ImageError.png");
if (stream != null)
_errorImage = ImageFromStream(stream);
}
return _errorImage;
}
/// <summary>
/// Get data object for the given html and plain text data.<br />
/// The data object can be used for clipboard or drag-drop operation.<br/>
/// Not relevant for platforms that don't render HTML on UI element.
/// </summary>
/// <param name="html">the html data</param>
/// <param name="plainText">the plain text data</param>
/// <returns>drag-drop data object</returns>
public object GetClipboardDataObject(string html, string plainText)
{
return GetClipboardDataObjectInt(html, plainText);
}
/// <summary>
/// Set the given text to the clipboard<br/>
/// Not relevant for platforms that don't render HTML on UI element.
/// </summary>
/// <param name="text">the text to set</param>
public void SetToClipboard(string text)
{
SetToClipboardInt(text);
}
/// <summary>
/// Set the given html and plain text data to clipboard.<br/>
/// Not relevant for platforms that don't render HTML on UI element.
/// </summary>
/// <param name="html">the html data</param>
/// <param name="plainText">the plain text data</param>
public void SetToClipboard(string html, string plainText)
{
SetToClipboardInt(html, plainText);
}
/// <summary>
/// Set the given image to clipboard.<br/>
/// Not relevant for platforms that don't render HTML on UI element.
/// </summary>
/// <param name="image">the image object to set to clipboard</param>
public void SetToClipboard(RImage image)
{
SetToClipboardInt(image);
}
/// <summary>
/// Create a context menu that can be used on the control<br/>
/// Not relevant for platforms that don't render HTML on UI element.
/// </summary>
/// <returns>new context menu</returns>
public RContextMenu GetContextMenu()
{
return CreateContextMenuInt();
}
/// <summary>
/// Save the given image to file by showing save dialog to the client.<br/>
/// Not relevant for platforms that don't render HTML on UI element.
/// </summary>
/// <param name="image">the image to save</param>
/// <param name="name">the name of the image for save dialog</param>
/// <param name="extension">the extension of the image for save dialog</param>
/// <param name="control">optional: the control to show the dialog on</param>
public void SaveToFile(RImage image, string name, string extension, RControl control = null)
{
SaveToFileInt(image, name, extension, control);
}
/// <summary>
/// Get font instance by given font family name, size and style.
/// </summary>
/// <param name="family">the font family name</param>
/// <param name="size">font size</param>
/// <param name="style">font style</param>
/// <returns>font instance</returns>
internal RFont CreateFont(string family, double size, RFontStyle style)
{
return CreateFontInt(family, size, style);
}
/// <summary>
/// Get font instance by given font family instance, size and style.<br/>
/// Used to support custom fonts that require explicit font family instance to be created.
/// </summary>
/// <param name="family">the font family instance</param>
/// <param name="size">font size</param>
/// <param name="style">font style</param>
/// <returns>font instance</returns>
internal RFont CreateFont(RFontFamily family, double size, RFontStyle style)
{
return CreateFontInt(family, size, style);
}
#region Private/Protected methods
/// <summary>
/// Resolve color value from given color name.
/// </summary>
/// <param name="colorName">the color name</param>
/// <returns>color value</returns>
protected abstract RColor GetColorInt(string colorName);
/// <summary>
/// Get cached pen instance for the given color.
/// </summary>
/// <param name="color">the color to get pen for</param>
/// <returns>pen instance</returns>
protected abstract RPen CreatePen(RColor color);
/// <summary>
/// Get cached solid brush instance for the given color.
/// </summary>
/// <param name="color">the color to get brush for</param>
/// <returns>brush instance</returns>
protected abstract RBrush CreateSolidBrush(RColor color);
/// <summary>
/// Get linear gradient color brush from <paramref name="color1"/> to <paramref name="color2"/>.
/// </summary>
/// <param name="rect">the rectangle to get the brush for</param>
/// <param name="color1">the start color of the gradient</param>
/// <param name="color2">the end color of the gradient</param>
/// <param name="angle">the angle to move the gradient from start color to end color in the rectangle</param>
/// <returns>linear gradient color brush instance</returns>
protected abstract RBrush CreateLinearGradientBrush(RRect rect, RColor color1, RColor color2, double angle);
/// <summary>
/// Convert image object returned from <see cref="HtmlImageLoadEventArgs"/> to <see cref="RImage"/>.
/// </summary>
/// <param name="image">the image returned from load event</param>
/// <returns>converted image or null</returns>
protected abstract RImage ConvertImageInt(object image);
/// <summary>
/// Create an <see cref="RImage"/> object from the given stream.
/// </summary>
/// <param name="memoryStream">the stream to create image from</param>
/// <returns>new image instance</returns>
protected abstract RImage ImageFromStreamInt(Stream memoryStream);
/// <summary>
/// Get font instance by given font family name, size and style.
/// </summary>
/// <param name="family">the font family name</param>
/// <param name="size">font size</param>
/// <param name="style">font style</param>
/// <returns>font instance</returns>
protected abstract RFont CreateFontInt(string family, double size, RFontStyle style);
/// <summary>
/// Get font instance by given font family instance, size and style.<br/>
/// Used to support custom fonts that require explicit font family instance to be created.
/// </summary>
/// <param name="family">the font family instance</param>
/// <param name="size">font size</param>
/// <param name="style">font style</param>
/// <returns>font instance</returns>
protected abstract RFont CreateFontInt(RFontFamily family, double size, RFontStyle style);
/// <summary>
/// Get data object for the given html and plain text data.<br />
/// The data object can be used for clipboard or drag-drop operation.
/// </summary>
/// <param name="html">the html data</param>
/// <param name="plainText">the plain text data</param>
/// <returns>drag-drop data object</returns>
protected virtual object GetClipboardDataObjectInt(string html, string plainText)
{
throw new NotImplementedException();
}
/// <summary>
/// Set the given text to the clipboard
/// </summary>
/// <param name="text">the text to set</param>
protected virtual void SetToClipboardInt(string text)
{
throw new NotImplementedException();
}
/// <summary>
/// Set the given html and plain text data to clipboard.
/// </summary>
/// <param name="html">the html data</param>
/// <param name="plainText">the plain text data</param>
protected virtual void SetToClipboardInt(string html, string plainText)
{
throw new NotImplementedException();
}
/// <summary>
/// Set the given image to clipboard.
/// </summary>
/// <param name="image"></param>
protected virtual void SetToClipboardInt(RImage image)
{
throw new NotImplementedException();
}
/// <summary>
/// Create a context menu that can be used on the control
/// </summary>
/// <returns>new context menu</returns>
protected virtual RContextMenu CreateContextMenuInt()
{
throw new NotImplementedException();
}
/// <summary>
/// Save the given image to file by showing save dialog to the client.
/// </summary>
/// <param name="image">the image to save</param>
/// <param name="name">the name of the image for save dialog</param>
/// <param name="extension">the extension of the image for save dialog</param>
/// <param name="control">optional: the control to show the dialog on</param>
protected virtual void SaveToFileInt(RImage image, string name, string extension, RControl control = null)
{
throw new NotImplementedException();
}
#endregion
}
}
| |
// Deflater.cs
//
// Copyright (C) 2001 Mike Krueger
// Copyright (C) 2004 John Reilly
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
namespace PdfSharp.SharpZipLib.Zip.Compression
{
/// <summary>
/// This is the Deflater class. The deflater class compresses input
/// with the deflate algorithm described in RFC 1951. It has several
/// compression levels and three different strategies described below.
///
/// This class is <i>not</i> thread safe. This is inherent in the API, due
/// to the split of deflate and setInput.
///
/// Author of the original java version: Jochen Hoenicke
/// </summary>
internal class Deflater
{
/// <summary>
/// The best and slowest compression level. This tries to find very
/// long and distant string repetitions.
/// </summary>
public static int BEST_COMPRESSION = 9;
/// <summary>
/// The worst but fastest compression level.
/// </summary>
public static int BEST_SPEED = 1;
/// <summary>
/// The default compression level.
/// </summary>
public static int DEFAULT_COMPRESSION = -1;
/// <summary>
/// This level won't compress at all but output uncompressed blocks.
/// </summary>
public static int NO_COMPRESSION = 0;
/// <summary>
/// The compression method. This is the only method supported so far.
/// There is no need to use this constant at all.
/// </summary>
public static int DEFLATED = 8;
/*
* The Deflater can do the following state transitions:
*
* (1) -> INIT_STATE ----> INIT_FINISHING_STATE ---.
* / | (2) (5) |
* / v (5) |
* (3)| SETDICT_STATE ---> SETDICT_FINISHING_STATE |(3)
* \ | (3) | ,-------'
* | | | (3) /
* v v (5) v v
* (1) -> BUSY_STATE ----> FINISHING_STATE
* | (6)
* v
* FINISHED_STATE
* \_____________________________________/
* | (7)
* v
* CLOSED_STATE
*
* (1) If we should produce a header we start in INIT_STATE, otherwise
* we start in BUSY_STATE.
* (2) A dictionary may be set only when we are in INIT_STATE, then
* we change the state as indicated.
* (3) Whether a dictionary is set or not, on the first call of deflate
* we change to BUSY_STATE.
* (4) -- intentionally left blank -- :)
* (5) FINISHING_STATE is entered, when flush() is called to indicate that
* there is no more INPUT. There are also states indicating, that
* the header wasn't written yet.
* (6) FINISHED_STATE is entered, when everything has been flushed to the
* internal pending output buffer.
* (7) At any time (7)
*
*/
private static int IS_SETDICT = 0x01;
private static int IS_FLUSHING = 0x04;
private static int IS_FINISHING = 0x08;
private static int INIT_STATE = 0x00;
private static int SETDICT_STATE = 0x01;
// private static int INIT_FINISHING_STATE = 0x08;
// private static int SETDICT_FINISHING_STATE = 0x09;
private static int BUSY_STATE = 0x10;
private static int FLUSHING_STATE = 0x14;
private static int FINISHING_STATE = 0x1c;
private static int FINISHED_STATE = 0x1e;
private static int CLOSED_STATE = 0x7f;
/// <summary>
/// Compression level.
/// </summary>
private int level;
/// <summary>
/// If true no Zlib/RFC1950 headers or footers are generated
/// </summary>
private bool noZlibHeaderOrFooter;
/// <summary>
/// The current state.
/// </summary>
private int state;
/// <summary>
/// The total bytes of output written.
/// </summary>
private long totalOut;
/// <summary>
/// The pending output.
/// </summary>
private DeflaterPending pending;
/// <summary>
/// The deflater engine.
/// </summary>
private DeflaterEngine engine;
/// <summary>
/// Creates a new deflater with default compression level.
/// </summary>
public Deflater()
: this(DEFAULT_COMPRESSION, false)
{
}
/// <summary>
/// Creates a new deflater with given compression level.
/// </summary>
/// <param name="lvl">
/// the compression level, a value between NO_COMPRESSION
/// and BEST_COMPRESSION, or DEFAULT_COMPRESSION.
/// </param>
/// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception>
public Deflater(int lvl)
: this(lvl, false)
{
}
/// <summary>
/// Creates a new deflater with given compression level.
/// </summary>
/// <param name="level">
/// the compression level, a value between NO_COMPRESSION
/// and BEST_COMPRESSION.
/// </param>
/// <param name="noZlibHeaderOrFooter">
/// true, if we should suppress the Zlib/RFC1950 header at the
/// beginning and the adler checksum at the end of the output. This is
/// useful for the GZIP/PKZIP formats.
/// </param>
/// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception>
public Deflater(int level, bool noZlibHeaderOrFooter)
{
if (level == DEFAULT_COMPRESSION)
{
level = 6;
}
else if (level < NO_COMPRESSION || level > BEST_COMPRESSION)
{
throw new ArgumentOutOfRangeException("level");
}
pending = new DeflaterPending();
engine = new DeflaterEngine(pending);
this.noZlibHeaderOrFooter = noZlibHeaderOrFooter;
SetStrategy(DeflateStrategy.Default);
SetLevel(level);
Reset();
}
/// <summary>
/// Resets the deflater. The deflater acts afterwards as if it was
/// just created with the same compression level and strategy as it
/// had before.
/// </summary>
public void Reset()
{
state = (noZlibHeaderOrFooter ? BUSY_STATE : INIT_STATE);
totalOut = 0;
pending.Reset();
engine.Reset();
}
/// <summary>
/// Gets the current adler checksum of the data that was processed so far.
/// </summary>
public int Adler
{
get
{
return engine.Adler;
}
}
/// <summary>
/// Gets the number of input bytes processed so far.
/// </summary>
public int TotalIn
{
get
{
return engine.TotalIn;
}
}
/// <summary>
/// Gets the number of output bytes so far.
/// </summary>
public long TotalOut
{
get
{
return totalOut;
}
}
/// <summary>
/// Flushes the current input block. Further calls to deflate() will
/// produce enough output to inflate everything in the current input
/// block. This is not part of Sun's JDK so I have made it package
/// private. It is used by DeflaterOutputStream to implement
/// flush().
/// </summary>
public void Flush()
{
state |= IS_FLUSHING;
}
/// <summary>
/// Finishes the deflater with the current input block. It is an error
/// to give more input after this method was called. This method must
/// be called to force all bytes to be flushed.
/// </summary>
public void Finish()
{
state |= IS_FLUSHING | IS_FINISHING;
}
/// <summary>
/// Returns true if the stream was finished and no more output bytes
/// are available.
/// </summary>
public bool IsFinished
{
get
{
return state == FINISHED_STATE && pending.IsFlushed;
}
}
/// <summary>
/// Returns true, if the input buffer is empty.
/// You should then call setInput().
/// NOTE: This method can also return true when the stream
/// was finished.
/// </summary>
public bool IsNeedingInput
{
get
{
return engine.NeedsInput();
}
}
/// <summary>
/// Sets the data which should be compressed next. This should be only
/// called when needsInput indicates that more input is needed.
/// If you call setInput when needsInput() returns false, the
/// previous input that is still pending will be thrown away.
/// The given byte array should not be changed, before needsInput() returns
/// true again.
/// This call is equivalent to <code>setInput(input, 0, input.length)</code>.
/// </summary>
/// <param name="input">
/// the buffer containing the input data.
/// </param>
/// <exception cref="System.InvalidOperationException">
/// if the buffer was finished() or ended().
/// </exception>
public void SetInput(byte[] input)
{
SetInput(input, 0, input.Length);
}
/// <summary>
/// Sets the data which should be compressed next. This should be
/// only called when needsInput indicates that more input is needed.
/// The given byte array should not be changed, before needsInput() returns
/// true again.
/// </summary>
/// <param name="input">
/// the buffer containing the input data.
/// </param>
/// <param name="off">
/// the start of the data.
/// </param>
/// <param name="len">
/// the length of the data.
/// </param>
/// <exception cref="System.InvalidOperationException">
/// if the buffer was finished() or ended() or if previous input is still pending.
/// </exception>
public void SetInput(byte[] input, int off, int len)
{
if ((state & IS_FINISHING) != 0)
{
throw new InvalidOperationException("finish()/end() already called");
}
engine.SetInput(input, off, len);
}
/// <summary>
/// Sets the compression level. There is no guarantee of the exact
/// position of the change, but if you call this when needsInput is
/// true the change of compression level will occur somewhere near
/// before the end of the so far given input.
/// </summary>
/// <param name="lvl">
/// the new compression level.
/// </param>
public void SetLevel(int lvl)
{
if (lvl == DEFAULT_COMPRESSION)
{
lvl = 6;
}
else if (lvl < NO_COMPRESSION || lvl > BEST_COMPRESSION)
{
throw new ArgumentOutOfRangeException("lvl");
}
if (level != lvl)
{
level = lvl;
engine.SetLevel(lvl);
}
}
/// <summary>
/// Get current compression level
/// </summary>
/// <returns>Returns the current compression level</returns>
public int GetLevel()
{
return level;
}
/// <summary>
/// Sets the compression strategy. Strategy is one of
/// DEFAULT_STRATEGY, HUFFMAN_ONLY and FILTERED. For the exact
/// position where the strategy is changed, the same as for
/// setLevel() applies.
/// </summary>
/// <param name="strategy">
/// The new compression strategy.
/// </param>
public void SetStrategy(DeflateStrategy strategy)
{
engine.Strategy = strategy;
}
/// <summary>
/// Deflates the current input block with to the given array.
/// </summary>
/// <param name="output">
/// The buffer where compressed data is stored
/// </param>
/// <returns>
/// The number of compressed bytes added to the output, or 0 if either
/// needsInput() or finished() returns true or length is zero.
/// </returns>
public int Deflate(byte[] output)
{
return Deflate(output, 0, output.Length);
}
/// <summary>
/// Deflates the current input block to the given array.
/// </summary>
/// <param name="output">
/// Buffer to store the compressed data.
/// </param>
/// <param name="offset">
/// Offset into the output array.
/// </param>
/// <param name="length">
/// The maximum number of bytes that may be stored.
/// </param>
/// <returns>
/// The number of compressed bytes added to the output, or 0 if either
/// needsInput() or finished() returns true or length is zero.
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// If end() was previously called.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// If offset and/or length don't match the array length.
/// </exception>
public int Deflate(byte[] output, int offset, int length)
{
int origLength = length;
if (state == CLOSED_STATE)
{
throw new InvalidOperationException("Deflater closed");
}
if (state < BUSY_STATE)
{
/* output header */
int header = (DEFLATED +
((DeflaterConstants.MAX_WBITS - 8) << 4)) << 8;
int level_flags = (level - 1) >> 1;
if (level_flags < 0 || level_flags > 3)
{
level_flags = 3;
}
header |= level_flags << 6;
if ((state & IS_SETDICT) != 0)
{
/* Dictionary was set */
header |= DeflaterConstants.PRESET_DICT;
}
header += 31 - (header % 31);
pending.WriteShortMSB(header);
if ((state & IS_SETDICT) != 0)
{
int chksum = engine.Adler;
engine.ResetAdler();
pending.WriteShortMSB(chksum >> 16);
pending.WriteShortMSB(chksum & 0xffff);
}
state = BUSY_STATE | (state & (IS_FLUSHING | IS_FINISHING));
}
for (; ; )
{
int count = pending.Flush(output, offset, length);
offset += count;
totalOut += count;
length -= count;
if (length == 0 || state == FINISHED_STATE)
{
break;
}
if (!engine.Deflate((state & IS_FLUSHING) != 0, (state & IS_FINISHING) != 0))
{
if (state == BUSY_STATE)
{
/* We need more input now */
return origLength - length;
}
else if (state == FLUSHING_STATE)
{
if (level != NO_COMPRESSION)
{
/* We have to supply some lookahead. 8 bit lookahead
* is needed by the zlib inflater, and we must fill
* the next byte, so that all bits are flushed.
*/
int neededbits = 8 + ((-pending.BitCount) & 7);
while (neededbits > 0)
{
/* write a static tree block consisting solely of
* an EOF:
*/
pending.WriteBits(2, 10);
neededbits -= 10;
}
}
state = BUSY_STATE;
}
else if (state == FINISHING_STATE)
{
pending.AlignToByte();
// Compressed data is complete. Write footer information if required.
if (!noZlibHeaderOrFooter)
{
int adler = engine.Adler;
pending.WriteShortMSB(adler >> 16);
pending.WriteShortMSB(adler & 0xffff);
}
state = FINISHED_STATE;
}
}
}
return origLength - length;
}
/// <summary>
/// Sets the dictionary which should be used in the deflate process.
/// This call is equivalent to <code>setDictionary(dict, 0, dict.Length)</code>.
/// </summary>
/// <param name="dict">
/// the dictionary.
/// </param>
/// <exception cref="System.InvalidOperationException">
/// if setInput () or deflate () were already called or another dictionary was already set.
/// </exception>
public void SetDictionary(byte[] dict)
{
SetDictionary(dict, 0, dict.Length);
}
/// <summary>
/// Sets the dictionary which should be used in the deflate process.
/// The dictionary is a byte array containing strings that are
/// likely to occur in the data which should be compressed. The
/// dictionary is not stored in the compressed output, only a
/// checksum. To decompress the output you need to supply the same
/// dictionary again.
/// </summary>
/// <param name="dict">
/// The dictionary data
/// </param>
/// <param name="offset">
/// An offset into the dictionary.
/// </param>
/// <param name="length">
/// The length of the dictionary data to use
/// </param>
/// <exception cref="System.InvalidOperationException">
/// If setInput () or deflate () were already called or another dictionary was already set.
/// </exception>
public void SetDictionary(byte[] dict, int offset, int length)
{
if (state != INIT_STATE)
{
throw new InvalidOperationException();
}
state = SETDICT_STATE;
engine.SetDictionary(dict, offset, length);
}
}
}
| |
using System;
namespace Lucene.Net.Analysis.Ru
{
/// <summary>
/// RussianCharsets class contains encodings schemes (charsets) and ToLowerCase() method implementation
/// for russian characters in Unicode, KOI8 and CP1252.
/// Each encoding scheme contains lowercase (positions 0-31) and uppercase (position 32-63) characters.
/// One should be able to add other encoding schemes (like ISO-8859-5 or customized) by adding a new charset
/// and adding logic to ToLowerCase() method for that charset.
/// </summary>
public class RussianCharsets
{
/// <summary>
/// Unicode Russian charset (lowercase letters only)
/// </summary>
public static char[] UnicodeRussian = {
'\u0430',
'\u0431',
'\u0432',
'\u0433',
'\u0434',
'\u0435',
'\u0436',
'\u0437',
'\u0438',
'\u0439',
'\u043A',
'\u043B',
'\u043C',
'\u043D',
'\u043E',
'\u043F',
'\u0440',
'\u0441',
'\u0442',
'\u0443',
'\u0444',
'\u0445',
'\u0446',
'\u0447',
'\u0448',
'\u0449',
'\u044A',
'\u044B',
'\u044C',
'\u044D',
'\u044E',
'\u044F',
// upper case
'\u0410',
'\u0411',
'\u0412',
'\u0413',
'\u0414',
'\u0415',
'\u0416',
'\u0417',
'\u0418',
'\u0419',
'\u041A',
'\u041B',
'\u041C',
'\u041D',
'\u041E',
'\u041F',
'\u0420',
'\u0421',
'\u0422',
'\u0423',
'\u0424',
'\u0425',
'\u0426',
'\u0427',
'\u0428',
'\u0429',
'\u042A',
'\u042B',
'\u042C',
'\u042D',
'\u042E',
'\u042F'
};
/// <summary>
/// KOI8 charset
/// </summary>
public static char[] KOI8 = {
(char)0xc1,
(char)0xc2,
(char)0xd7,
(char)0xc7,
(char)0xc4,
(char)0xc5,
(char)0xd6,
(char)0xda,
(char)0xc9,
(char)0xca,
(char)0xcb,
(char)0xcc,
(char)0xcd,
(char)0xce,
(char)0xcf,
(char)0xd0,
(char)0xd2,
(char)0xd3,
(char)0xd4,
(char)0xd5,
(char)0xc6,
(char)0xc8,
(char)0xc3,
(char)0xde,
(char)0xdb,
(char)0xdd,
(char)0xdf,
(char)0xd9,
(char)0xd8,
(char)0xdc,
(char)0xc0,
(char)0xd1,
// upper case
(char)0xe1,
(char)0xe2,
(char)0xf7,
(char)0xe7,
(char)0xe4,
(char)0xe5,
(char)0xf6,
(char)0xfa,
(char)0xe9,
(char)0xea,
(char)0xeb,
(char)0xec,
(char)0xed,
(char)0xee,
(char)0xef,
(char)0xf0,
(char)0xf2,
(char)0xf3,
(char)0xf4,
(char)0xf5,
(char)0xe6,
(char)0xe8,
(char)0xe3,
(char)0xfe,
(char)0xfb,
(char)0xfd,
(char)0xff,
(char)0xf9,
(char)0xf8,
(char)0xfc,
(char)0xe0,
(char)0xf1
};
/// <summary>
/// CP1251 Charset
/// </summary>
public static char[] CP1251 = {
(char)0xE0,
(char)0xE1,
(char)0xE2,
(char)0xE3,
(char)0xE4,
(char)0xE5,
(char)0xE6,
(char)0xE7,
(char)0xE8,
(char)0xE9,
(char)0xEA,
(char)0xEB,
(char)0xEC,
(char)0xED,
(char)0xEE,
(char)0xEF,
(char)0xF0,
(char)0xF1,
(char)0xF2,
(char)0xF3,
(char)0xF4,
(char)0xF5,
(char)0xF6,
(char)0xF7,
(char)0xF8,
(char)0xF9,
(char)0xFA,
(char)0xFB,
(char)0xFC,
(char)0xFD,
(char)0xFE,
(char)0xFF,
// upper case
(char)0xC0,
(char)0xC1,
(char)0xC2,
(char)0xC3,
(char)0xC4,
(char)0xC5,
(char)0xC6,
(char)0xC7,
(char)0xC8,
(char)0xC9,
(char)0xCA,
(char)0xCB,
(char)0xCC,
(char)0xCD,
(char)0xCE,
(char)0xCF,
(char)0xD0,
(char)0xD1,
(char)0xD2,
(char)0xD3,
(char)0xD4,
(char)0xD5,
(char)0xD6,
(char)0xD7,
(char)0xD8,
(char)0xD9,
(char)0xDA,
(char)0xDB,
(char)0xDC,
(char)0xDD,
(char)0xDE,
(char)0xDF
};
public static char ToLowerCase(char letter, char[] charset)
{
if (charset == UnicodeRussian)
{
if (letter >= '\u0430' && letter <= '\u044F')
{
return letter;
}
if (letter >= '\u0410' && letter <= '\u042F')
{
return (char) (letter + 32);
}
}
if (charset == KOI8)
{
if (letter >= 0xe0 && letter <= 0xff)
{
return (char) (letter - 32);
}
if (letter >= 0xc0 && letter <= 0xdf)
{
return letter;
}
}
if (charset == CP1251)
{
if (letter >= 0xC0 && letter <= 0xDF)
{
return (char) (letter + 32);
}
if (letter >= 0xE0 && letter <= 0xFF)
{
return letter;
}
}
return Char.ToLower(letter);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
namespace PosterAlignment.InputUtilities
{
[RequireComponent(typeof(MouseStateManager))]
[RequireComponent(typeof(JoystickStateManager))]
[RequireComponent(typeof(GestureStateManager))]
[AddComponentMenu("Event/Custom HoloLens Input Module")]
public class CustomHoloLensInputModule : PointerInputModule
{
public StateManager.InputType InputType = StateManager.InputType.Gesture;
public bool CopyToMiddleButton = false;
public bool CopyToRightButton = false;
private readonly static MouseState inputState = new MouseState();
private MouseStateManager mouseManager;
private JoystickStateManager joystickManager;
private GestureStateManager gestureManager;
private static Dictionary<int, WorldPointerEventData> worldPointerEventData
= new Dictionary<int, WorldPointerEventData>();
private static RaycastResult emptyResult;
public static RaycastResult GetRaycastResult(int buttonId = -1)
{
WorldPointerEventData data = null;
if (worldPointerEventData.TryGetValue(buttonId, out data))
{
return data.pointerCurrentRaycast;
}
return emptyResult;
}
public static MouseButtonEventData GetInputButtonState(PointerEventData.InputButton button = PointerEventData.InputButton.Left)
{
return inputState.GetButtonState(button).eventData;
}
private bool forceModuleActive;
public bool ForceModuleActive
{
get { return this.forceModuleActive; }
set { this.forceModuleActive = value; }
}
protected override void Awake()
{
base.Awake();
emptyResult = new RaycastResult();
if (null == Camera.main)
{
return;
}
// main camera needs a 3d raycaster
var raycaster = Camera.main.gameObject.GetComponentInParent<PhysicsRaycaster>();
if (null == raycaster)
{
Camera.main.gameObject.AddComponent<PhysicsRaycaster>();
// remove Ignore Raycast layer
raycaster = Camera.main.gameObject.GetComponent<PhysicsRaycaster>();
if (null != raycaster)
{
raycaster.eventMask = raycaster.eventMask & ~(1 << LayerMask.NameToLayer("Ignore Raycast"));
}
}
}
public override bool IsModuleSupported()
{
var supported = this.forceModuleActive
|| this.gestureManager.IsSupported()
|| this.mouseManager.IsSupported()
|| this.joystickManager.IsSupported();
return supported;
}
public override bool ShouldActivateModule()
{
if (!base.ShouldActivateModule())
{
return false;
}
var shouldActivate = this.forceModuleActive;
shouldActivate |= this.gestureManager.ShouldActivate();
shouldActivate |= this.mouseManager.ShouldActivate();
shouldActivate |= this.joystickManager.ShouldActivate();
return shouldActivate;
}
public override void ActivateModule()
{
base.ActivateModule();
var toSelect = this.eventSystem.currentSelectedGameObject;
if (toSelect == null)
{
toSelect = this.eventSystem.firstSelectedGameObject;
}
this.eventSystem.SetSelectedGameObject(toSelect, this.GetBaseEventData());
if (!this.EnsureModules())
{
return;
}
this.gestureManager.ActivateModule();
this.mouseManager.ActivateModule();
this.joystickManager.ActivateModule();
}
public override void DeactivateModule()
{
base.DeactivateModule();
// clear selection
var baseEventData = GetBaseEventData();
foreach (var pointer in worldPointerEventData.Values)
{
HandlePointerExitAndEnter(pointer, null);
}
worldPointerEventData.Clear();
eventSystem.SetSelectedGameObject(null, baseEventData);
if (!this.EnsureModules())
{
return;
}
this.gestureManager.DeactivateModule();
this.mouseManager.DeactivateModule();
this.joystickManager.DeactivateModule();
}
public override void UpdateModule()
{
StateManager.CheckForScreenUpdates();
if (!this.EnsureModules())
{
return;
}
this.gestureManager.UpdateModule();
this.mouseManager.UpdateModule();
this.joystickManager.UpdateModule();
}
public override void Process()
{
bool usedEvent = this.SendUpdateEventToSelectedObject();
if (this.eventSystem.sendNavigationEvents)
{
if (!usedEvent)
{
usedEvent |= this.SendMoveEvent();
}
if (!usedEvent)
{
this.SendSubmitCancelEvent();
}
}
this.ProcessInputEventData();
}
public override string ToString()
{
var sb = new System.Text.StringBuilder("<b>Pointer Input Module of type: </b>" + GetType());
sb.AppendLine();
foreach (var pointer in worldPointerEventData)
{
if (pointer.Value == null)
continue;
sb.AppendLine("<B>Pointer:</b> " + pointer.Key);
sb.AppendLine(pointer.Value.ToString());
}
return sb.ToString();
}
// todo: refactor to be a generic list
private bool EnsureModules()
{
if (this.mouseManager == null)
{
this.mouseManager = this.gameObject.GetComponent<MouseStateManager>();
}
if (this.joystickManager == null)
{
this.joystickManager = this.gameObject.GetComponent<JoystickStateManager>();
}
if (this.gestureManager == null)
{
this.gestureManager = this.gameObject.GetComponent<GestureStateManager>();
}
return (this.mouseManager != null && this.joystickManager != null && this.gestureManager != null);
}
// Send update to selected object
private bool SendUpdateEventToSelectedObject()
{
if (this.eventSystem.currentSelectedGameObject == null)
{
return false;
}
var data = this.GetBaseEventData();
ExecuteEvents.Execute(this.eventSystem.currentSelectedGameObject, data, ExecuteEvents.updateSelectedHandler);
return data.used;
}
// sends submit/cancel action
private bool SendSubmitCancelEvent()
{
// eventSystem must have a selected object
if (this.eventSystem.currentSelectedGameObject == null)
{
return false;
}
var data = this.GetBaseEventData();
// Submit, only send once
bool doSubmit = this.joystickManager.ShouldSubmit();
if (!doSubmit)
{
doSubmit |= this.mouseManager.ShouldSubmit(); // should be false, but may want to support multi-button type mouse
}
if (!doSubmit)
{
doSubmit |= this.gestureManager.ShouldSubmit(); // could be true based on voice
}
if (doSubmit)
{
ExecuteEvents.Execute(this.eventSystem.currentSelectedGameObject, data, ExecuteEvents.submitHandler);
}
// Cancel, only send once
bool doCancel = this.joystickManager.ShouldCancel();
if (!doCancel)
{
doCancel |= this.mouseManager.ShouldCancel();
}
if (!doCancel)
{
doCancel |= this.gestureManager.ShouldCancel();
}
if (doCancel)
{
ExecuteEvents.Execute(this.eventSystem.currentSelectedGameObject, data, ExecuteEvents.cancelHandler);
}
return data.used;
}
// sends navigation event within a canvas
private bool SendMoveEvent()
{
// eventSystem must have a selected object
if (this.eventSystem.currentSelectedGameObject == null)
{
return false;
}
Vector2 movement = Vector2.zero;
bool doMove = this.joystickManager.ShouldMove(out movement);
if (!doMove)
{
doMove |= this.mouseManager.ShouldMove(out movement);
}
if (!doMove)
{
doMove |= this.gestureManager.ShouldMove(out movement);
}
// convert event data to axisEventData
// movement shold be normalized between -1.0f to 1.0f
var axisEventData = this.GetAxisEventData(movement.x, movement.y, 0.6f);
if (doMove)
{
ExecuteEvents.Execute(this.eventSystem.currentSelectedGameObject, axisEventData, ExecuteEvents.moveHandler);
}
return axisEventData.used;
}
// Process the pointer event data
private void ProcessInputEventData()
{
GetPointerEventData();
var buttonEventData = GetInputButtonState(PointerEventData.InputButton.Left);
// Process primary input
this.ProcessPress(buttonEventData.buttonData, buttonEventData.PressedThisFrame(), buttonEventData.ReleasedThisFrame());
this.ProcessMove(buttonEventData.buttonData);
this.ProcessDrag(buttonEventData.buttonData);
// Now process right / middle input
buttonEventData = GetInputButtonState(PointerEventData.InputButton.Right);
this.ProcessPress(buttonEventData.buttonData, buttonEventData.PressedThisFrame(), buttonEventData.ReleasedThisFrame());
this.ProcessDrag(buttonEventData.buttonData);
buttonEventData = GetInputButtonState(PointerEventData.InputButton.Middle);
this.ProcessPress(buttonEventData.buttonData, buttonEventData.PressedThisFrame(), buttonEventData.ReleasedThisFrame());
this.ProcessDrag(buttonEventData.buttonData);
// process scroll event
buttonEventData = GetInputButtonState(PointerEventData.InputButton.Left);
if (!Mathf.Approximately(buttonEventData.buttonData.scrollDelta.sqrMagnitude, 0.0f))
{
var scrollHandler = ExecuteEvents.GetEventHandler<IScrollHandler>(buttonEventData.buttonData.pointerCurrentRaycast.gameObject);
ExecuteEvents.ExecuteHierarchy(scrollHandler, buttonEventData.buttonData, ExecuteEvents.scrollHandler);
}
}
// Process the press
private void ProcessPress(PointerEventData pointerEvent, bool pressedThisFrame, bool releasedThisFrame)
{
var currentOverGo = pointerEvent.pointerCurrentRaycast.gameObject;
// PointerDown/PointerClick event
if (pressedThisFrame)
{
pointerEvent.eligibleForClick = true;
pointerEvent.delta = Vector2.zero;
pointerEvent.dragging = false;
pointerEvent.useDragThreshold = true;
pointerEvent.pressPosition = pointerEvent.position;
pointerEvent.pointerPressRaycast = pointerEvent.pointerCurrentRaycast;
this.DeselectIfSelectionChanged(currentOverGo, pointerEvent);
// search for the control that will receive the press
var newPressed = ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.pointerDownHandler);
// didnt find a press handler... search for a click handler
if (newPressed == null)
{
newPressed = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo);
}
float time = Time.unscaledTime;
if (newPressed == pointerEvent.lastPress)
{
var diffTime = time - pointerEvent.clickTime;
if (diffTime < 0.3f)
{
++pointerEvent.clickCount;
}
else
{
pointerEvent.clickCount = 1;
}
pointerEvent.clickTime = time;
}
else
{
pointerEvent.clickCount = 1;
}
pointerEvent.pointerPress = newPressed;
pointerEvent.rawPointerPress = currentOverGo;
pointerEvent.clickTime = time;
// Save the drag handler as well
pointerEvent.pointerDrag = ExecuteEvents.GetEventHandler<IDragHandler>(currentOverGo);
if (pointerEvent.pointerDrag != null)
{
ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.initializePotentialDrag);
}
}
// PointerUp notification
if (releasedThisFrame)
{
ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerUpHandler);
// see if we released on the same element that was clicked before
var pointerUpHandler = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo);
// PointerClick and Drop events
if (pointerEvent.pointerPress == pointerUpHandler && pointerEvent.eligibleForClick)
{
ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerClickHandler);
}
else if (pointerEvent.pointerDrag != null && pointerEvent.dragging)
{
ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.dropHandler);
}
// reset pressed state
pointerEvent.eligibleForClick = false;
pointerEvent.pointerPress = null;
pointerEvent.rawPointerPress = null;
// send endDrag event
if (pointerEvent.pointerDrag != null && pointerEvent.dragging)
{
ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.endDragHandler);
}
// reset dragging state
pointerEvent.dragging = false;
pointerEvent.pointerDrag = null;
// if the current object is not the previous entered object, then set that now
if (currentOverGo != pointerEvent.pointerEnter)
{
this.HandlePointerExitAndEnter(pointerEvent, null);
this.HandlePointerExitAndEnter(pointerEvent, currentOverGo);
}
}
}
private void GetPointerEventData()
{
// get eventData for left button first
WorldPointerEventData leftData;
bool created = this.GetWorldPointerData(kMouseLeftId, out leftData, true);
if(!created)
{
// first time through
}
leftData.Reset();
// set the event data for screenPosition
SetPositionEventData(ref leftData);
// set the raycast result
SetRaycastResult(ref leftData);
// set scrollDelta event data
SetScrollDeltaEventData(ref leftData);
// update the delta and scroll for the appropriate input for drag events
leftData.button = PointerEventData.InputButton.Left;
SetDeltaEventData(ref leftData);
// copy the apropriate data into right and middle slots
WorldPointerEventData rightData;
this.GetWorldPointerData(kMouseRightId, out rightData, true);
if (CopyToRightButton)
{
CopyFromTo(leftData, rightData);
}
rightData.button = PointerEventData.InputButton.Right;
//SetDeltaEventData(ref rightData);
WorldPointerEventData middleData;
this.GetWorldPointerData(kMouseMiddleId, out middleData, true);
if (CopyToMiddleButton)
{
CopyFromTo(leftData, middleData);
}
middleData.button = PointerEventData.InputButton.Middle;
//SetDeltaEventData(ref middleData);
inputState.SetButtonState(PointerEventData.InputButton.Left, this.GetStateforButton(leftData.button), leftData);
inputState.SetButtonState(PointerEventData.InputButton.Right, this.GetStateforButton(rightData.button), rightData);
inputState.SetButtonState(PointerEventData.InputButton.Middle, this.GetStateforButton(middleData.button), middleData);
}
private bool GetWorldPointerData(int buttonId, out WorldPointerEventData data, bool create)
{
if (!worldPointerEventData.TryGetValue(buttonId, out data) && create)
{
data = new WorldPointerEventData(eventSystem)
{
pointerId = buttonId,
};
worldPointerEventData.Add(buttonId, data);
return true;
}
return false;
}
private void SetPositionEventData(ref WorldPointerEventData eventData)
{
// get position for raycast
Vector2 pointerPos = this.gestureManager.ScreenPosition;
Vector3 worldPos = this.gestureManager.WorldScreenPosition;
switch (this.InputType)
{
case StateManager.InputType.Mouse:
if(this.mouseManager.IsSupported() || this.mouseManager.ShouldActivate())
{
pointerPos = this.mouseManager.ScreenPosition;
worldPos = this.mouseManager.WorldScreenPosition;
}
break;
case StateManager.InputType.Joystick:
if (this.joystickManager.IsSupported() || this.joystickManager.ShouldActivate())
{
pointerPos = this.joystickManager.ScreenPosition;
worldPos = this.joystickManager.WorldScreenPosition;
}
break;
}
// set the event position
eventData.inputType = this.InputType;
eventData.position = pointerPos; // screenPosition
eventData.worldPosition = worldPos; // position on near plane
}
private void SetRaycastResult(ref WorldPointerEventData eventData)
{
// raycast the position for any results
this.eventSystem.RaycastAll(eventData, this.m_RaycastResultCache);
// use first object in cache
var raycast = FindFirstRaycast(this.m_RaycastResultCache);
// clear the cache
this.m_RaycastResultCache.Clear();
// correct raycast result
if (raycast.isValid)
{
// for UI objects raycast.worldPosition == Vector3.zero, have to raycast the screenPosition
if (raycast.worldPosition == Vector3.zero)
{
Ray ray = Camera.main.ScreenPointToRay(raycast.screenPosition);
raycast.worldPosition = eventData.worldPosition + (ray.direction * raycast.distance);
}
if (raycast.worldNormal == Vector3.zero)
{
raycast.worldNormal = -raycast.gameObject.transform.forward;
}
}
else
{
Ray ray = Camera.main.ScreenPointToRay(eventData.position);
raycast.worldPosition = Camera.main.transform.position + ray.direction;
raycast.worldNormal = -ray.direction;
}
// set the raycast data
eventData.pointerCurrentRaycast = raycast;
}
private void SetScrollDeltaEventData(ref WorldPointerEventData eventData)
{
eventData.scrollDelta = this.gestureManager.ScrollDelta;
if (this.joystickManager.ShouldActivate())
{
eventData.scrollDelta = this.joystickManager.ScrollDelta;
}
if (this.mouseManager.ShouldActivate())
{
eventData.scrollDelta = this.mouseManager.ScrollDelta;
}
}
private void SetDeltaEventData(ref WorldPointerEventData eventData)
{
eventData.useDragThreshold = false;
eventData.delta = this.gestureManager.ScreenDelta;
eventData.worldDelta = this.gestureManager.WorldDelta;
if (this.joystickManager.ShouldActivate())
{
eventData.delta = this.joystickManager.ScreenDelta;
eventData.worldDelta = this.joystickManager.WorldDelta;
}
if (this.mouseManager.ShouldActivate())
{
eventData.delta = this.mouseManager.ScreenDelta;
eventData.worldDelta = this.mouseManager.WorldDelta;
}
}
private PointerEventData.FramePressState GetStateforButton(PointerEventData.InputButton button)
{
var pressed = this.joystickManager.IsPressed(button) || this.mouseManager.IsPressed(button) || this.gestureManager.IsPressed(button);
var released = this.joystickManager.IsReleased(button) || this.mouseManager.IsReleased(button) || this.gestureManager.IsReleased(button);
this.joystickManager.ResetButtonState(button);
this.mouseManager.ResetButtonState(button);
this.gestureManager.ResetButtonState(button);
if (pressed && released)
{
return PointerEventData.FramePressState.PressedAndReleased;
}
if (pressed)
{
return PointerEventData.FramePressState.Pressed;
}
if (released)
{
return PointerEventData.FramePressState.Released;
}
return PointerEventData.FramePressState.NotChanged;
}
}
}
| |
// 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.Test.ModuleCore;
using System;
using System.IO;
using System.Text;
using System.Xml;
namespace CoreXml.Test.XLinq
{
public partial class XNodeReaderFunctionalTests : TestModule
{
public partial class XNodeReaderTests : XLinqTestCase
{
public partial class TCReadContentAsBinHex : BridgeHelpers
{
public const string ST_ELEM_NAME1 = "ElemAll";
public const string ST_ELEM_NAME2 = "ElemEmpty";
public const string ST_ELEM_NAME3 = "ElemNum";
public const string ST_ELEM_NAME4 = "ElemText";
public const string ST_ELEM_NAME5 = "ElemNumText";
public const string ST_ELEM_NAME6 = "ElemLong";
public const string strTextBinHex = "ABCDEF";
public const string strNumBinHex = "0123456789";
public override void Init()
{
base.Init();
CreateBinHexTestFile(pBinHexXml);
}
public override void Terminate()
{
base.Terminate();
}
private bool VerifyInvalidReadBinHex(int iBufferSize, int iIndex, int iCount, Type exceptionType)
{
bool bPassed = false;
byte[] buffer = new byte[iBufferSize];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return true;
try
{
DataReader.ReadContentAsBinHex(buffer, iIndex, iCount);
}
catch (Exception e)
{
bPassed = (e.GetType().ToString() == exceptionType.ToString());
if (!bPassed)
{
TestLog.WriteLine("Actual exception:{0}", e.GetType().ToString());
TestLog.WriteLine("Expected exception:{0}", exceptionType.ToString());
}
}
return bPassed;
}
protected void TestInvalidNodeType(XmlNodeType nt)
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnNodeType(DataReader, nt);
string name = DataReader.Name;
string value = DataReader.Value;
byte[] buffer = new byte[1];
if (!DataReader.CanReadBinaryContent) return;
try
{
int nBytes = DataReader.ReadContentAsBinHex(buffer, 0, 1);
}
catch (InvalidOperationException)
{
return;
}
TestLog.Compare(false, "Invalid OP exception not thrown on wrong nodetype");
}
//[Variation("ReadBinHex Element with all valid value")]
public void TestReadBinHex_1()
{
int binhexlen = 0;
byte[] binhex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
binhexlen = DataReader.ReadContentAsBinHex(binhex, 0, binhex.Length);
string strActbinhex = "";
for (int i = 0; i < binhexlen; i = i + 2)
{
strActbinhex += System.BitConverter.ToChar(binhex, i);
}
TestLog.Compare(strActbinhex, (strNumBinHex + strTextBinHex), "1. Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all valid Num value", Priority = 0)]
public void TestReadBinHex_2()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME3);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, strNumBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all valid Text value")]
public void TestReadBinHex_3()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, strTextBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element on CDATA", Priority = 0)]
public void TestReadBinHex_4()
{
int BinHexlen = 0;
byte[] BinHex = new byte[3];
string xmlStr = "<root><![CDATA[ABCDEF]]></root>";
XmlReader DataReader = GetReader(new StringReader(xmlStr));
PositionOnElement(DataReader, "root");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
TestLog.Compare(BinHexlen, 3, "BinHex");
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
TestLog.Compare(BinHexlen, 0, "BinHex");
DataReader.Read();
TestLog.Compare(DataReader.NodeType, XmlNodeType.None, "Not on none");
}
//[Variation("ReadBinHex Element with all valid value (from concatenation), Priority=0")]
public void TestReadBinHex_5()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME5);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, (strNumBinHex + strTextBinHex), "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all long valid value (from concatenation)")]
public void TestReadBinHex_6()
{
int BinHexlen = 0;
byte[] BinHex = new byte[2000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME6);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
string strExpBinHex = "";
for (int i = 0; i < 10; i++)
strExpBinHex += (strNumBinHex + strTextBinHex);
TestLog.Compare(strActBinHex, strExpBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex with count > buffer size")]
public void TestReadBinHex_7()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 6, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with count < 0")]
public void TestReadBinHex_8()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 2, -1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index > buffer size")]
public void vReadBinHex_9()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 5, 1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index < 0")]
public void TestReadBinHex_10()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, -1, 1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index + count exceeds buffer")]
public void TestReadBinHex_11()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 10, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex index & count =0")]
public void TestReadBinHex_12()
{
byte[] buffer = new byte[5];
int iCount = 0;
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
try
{
iCount = DataReader.ReadContentAsBinHex(buffer, 0, 0);
}
catch (Exception e)
{
TestLog.WriteLine(e.ToString());
throw new TestException(TestResult.Failed, "");
}
TestLog.Compare(iCount, 0, "has to be zero");
}
//[Variation("ReadBinHex Element multiple into same buffer (using offset), Priority=0")]
public void TestReadBinHex_13()
{
int BinHexlen = 10;
byte[] BinHex = new byte[BinHexlen];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
string strActbinhex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
DataReader.ReadContentAsBinHex(BinHex, i, 2);
strActbinhex = (System.BitConverter.ToChar(BinHex, i)).ToString();
TestLog.Compare(string.Compare(strActbinhex, 0, strTextBinHex, i / 2, 1), 0, "Compare All Valid Base64");
}
}
//[Variation("ReadBinHex with buffer == null")]
public void TestReadBinHex_14()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
try
{
DataReader.ReadContentAsBinHex(null, 0, 0);
}
catch (ArgumentNullException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadBinHex after failed ReadBinHex")]
public void TestReadBinHex_15()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, "ElemErr");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = 0;
try
{
nRead = DataReader.ReadContentAsBinHex(buffer, 0, 1);
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
int idx = e.Message.IndexOf("a&");
TestLog.Compare(idx >= 0, "msg");
CheckXmlException("Xml_UserException", e, 1, 968);
}
}
//[Variation("Read after partial ReadBinHex")]
public void TestReadBinHex_16()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, "ElemNum");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = DataReader.ReadContentAsBinHex(buffer, 0, 8);
TestLog.Compare(nRead, 8, "0");
DataReader.Read();
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Element, "ElemText", string.Empty), "1vn");
}
//[Variation("Current node on multiple calls")]
public void TestReadBinHex_17()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, "ElemNum");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[30];
int nRead = DataReader.ReadContentAsBinHex(buffer, 0, 2);
TestLog.Compare(nRead, 2, "0");
nRead = DataReader.ReadContentAsBinHex(buffer, 0, 19);
TestLog.Compare(nRead, 18, "1");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.EndElement, "ElemNum", string.Empty), "1vn");
}
//[Variation("ReadBinHex with whitespace")]
public void TestTextReadBinHex_21()
{
byte[] buffer = new byte[1];
string strxml = "<abc> 1 1 B </abc>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadContentAsBinHex(buffer, 0, 1)) > 0)
result += nRead;
TestLog.Compare(result, 1, "res");
TestLog.Compare(buffer[0], (byte)17, "buffer[0]");
}
//[Variation("ReadBinHex with odd number of chars")]
public void TestTextReadBinHex_22()
{
byte[] buffer = new byte[1];
string strxml = "<abc>11B</abc>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadContentAsBinHex(buffer, 0, 1)) > 0)
result += nRead;
TestLog.Compare(result, 1, "res");
TestLog.Compare(buffer[0], (byte)17, "buffer[0]");
}
//[Variation("ReadBinHex when end tag doesn't exist")]
public void TestTextReadBinHex_23()
{
byte[] buffer = new byte[5000];
string strxml = "<B>" + new string('A', 5000);
try
{
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "B");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
DataReader.ReadContentAsBinHex(buffer, 0, 5000);
TestLog.WriteLine("Accepted incomplete element");
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004);
}
}
//[Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes going Whidbey to Everett")]
public void TestTextReadBinHex_24()
{
string filename = Path.Combine("TestData", "XmlReader", "Common", "Bug99148.xml");
XmlReader DataReader = GetReader(filename);
DataReader.MoveToContent();
int bytes = -1;
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
StringBuilder output = new StringBuilder();
while (bytes != 0)
{
byte[] bbb = new byte[1024];
bytes = DataReader.ReadContentAsBinHex(bbb, 0, bbb.Length);
for (int i = 0; i < bytes; i++)
{
output.AppendFormat(bbb[i].ToString());
}
}
if (TestLog.Compare(output.ToString().Length, 1735, "Expected Length : 1735"))
return;
else
throw new TestException(TestResult.Failed, "");
}
//[Variation("DebugAssert in ReadContentAsBinHex")]
public void DebugAssertInReadContentAsBinHex()
{
XmlReader DataReader = GetReaderStr(@"<root>
<boo>hey</boo>
</root>");
byte[] buffer = new byte[5];
int iCount = 0;
while (DataReader.Read())
{
if (DataReader.NodeType == XmlNodeType.Element)
break;
}
if (!DataReader.CanReadBinaryContent) return;
DataReader.Read();
iCount = DataReader.ReadContentAsBinHex(buffer, 0, 0);
}
}
//[TestCase(Name = "ReadElementContentAsBinHex", Desc = "ReadElementContentAsBinHex")]
public partial class TCReadElementContentAsBinHex : BridgeHelpers
{
public const string ST_ELEM_NAME1 = "ElemAll";
public const string ST_ELEM_NAME2 = "ElemEmpty";
public const string ST_ELEM_NAME3 = "ElemNum";
public const string ST_ELEM_NAME4 = "ElemText";
public const string ST_ELEM_NAME5 = "ElemNumText";
public const string ST_ELEM_NAME6 = "ElemLong";
public const string strTextBinHex = "ABCDEF";
public const string strNumBinHex = "0123456789";
public override void Init()
{
base.Init();
CreateBinHexTestFile(pBinHexXml);
}
public override void Terminate()
{
base.Terminate();
}
private bool VerifyInvalidReadBinHex(int iBufferSize, int iIndex, int iCount, Type exceptionType)
{
bool bPassed = false;
byte[] buffer = new byte[iBufferSize];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
if (!DataReader.CanReadBinaryContent) return true;
try
{
DataReader.ReadElementContentAsBinHex(buffer, iIndex, iCount);
}
catch (Exception e)
{
bPassed = (e.GetType().ToString() == exceptionType.ToString());
if (!bPassed)
{
TestLog.WriteLine("Actual exception:{0}", e.GetType().ToString());
TestLog.WriteLine("Expected exception:{0}", exceptionType.ToString());
}
}
return bPassed;
}
protected void TestInvalidNodeType(XmlNodeType nt)
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnNodeType(DataReader, nt);
string name = DataReader.Name;
string value = DataReader.Value;
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[1];
try
{
int nBytes = DataReader.ReadElementContentAsBinHex(buffer, 0, 1);
}
catch (InvalidOperationException)
{
return;
}
TestLog.Compare(false, "Invalid OP exception not thrown on wrong nodetype");
}
//[Variation("ReadBinHex Element with all valid value")]
public void TestReadBinHex_1()
{
int binhexlen = 0;
byte[] binhex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
if (!DataReader.CanReadBinaryContent) return;
binhexlen = DataReader.ReadElementContentAsBinHex(binhex, 0, binhex.Length);
string strActbinhex = "";
for (int i = 0; i < binhexlen; i = i + 2)
{
strActbinhex += System.BitConverter.ToChar(binhex, i);
}
TestLog.Compare(strActbinhex, (strNumBinHex + strTextBinHex), "1. Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all valid Num value", Priority = 0)]
public void TestReadBinHex_2()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME3);
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, strNumBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all valid Text value")]
public void TestReadBinHex_3()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, strTextBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with Comments and PIs", Priority = 0)]
public void TestReadBinHex_4()
{
int BinHexlen = 0;
byte[] BinHex = new byte[3];
XmlReader DataReader = GetReader(new StringReader("<root>AB<!--Comment-->CD<?pi target?>EF</root>"));
PositionOnElement(DataReader, "root");
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length);
TestLog.Compare(BinHexlen, 3, "BinHex");
}
//[Variation("ReadBinHex Element with all valid value (from concatenation), Priority=0")]
public void TestReadBinHex_5()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME5);
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, (strNumBinHex + strTextBinHex), "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all long valid value (from concatenation)")]
public void TestReadBinHex_6()
{
int BinHexlen = 0;
byte[] BinHex = new byte[2000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME6);
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
string strExpBinHex = "";
for (int i = 0; i < 10; i++)
strExpBinHex += (strNumBinHex + strTextBinHex);
TestLog.Compare(strActBinHex, strExpBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex with count > buffer size")]
public void TestReadBinHex_7()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 6, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with count < 0")]
public void TestReadBinHex_8()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 2, -1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index > buffer size")]
public void vReadBinHex_9()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 5, 1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index < 0")]
public void TestReadBinHex_10()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, -1, 1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index + count exceeds buffer")]
public void TestReadBinHex_11()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 10, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex index & count =0")]
public void TestReadBinHex_12()
{
byte[] buffer = new byte[5];
int iCount = 0;
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
if (!DataReader.CanReadBinaryContent) return;
try
{
iCount = DataReader.ReadElementContentAsBinHex(buffer, 0, 0);
}
catch (Exception e)
{
TestLog.WriteLine(e.ToString());
throw new TestException(TestResult.Failed, "");
}
TestLog.Compare(iCount, 0, "has to be zero");
}
//[Variation("ReadBinHex Element multiple into same buffer (using offset), Priority=0")]
public void TestReadBinHex_13()
{
int BinHexlen = 10;
byte[] BinHex = new byte[BinHexlen];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
if (!DataReader.CanReadBinaryContent) return;
string strActbinhex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
DataReader.ReadElementContentAsBinHex(BinHex, i, 2);
strActbinhex = (System.BitConverter.ToChar(BinHex, i)).ToString();
TestLog.Compare(string.Compare(strActbinhex, 0, strTextBinHex, i / 2, 1), 0, "Compare All Valid Base64");
}
}
//[Variation("ReadBinHex with buffer == null")]
public void TestReadBinHex_14()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
if (!DataReader.CanReadBinaryContent) return;
try
{
DataReader.ReadElementContentAsBinHex(null, 0, 0);
}
catch (ArgumentNullException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadBinHex after failed ReadBinHex")]
public void TestReadBinHex_15()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, "ElemErr");
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = 0;
try
{
nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 1);
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
int idx = e.Message.IndexOf("a&");
TestLog.Compare(idx >= 0, "msg");
CheckXmlException("Xml_UserException", e, 1, 968);
}
}
//[Variation("Read after partial ReadBinHex")]
public void TestReadBinHex_16()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, "ElemNum");
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 8);
TestLog.Compare(nRead, 8, "0");
DataReader.Read();
TestLog.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on text node");
}
//[Variation("ReadBinHex with whitespace")]
public void TestTextReadBinHex_21()
{
byte[] buffer = new byte[1];
string strxml = "<abc> 1 1 B </abc>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
if (!DataReader.CanReadBinaryContent) return;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 1)) > 0)
result += nRead;
TestLog.Compare(result, 1, "res");
TestLog.Compare(buffer[0], (byte)17, "buffer[0]");
}
//[Variation("ReadBinHex with odd number of chars")]
public void TestTextReadBinHex_22()
{
byte[] buffer = new byte[1];
string strxml = "<abc>11B</abc>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
if (!DataReader.CanReadBinaryContent) return;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 1)) > 0)
result += nRead;
TestLog.Compare(result, 1, "res");
TestLog.Compare(buffer[0], (byte)17, "buffer[0]");
}
//[Variation("ReadBinHex when end tag doesn't exist")]
public void TestTextReadBinHex_23()
{
byte[] buffer = new byte[5000];
string strxml = "<B>" + new string('A', 5000);
try
{
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "B");
DataReader.ReadElementContentAsBinHex(buffer, 0, 5000);
TestLog.WriteLine("Accepted incomplete element");
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004);
}
}
//[Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes going Whidbey to Everett")]
public void TestTextReadBinHex_24()
{
string filename = Path.Combine("TestData", "XmlReader", "Common", "Bug99148.xml");
XmlReader DataReader = GetReader(filename);
DataReader.MoveToContent();
if (!DataReader.CanReadBinaryContent) return;
int bytes = -1;
StringBuilder output = new StringBuilder();
while (bytes != 0)
{
byte[] bbb = new byte[1024];
bytes = DataReader.ReadElementContentAsBinHex(bbb, 0, bbb.Length);
for (int i = 0; i < bytes; i++)
{
output.AppendFormat(bbb[i].ToString());
}
}
if (TestLog.Compare(output.ToString().Length, 1735, "Expected Length : 1735"))
return;
else
throw new TestException(TestResult.Failed, "");
}
//[Variation("SubtreeReader inserted attributes don't work with ReadContentAsBinHex")]
public void TestTextReadBinHex_25()
{
string strxml = "<root xmlns='0102030405060708090a0B0c'><bar/></root>";
using (XmlReader r = GetReader(new StringReader(strxml)))
{
r.Read();
r.Read();
using (XmlReader sr = r.ReadSubtree())
{
if (!sr.CanReadBinaryContent) return;
sr.Read();
sr.MoveToFirstAttribute();
sr.MoveToFirstAttribute();
byte[] bytes = new byte[4];
while ((sr.ReadContentAsBinHex(bytes, 0, bytes.Length)) > 0) { }
}
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
using GenStrings;
namespace System.Collections.Specialized.Tests
{
public class CopyToArrayIntNameValueCollectionTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
public void Test01()
{
IntlStrings intl;
NameValueCollection nvc;
// simple string values
string[] values =
{
"",
" ",
"a",
"aA",
"text",
" SPaces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// keys for simple string values
string[] keys =
{
"zero",
"oNe",
" ",
"",
"aa",
"1",
System.DateTime.Today.ToString(),
"$%^#",
Int32.MaxValue.ToString(),
" spaces",
"2222222222222222222222222"
};
string[] destination;
int cnt = 0; // Count
// initialize IntStrings
intl = new IntlStrings();
// [] NameValueCollection is constructed as expected
//-----------------------------------------------------------------
nvc = new NameValueCollection();
// [] CopyTo() empty collection into empty array
//
destination = new string[] { };
try
{
nvc.CopyTo(destination, -1);
Assert.False(true, "Error, no exception");
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
Assert.False(true, string.Format("Error, unexpected exception: {0}", e.ToString()));
}
try
{
nvc.CopyTo(destination, 0);
}
catch (Exception e)
{
Assert.False(true, string.Format("Error, unexpected exception: {0}", e.ToString()));
}
try
{
nvc.CopyTo(destination, 1);
Assert.False(true, "Error, no exception");
}
catch (ArgumentException)
{
}
catch (Exception e)
{
Assert.False(true, string.Format("Error, unexpected exception: {0}", e.ToString()));
}
// [] CopyTo() empty collection into filled array
//
destination = new string[values.Length];
for (int i = 0; i < values.Length; i++)
{
destination[i] = values[i];
}
nvc.CopyTo(destination, 0);
if (destination.Length != values.Length)
{
Assert.False(true, "Error, altered array after copying empty collection");
}
if (destination.Length == values.Length)
{
for (int i = 0; i < values.Length; i++)
{
if (String.Compare(destination[i], values[i]) != 0)
{
Assert.False(true, string.Format("Error, altered item {0} after copying empty collection", i));
}
}
}
//
// [] CopyTo(array, 0) collection with simple strings
cnt = nvc.Count;
int len = values.Length;
for (int i = 0; i < len; i++)
{
nvc.Add(keys[i], values[i]);
}
if (nvc.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, values.Length));
}
destination = new string[len];
nvc.CopyTo(destination, 0);
//
// order of items is the same as order it was in collection
//
for (int i = 0; i < len; i++)
{
// verify that collection is copied correctly
//
if (String.Compare(nvc[i], destination[i]) != 0)
{
Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, destination[i], nvc[i]));
}
}
// [] CopyTo(array, middle_index) collection with simple strings
//
nvc.Clear();
for (int i = 0; i < len; i++)
{
nvc.Add(keys[i], values[i]);
}
if (nvc.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, values.Length));
}
destination = new string[len * 2];
nvc.CopyTo(destination, len);
//
// order of items is the same as they wer in collection
//
for (int i = 0; i < len; i++)
{
// verify that collection is copied correctly
//
if (String.Compare(nvc[i], destination[i + len]) != 0)
{
Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, destination[i + len], nvc[i]));
}
}
//
// Intl strings
// [] CopyTo(array, 0) collection with Intl strings
//
string[] intlValues = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
string val = intl.GetRandomString(MAX_LEN);
while (Array.IndexOf(intlValues, val) != -1)
val = intl.GetRandomString(MAX_LEN);
intlValues[i] = val;
}
Boolean caseInsensitive = false;
for (int i = 0; i < len * 2; i++)
{
if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant())
caseInsensitive = true;
}
nvc.Clear();
for (int i = 0; i < len; i++)
{
nvc.Add(intlValues[i + len], intlValues[i]);
}
if (nvc.Count != (len))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, len));
}
destination = new string[len];
nvc.CopyTo(destination, 0);
//
// order of items is the same as they wer in collection
//
for (int i = 0; i < len; i++)
{
// verify that collection is copied correctly
//
if (String.Compare(nvc[i], destination[i]) != 0)
{
Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, destination[i], nvc[i]));
}
}
//
// Intl strings
// [] CopyTo(array, middle_index) collection with Intl strings
//
destination = new string[len * 2];
nvc.CopyTo(destination, len);
//
// order of items is the same as they were in collection
//
for (int i = 0; i < len; i++)
{
// verify that collection is copied correctly
//
if (String.Compare(nvc[i], destination[i + len]) != 0)
{
Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, destination[i + len], nvc[i]));
}
}
//
// [] Case sensitivity
//
string[] intlValuesLower = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
intlValues[i] = intlValues[i].ToUpperInvariant();
}
for (int i = 0; i < len * 2; i++)
{
intlValuesLower[i] = intlValues[i].ToLowerInvariant();
}
nvc.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
nvc.Add(intlValues[i + len], intlValues[i]); // adding uppercase strings
}
destination = new string[len];
nvc.CopyTo(destination, 0);
//
// order of items is the same as they were in collection
//
for (int i = 0; i < len; i++)
{
// verify that collection is copied correctly
//
if (String.Compare(nvc[i], destination[i]) != 0)
{
Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, destination[i], nvc[i]));
}
if (!caseInsensitive && Array.IndexOf(intlValuesLower, destination[i]) != -1)
{
Assert.False(true, string.Format("Error, copied lowercase string"));
}
}
//
// [] CopyTo(null, int)
//
destination = null;
Assert.Throws<ArgumentNullException>(() => { nvc.CopyTo(destination, 0); });
//
// [] CopyTo(string[], -1)
//
cnt = nvc.Count;
destination = new string[] { };
Assert.Throws<ArgumentOutOfRangeException>(() => { nvc.CopyTo(destination, -1); });
//
// [] CopyTo(Array, upperBound+1)
//
if (nvc.Count < 1)
{
for (int i = 0; i < len; i++)
{
nvc.Add(keys[i], values[i]);
}
}
destination = new string[len];
Assert.Throws<ArgumentException>(() => { nvc.CopyTo(destination, len); });
//
// [] CopyTo(Array, upperBound+2)
//
Assert.Throws<ArgumentException>(() => { nvc.CopyTo(destination, len + 1); });
//
// [] CopyTo(Array, not_enough_space)
//
Assert.Throws<ArgumentException>(() => { nvc.CopyTo(destination, len / 2); });
//
// [] CopyTo(multidim_Array, 0)
//
Array dest = new string[len, len];
Assert.Throws<ArgumentException>(() => { nvc.CopyTo(dest, 0); });
// [] CopyTo(array, 0) collection with multiple items with the same key
//
nvc.Clear();
len = values.Length;
string k = "keykey";
string exp = "";
for (int i = 0; i < len; i++)
{
nvc.Add(k, "Value" + i);
if (i < len - 1)
exp += "Value" + i + ",";
else
exp += "Value" + i;
}
if (nvc.Count != 1)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, 1));
}
destination = new string[1];
nvc.CopyTo(destination, 0);
// verify that collection is copied correctly
//
if (String.Compare(nvc[0], destination[0]) != 0)
{
Assert.False(true, string.Format("Error, copied \"{0}\" instead of \"{1}\"", destination[0], nvc[0]));
}
if (String.Compare(exp, destination[0]) != 0)
{
Assert.False(true, string.Format("Error, copied string is not the same as expected: {0}", destination[0]));
}
//
// [] CopyTo(wrong_type, 0)
//
dest = new DictionaryEntry[len];
Assert.Throws<InvalidCastException>(() => { nvc.CopyTo(dest, 0); });
}
}
}
| |
/*
* Copyright 2008 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 ReaderException = com.google.zxing.ReaderException;
using Result = com.google.zxing.Result;
using ResultPointCallback = com.google.zxing.ResultPointCallback;
using DecodeHintType = com.google.zxing.DecodeHintType;
using ResultPoint = com.google.zxing.ResultPoint;
using BarcodeFormat = com.google.zxing.BarcodeFormat;
using BitArray = com.google.zxing.common.BitArray;
namespace com.google.zxing.oned
{
/// <summary> <p>Encapsulates functionality and implementation that is common to UPC and EAN families
/// of one-dimensional barcodes.</p>
///
/// </summary>
/// <author> dswitkin@google.com (Daniel Switkin)
/// </author>
/// <author> Sean Owen
/// </author>
/// <author> alasdair@google.com (Alasdair Mackintosh)
/// </author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
/// </author>
public abstract class UPCEANReader:OneDReader
{
/// <summary> Get the format of this decoder.
///
/// </summary>
/// <returns> The 1D format.
/// </returns>
internal abstract BarcodeFormat BarcodeFormat{get;}
// These two values are critical for determining how permissive the decoding will be.
// We've arrived at these values through a lot of trial and error. Setting them any higher
// lets false positives creep in quickly.
//UPGRADE_NOTE: Final was removed from the declaration of 'MAX_AVG_VARIANCE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
private static readonly int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.42f);
//UPGRADE_NOTE: Final was removed from the declaration of 'MAX_INDIVIDUAL_VARIANCE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
private static readonly int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f);
/// <summary> Start/end guard pattern.</summary>
//UPGRADE_NOTE: Final was removed from the declaration of 'START_END_PATTERN'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
internal static readonly int[] START_END_PATTERN = new int[]{1, 1, 1};
/// <summary> Pattern marking the middle of a UPC/EAN pattern, separating the two halves.</summary>
//UPGRADE_NOTE: Final was removed from the declaration of 'MIDDLE_PATTERN'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
internal static readonly int[] MIDDLE_PATTERN = new int[]{1, 1, 1, 1, 1};
/// <summary> "Odd", or "L" patterns used to encode UPC/EAN digits.</summary>
//UPGRADE_NOTE: Final was removed from the declaration of 'L_PATTERNS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
internal static readonly int[][] L_PATTERNS = new int[][]{new int[]{3, 2, 1, 1}, new int[]{2, 2, 2, 1}, new int[]{2, 1, 2, 2}, new int[]{1, 4, 1, 1}, new int[]{1, 1, 3, 2}, new int[]{1, 2, 3, 1}, new int[]{1, 1, 1, 4}, new int[]{1, 3, 1, 2}, new int[]{1, 2, 1, 3}, new int[]{3, 1, 1, 2}};
/// <summary> As above but also including the "even", or "G" patterns used to encode UPC/EAN digits.</summary>
internal static int[][] L_AND_G_PATTERNS;
//UPGRADE_NOTE: Final was removed from the declaration of 'decodeRowStringBuffer '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private System.Text.StringBuilder decodeRowStringBuffer;
protected internal UPCEANReader()
{
decodeRowStringBuffer = new System.Text.StringBuilder(20);
}
internal static int[] findStartGuardPattern(BitArray row)
{
bool foundStart = false;
int[] startRange = null;
int nextStart = 0;
while (!foundStart)
{
startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN);
int start = startRange[0];
nextStart = startRange[1];
// Make sure there is a quiet zone at least as big as the start pattern before the barcode.
// If this check would run off the left edge of the image, do not accept this barcode,
// as it is very likely to be a false positive.
int quietStart = start - (nextStart - start);
if (quietStart >= 0)
{
foundStart = row.isRange(quietStart, start, false);
}
}
return startRange;
}
public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints)
{
return decodeRow(rowNumber, row, findStartGuardPattern(row), hints);
}
/// <summary> <p>Like {@link #decodeRow(int, BitArray, java.util.Hashtable)}, but
/// allows caller to inform method about where the UPC/EAN start pattern is
/// found. This allows this to be computed once and reused across many implementations.</p>
/// </summary>
public virtual Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange, System.Collections.Hashtable hints)
{
ResultPointCallback resultPointCallback = hints == null?null:(ResultPointCallback) hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK];
if (resultPointCallback != null)
{
resultPointCallback.foundPossibleResultPoint(new ResultPoint((startGuardRange[0] + startGuardRange[1]) / 2.0f, rowNumber));
}
System.Text.StringBuilder result = decodeRowStringBuffer;
result.Length = 0;
int endStart = decodeMiddle(row, startGuardRange, result);
if (resultPointCallback != null)
{
resultPointCallback.foundPossibleResultPoint(new ResultPoint(endStart, rowNumber));
}
int[] endRange = decodeEnd(row, endStart);
if (resultPointCallback != null)
{
resultPointCallback.foundPossibleResultPoint(new ResultPoint((endRange[0] + endRange[1]) / 2.0f, rowNumber));
}
// Make sure there is a quiet zone at least as big as the end pattern after the barcode. The
// spec might want more whitespace, but in practice this is the maximum we can count on.
int end = endRange[1];
int quietEnd = end + (end - endRange[0]);
if (quietEnd >= row.Size || !row.isRange(end, quietEnd, false))
{
throw ReaderException.Instance;
}
System.String resultString = result.ToString();
if (!checkChecksum(resultString))
{
throw ReaderException.Instance;
}
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
float left = (float) (startGuardRange[1] + startGuardRange[0]) / 2.0f;
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
float right = (float) (endRange[1] + endRange[0]) / 2.0f;
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
return new Result(resultString, null, new ResultPoint[]{new ResultPoint(left, (float) rowNumber), new ResultPoint(right, (float) rowNumber)}, BarcodeFormat);
}
/// <returns> {@link #checkStandardUPCEANChecksum(String)}
/// </returns>
//UPGRADE_NOTE: Access modifiers of method 'checkChecksum' were changed to 'protected'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1204'"
protected internal virtual bool checkChecksum(System.String s)
{
return checkStandardUPCEANChecksum(s);
}
/// <summary> Computes the UPC/EAN checksum on a string of digits, and reports
/// whether the checksum is correct or not.
///
/// </summary>
/// <param name="s">string of digits to check
/// </param>
/// <returns> true iff string of digits passes the UPC/EAN checksum algorithm
/// </returns>
/// <throws> ReaderException if the string does not contain only digits </throws>
private static bool checkStandardUPCEANChecksum(System.String s)
{
int length = s.Length;
if (length == 0)
{
return false;
}
int sum = 0;
for (int i = length - 2; i >= 0; i -= 2)
{
int digit = (int) s[i] - (int) '0';
if (digit < 0 || digit > 9)
{
throw ReaderException.Instance;
}
sum += digit;
}
sum *= 3;
for (int i = length - 1; i >= 0; i -= 2)
{
int digit = (int) s[i] - (int) '0';
if (digit < 0 || digit > 9)
{
throw ReaderException.Instance;
}
sum += digit;
}
return sum % 10 == 0;
}
//UPGRADE_NOTE: Access modifiers of method 'decodeEnd' were changed to 'protected'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1204'"
protected internal virtual int[] decodeEnd(BitArray row, int endStart)
{
return findGuardPattern(row, endStart, false, START_END_PATTERN);
}
/// <param name="row">row of black/white values to search
/// </param>
/// <param name="rowOffset">position to start search
/// </param>
/// <param name="whiteFirst">if true, indicates that the pattern specifies white/black/white/...
/// pixel counts, otherwise, it is interpreted as black/white/black/...
/// </param>
/// <param name="pattern">pattern of counts of number of black and white pixels that are being
/// searched for as a pattern
/// </param>
/// <returns> start/end horizontal offset of guard pattern, as an array of two ints
/// </returns>
/// <throws> ReaderException if pattern is not found </throws>
internal static int[] findGuardPattern(BitArray row, int rowOffset, bool whiteFirst, int[] pattern)
{
int patternLength = pattern.Length;
int[] counters = new int[patternLength];
int width = row.Size;
bool isWhite = false;
while (rowOffset < width)
{
isWhite = !row.get_Renamed(rowOffset);
if (whiteFirst == isWhite)
{
break;
}
rowOffset++;
}
int counterPosition = 0;
int patternStart = rowOffset;
for (int x = rowOffset; x < width; x++)
{
bool pixel = row.get_Renamed(x);
if (pixel ^ isWhite)
{
counters[counterPosition]++;
}
else
{
if (counterPosition == patternLength - 1)
{
if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE)
{
return new int[]{patternStart, x};
}
patternStart += counters[0] + counters[1];
for (int y = 2; y < patternLength; y++)
{
counters[y - 2] = counters[y];
}
counters[patternLength - 2] = 0;
counters[patternLength - 1] = 0;
counterPosition--;
}
else
{
counterPosition++;
}
counters[counterPosition] = 1;
isWhite = !isWhite;
}
}
throw ReaderException.Instance;
}
/// <summary> Attempts to decode a single UPC/EAN-encoded digit.
///
/// </summary>
/// <param name="row">row of black/white values to decode
/// </param>
/// <param name="counters">the counts of runs of observed black/white/black/... values
/// </param>
/// <param name="rowOffset">horizontal offset to start decoding from
/// </param>
/// <param name="patterns">the set of patterns to use to decode -- sometimes different encodings
/// for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should
/// be used
/// </param>
/// <returns> horizontal offset of first pixel beyond the decoded digit
/// </returns>
/// <throws> ReaderException if digit cannot be decoded </throws>
internal static int decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns)
{
recordPattern(row, rowOffset, counters);
int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept
int bestMatch = - 1;
int max = patterns.Length;
for (int i = 0; i < max; i++)
{
int[] pattern = patterns[i];
int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE);
if (variance < bestVariance)
{
bestVariance = variance;
bestMatch = i;
}
}
if (bestMatch >= 0)
{
return bestMatch;
}
else
{
throw ReaderException.Instance;
}
}
/// <summary> Subclasses override this to decode the portion of a barcode between the start
/// and end guard patterns.
///
/// </summary>
/// <param name="row">row of black/white values to search
/// </param>
/// <param name="startRange">start/end offset of start guard pattern
/// </param>
/// <param name="resultString">{@link StringBuffer} to append decoded chars to
/// </param>
/// <returns> horizontal offset of first pixel after the "middle" that was decoded
/// </returns>
/// <throws> ReaderException if decoding could not complete successfully </throws>
protected internal abstract int decodeMiddle(BitArray row, int[] startRange, System.Text.StringBuilder resultString);
static UPCEANReader()
{
{
L_AND_G_PATTERNS = new int[20][];
for (int i = 0; i < 10; i++)
{
L_AND_G_PATTERNS[i] = L_PATTERNS[i];
}
for (int i = 10; i < 20; i++)
{
int[] widths = L_PATTERNS[i - 10];
int[] reversedWidths = new int[widths.Length];
for (int j = 0; j < widths.Length; j++)
{
reversedWidths[j] = widths[widths.Length - j - 1];
}
L_AND_G_PATTERNS[i] = reversedWidths;
}
}
}
}
}
| |
using System;
using System.Reflection;
using System.Linq;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Libraries.Imaging
{
public class ColorHistogram
{
//take a blow up in space to have verified code
private int width, height;
private Histogram red, green, blue;
public Histogram Red { get { return red; } }
public Histogram Green { get { return green; } }
public Histogram Blue { get { return blue; } }
public int Width { get { return width; } }
public int Height { get { return height; } }
public ColorHistogram(int[][] image)
{
width = image.Length;
height = image[0].Length;
byte[][] r = new byte[width][];
byte[][] g = new byte[width][];
byte[][] b = new byte[width][];
for(int i = 0; i < width; i++)
{
byte[] rLine = new byte[height];
byte[] gLine = new byte[height];
byte[] bLine = new byte[height];
int[] line = image[i];
for(int j = 0; j < height; j++)
{
Color c = Color.FromArgb(line[j]);
rLine[j] = (byte)c.R;
gLine[j] = (byte)c.G;
bLine[j] = (byte)c.B;
}
r[i] = rLine;
g[i] = gLine;
b[i] = bLine;
}
red = new Histogram(r);
green = new Histogram(g);
blue = new Histogram(b);
}
public ColorHistogram(int width, int height)
{
this.width = width;
this.height = height;
red = new Histogram(width, height);
blue = new Histogram(width, height);
green = new Histogram(width, height);
}
public void Repurpose(IEnumerable<int> elements)
{
var decomp = Decompose(elements);
red.Repurpose(decomp.Item1);
green.Repurpose(decomp.Item2);
blue.Repurpose(decomp.Item3);
}
private static Tuple<IEnumerable<byte>, IEnumerable<byte>, IEnumerable<byte>> Decompose(IEnumerable<int> elements)
{
List<byte> r = new List<byte>();
List<byte> g = new List<byte>();
List<byte> b = new List<byte>();
foreach(var v in elements)
{
Color c = Color.FromArgb(v);
r.Add((byte)c.R);
g.Add((byte)c.G);
b.Add((byte)c.B);
}
return new Tuple<IEnumerable<byte>, IEnumerable<byte>, IEnumerable<byte>>(r, g, b);
}
}
public class Histogram
{
//8-bit histogram
public const int NUM_VALUES = 256;
private long[] contents, totals;
private byte[] globalEqualizedIntensity;
private double[] pk;
private int width, height;
private long totalPixelCount;
public int Width { get { return width; } }
public int Height { get { return height; } }
public long PixelCount { get { return totalPixelCount; } }
public byte[] GlobalEqualizedIntensity { get { return globalEqualizedIntensity; } }
public double[] PK { get { return pk; } }
public long this[byte intensity] { get { return contents[(int)intensity]; } }
public long this[int intensity] { get { return contents[intensity]; } }
public long this[int from, int to]
{
get
{
if(from == 0)
return totals[to - 1];
else if((to - from) == 1) //only one item
return totals[from];
else
{
long total = 0L;
for(int i = from; i < to; i++)
total += (long)this[i];
return total;
}
}
}
private Histogram()
{
contents = new long[NUM_VALUES];
totals = new long[NUM_VALUES];
pk = new double[NUM_VALUES];
globalEqualizedIntensity = new byte[NUM_VALUES];
}
public Histogram(int width, int height)
: this()
{
this.width = width;
this.height = height;
totalPixelCount = width * height;
}
public Histogram(IEnumerable<byte> data)
: this()
{
foreach(var v in data)
{
contents[(int)v]++;
totalPixelCount++;
}
SetupExtraneousData();
}
public Histogram(Bitmap bitmap)
: this(bitmap.Width, bitmap.Height)
{
PerformActionAcrossTheImageAndSetup((i,j) => contents[bitmap.GetPixel(i,j).R]++);
}
private void PerformActionAcrossTheImageAndSetup(Action<int,int> body)
{
for(int i = 0; i < width; i++)
for(int j = 0; j < height; j++)
body(i,j);
SetupExtraneousData();
}
public Histogram(byte[][] value)
: this(value.Length, value[0].Length)
{
PerformActionAcrossTheImageAndSetup((x,y) => contents[(int)value[x][y]]++);
}
public Histogram(int width, int height, byte[,] value)
: this(width, height)
{
PerformActionAcrossTheImageAndSetup((i,j) => contents[(int)value[i,j]]++);
}
public void Repurpose(IEnumerable<byte> elements)
{
for(int i = 0; i < 256; i++)
contents[i] = 0;
totalPixelCount = 0;
foreach(byte b in elements)
{
contents[(int)b]++;
totalPixelCount++;
}
SetupExtraneousData();
}
private void SetupExtraneousData()
{
double pixelCount = (double)totalPixelCount;
byte previousIntensity = (byte)0;
for(int i = 0; i < NUM_VALUES; i++)
{
//do this in a single pass
double amount = (double)SetupTotalsIteration(i);
SetupPkIteration(i, pixelCount);
SetupEqualizedIntensityIteration(i, pixelCount, amount,
ref previousIntensity);
}
}
private void SetupPkIteration(int i, double pixelCount)
{
pk[i] = contents[i] / pixelCount;
}
private void SetupEqualizedIntensityIteration(int i,
double count, double amount,
ref byte previousIntensity)
{
if(contents[i] == 0)
globalEqualizedIntensity[i] = previousIntensity;
else
{
double result = (255.0 * (amount / count));
globalEqualizedIntensity[i] = (byte)result;
previousIntensity = (byte)result;
}
}
private long SetupTotalsIteration(int i)
{
if(i == 0)
totals[i] = contents[i]; //just copy over the number of pixels
else
totals[i] = totals[i - 1] + contents[i];
return totals[i];
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Scott Wilson <sw@scratchstudio.net>
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: XmlFileErrorLog.cs 795 2011-02-16 22:29:34Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Xml;
using System.Collections.Generic;
using IDictionary = System.Collections.IDictionary;
#endregion
/// <summary>
/// An <see cref="ErrorLog"/> implementation that uses XML files stored on
/// disk as its backing store.
/// </summary>
public class XmlFileErrorLog : ErrorLog
{
private readonly string _logPath;
/// <summary>
/// Initializes a new instance of the <see cref="XmlFileErrorLog"/> class
/// using a dictionary of configured settings.
/// </summary>
public XmlFileErrorLog(IDictionary config)
{
if (config == null) throw new ArgumentNullException("config");
var logPath = config.Find("logPath", string.Empty);
if (logPath.Length == 0)
{
//
// For compatibility reasons with older version of this
// implementation, we also try "LogPath".
//
logPath = config.Find("LogPath", string.Empty);
if (logPath.Length == 0)
throw new ApplicationException("Log path is missing for the XML file-based error log.");
}
if (logPath.StartsWith("~/"))
logPath = MapPath(logPath);
_logPath = logPath;
}
/// <remarks>
/// This method is excluded from inlining so that if
/// HostingEnvironment does not need JIT-ing if it is not implicated
/// by the caller.
/// </remarks>
[ MethodImpl(MethodImplOptions.NoInlining) ]
private static string MapPath(string path)
{
return System.Web.Hosting.HostingEnvironment.MapPath(path);
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlFileErrorLog"/> class
/// to use a specific path to store/load XML files.
/// </summary>
public XmlFileErrorLog(string logPath)
{
if (logPath == null) throw new ArgumentNullException("logPath");
if (logPath.Length == 0) throw new ArgumentException(null, "logPath");
_logPath = logPath;
}
/// <summary>
/// Gets the path to where the log is stored.
/// </summary>
public virtual string LogPath
{
get { return _logPath; }
}
/// <summary>
/// Gets the name of this error log implementation.
/// </summary>
public override string Name
{
get { return "XML File-Based Error Log"; }
}
/// <summary>
/// Logs an error to the database.
/// </summary>
/// <remarks>
/// Logs an error as a single XML file stored in a folder. XML files are named with a
/// sortable date and a unique identifier. Currently the XML files are stored indefinately.
/// As they are stored as files, they may be managed using standard scheduled jobs.
/// </remarks>
public override string Log(Error error)
{
string logPath = LogPath;
if (!Directory.Exists(logPath))
Directory.CreateDirectory(logPath);
string errorId = Guid.NewGuid().ToString();
DateTime timeStamp = (error.Time > DateTime.MinValue ? error.Time : DateTime.Now);
string fileName = string.Format(CultureInfo.InvariantCulture,
@"error-{0:yyyy-MM-ddHHmmssZ}-{1}.xml",
/* 0 */ timeStamp.ToUniversalTime(),
/* 1 */ errorId);
string path = Path.Combine(logPath, fileName);
using (var writer = new XmlTextWriter(path, Encoding.UTF8))
{
writer.Formatting = Formatting.Indented;
writer.WriteStartElement("error");
writer.WriteAttributeString("errorId", errorId);
ErrorXml.Encode(error, writer);
writer.WriteEndElement();
writer.Flush();
}
return errorId;
}
/// <summary>
/// Returns a page of errors from the folder in descending order
/// of logged time as defined by the sortable filenames.
/// </summary>
public override int GetErrors(int pageIndex, int pageSize, ICollection<ErrorLogEntry> errorEntryList)
{
if (pageIndex < 0) throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null);
if (pageSize < 0) throw new ArgumentOutOfRangeException("pageSize", pageSize, null);
var logPath = LogPath;
var dir = new DirectoryInfo(logPath);
if (!dir.Exists)
return 0;
var infos = dir.GetFiles("error-*.xml");
if (!infos.Any())
return 0;
var files = infos.Where(info => IsUserFile(info.Attributes))
.OrderBy(info => info.Name, StringComparer.OrdinalIgnoreCase)
.Select(info => Path.Combine(logPath, info.Name))
.Reverse()
.ToArray();
if (errorEntryList != null)
{
var entries = files.Skip(pageIndex * pageSize)
.Take(pageSize)
.Select(LoadErrorLogEntry);
foreach (var entry in entries)
errorEntryList.Add(entry);
}
return files.Length; // Return total
}
private ErrorLogEntry LoadErrorLogEntry(string path)
{
using (var reader = XmlReader.Create(path))
{
if (!reader.IsStartElement("error"))
return null;
var id = reader.GetAttribute("errorId");
var error = ErrorXml.Decode(reader);
return new ErrorLogEntry(this, id, error);
}
}
/// <summary>
/// Returns the specified error from the filesystem, or throws an exception if it does not exist.
/// </summary>
public override ErrorLogEntry GetError(string id)
{
try
{
id = (new Guid(id)).ToString(); // validate GUID
}
catch (FormatException e)
{
throw new ArgumentException(e.Message, id, e);
}
var file = new DirectoryInfo(LogPath).GetFiles(string.Format("error-*-{0}.xml", id))
.FirstOrDefault();
if (file == null)
return null;
if (!IsUserFile(file.Attributes))
return null;
using (var reader = XmlReader.Create(file.FullName))
return new ErrorLogEntry(this, id, ErrorXml.Decode(reader));
}
private static bool IsUserFile(FileAttributes attributes)
{
return 0 == (attributes & (FileAttributes.Directory |
FileAttributes.Hidden |
FileAttributes.System));
}
}
}
| |
using System;
using System.Collections.Generic;
namespace Lucene.Net.Index
{
using NUnit.Framework;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
/*
* 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 Document = Documents.Document;
using IOContext = Lucene.Net.Store.IOContext;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using TestUtil = Lucene.Net.Util.TestUtil;
[TestFixture]
public class TestSegmentReader : LuceneTestCase
{
private Directory Dir;
private Document TestDoc;
private SegmentReader Reader;
//TODO: Setup the reader w/ multiple documents
[SetUp]
public override void SetUp()
{
base.SetUp();
Dir = NewDirectory();
TestDoc = new Document();
DocHelper.SetupDoc(TestDoc);
SegmentCommitInfo info = DocHelper.WriteDoc(Random(), Dir, TestDoc);
Reader = new SegmentReader(info, DirectoryReader.DEFAULT_TERMS_INDEX_DIVISOR, IOContext.READ);
}
[TearDown]
public override void TearDown()
{
Reader.Dispose();
Dir.Dispose();
base.TearDown();
}
[Test]
public virtual void Test()
{
Assert.IsTrue(Dir != null);
Assert.IsTrue(Reader != null);
Assert.IsTrue(DocHelper.NameValues.Count > 0);
Assert.IsTrue(DocHelper.NumFields(TestDoc) == DocHelper.All.Count);
}
[Test]
public virtual void TestDocument()
{
Assert.IsTrue(Reader.NumDocs == 1);
Assert.IsTrue(Reader.MaxDoc >= 1);
Document result = Reader.Document(0);
Assert.IsTrue(result != null);
//There are 2 unstored fields on the document that are not preserved across writing
Assert.IsTrue(DocHelper.NumFields(result) == DocHelper.NumFields(TestDoc) - DocHelper.Unstored.Count);
IList<IndexableField> fields = result.Fields;
foreach (IndexableField field in fields)
{
Assert.IsTrue(field != null);
Assert.IsTrue(DocHelper.NameValues.ContainsKey(field.Name()));
}
}
[Test]
public virtual void TestGetFieldNameVariations()
{
ICollection<string> allFieldNames = new HashSet<string>();
ICollection<string> indexedFieldNames = new HashSet<string>();
ICollection<string> notIndexedFieldNames = new HashSet<string>();
ICollection<string> tvFieldNames = new HashSet<string>();
ICollection<string> noTVFieldNames = new HashSet<string>();
foreach (FieldInfo fieldInfo in Reader.FieldInfos)
{
string name = fieldInfo.Name;
allFieldNames.Add(name);
if (fieldInfo.Indexed)
{
indexedFieldNames.Add(name);
}
else
{
notIndexedFieldNames.Add(name);
}
if (fieldInfo.HasVectors())
{
tvFieldNames.Add(name);
}
else if (fieldInfo.Indexed)
{
noTVFieldNames.Add(name);
}
}
Assert.IsTrue(allFieldNames.Count == DocHelper.All.Count);
foreach (string s in allFieldNames)
{
Assert.IsTrue(DocHelper.NameValues.ContainsKey(s) == true || s.Equals(""));
}
Assert.IsTrue(indexedFieldNames.Count == DocHelper.Indexed.Count);
foreach (string s in indexedFieldNames)
{
Assert.IsTrue(DocHelper.Indexed.ContainsKey(s) == true || s.Equals(""));
}
Assert.IsTrue(notIndexedFieldNames.Count == DocHelper.Unindexed.Count);
//Get all indexed fields that are storing term vectors
Assert.IsTrue(tvFieldNames.Count == DocHelper.Termvector.Count);
Assert.IsTrue(noTVFieldNames.Count == DocHelper.Notermvector.Count);
}
[Test]
public virtual void TestTerms()
{
Fields fields = MultiFields.GetFields(Reader);
foreach (string field in fields)
{
Terms terms = fields.Terms(field);
Assert.IsNotNull(terms);
TermsEnum termsEnum = terms.Iterator(null);
while (termsEnum.Next() != null)
{
BytesRef term = termsEnum.Term();
Assert.IsTrue(term != null);
string fieldValue = (string)DocHelper.NameValues[field];
Assert.IsTrue(fieldValue.IndexOf(term.Utf8ToString()) != -1);
}
}
DocsEnum termDocs = TestUtil.Docs(Random(), Reader, DocHelper.TEXT_FIELD_1_KEY, new BytesRef("field"), MultiFields.GetLiveDocs(Reader), null, 0);
Assert.IsTrue(termDocs.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
termDocs = TestUtil.Docs(Random(), Reader, DocHelper.NO_NORMS_KEY, new BytesRef(DocHelper.NO_NORMS_TEXT), MultiFields.GetLiveDocs(Reader), null, 0);
Assert.IsTrue(termDocs.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
DocsAndPositionsEnum positions = MultiFields.GetTermPositionsEnum(Reader, MultiFields.GetLiveDocs(Reader), DocHelper.TEXT_FIELD_1_KEY, new BytesRef("field"));
// NOTE: prior rev of this test was failing to first
// call next here:
Assert.IsTrue(positions.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
Assert.IsTrue(positions.DocID() == 0);
Assert.IsTrue(positions.NextPosition() >= 0);
}
[Test]
public virtual void TestNorms()
{
//TODO: Not sure how these work/should be tested
/*
try {
byte [] norms = reader.norms(DocHelper.TEXT_FIELD_1_KEY);
System.out.println("Norms: " + norms);
Assert.IsTrue(norms != null);
} catch (IOException e) {
e.printStackTrace();
Assert.IsTrue(false);
}
*/
CheckNorms(Reader);
}
public static void CheckNorms(AtomicReader reader)
{
// test omit norms
for (int i = 0; i < DocHelper.Fields.Length; i++)
{
IndexableField f = DocHelper.Fields[i];
if (f.FieldType().Indexed)
{
Assert.AreEqual(reader.GetNormValues(f.Name()) != null, !f.FieldType().OmitNorms);
Assert.AreEqual(reader.GetNormValues(f.Name()) != null, !DocHelper.NoNorms.ContainsKey(f.Name()));
if (reader.GetNormValues(f.Name()) == null)
{
// test for norms of null
NumericDocValues norms = MultiDocValues.GetNormValues(reader, f.Name());
Assert.IsNull(norms);
}
}
}
}
[Test]
public virtual void TestTermVectors()
{
Terms result = Reader.GetTermVectors(0).Terms(DocHelper.TEXT_FIELD_2_KEY);
Assert.IsNotNull(result);
Assert.AreEqual(3, result.Size());
TermsEnum termsEnum = result.Iterator(null);
while (termsEnum.Next() != null)
{
string term = termsEnum.Term().Utf8ToString();
int freq = (int)termsEnum.TotalTermFreq();
Assert.IsTrue(DocHelper.FIELD_2_TEXT.IndexOf(term) != -1);
Assert.IsTrue(freq > 0);
}
Fields results = Reader.GetTermVectors(0);
Assert.IsTrue(results != null);
Assert.AreEqual(3, results.Size, "We do not have 3 term freq vectors");
}
[Test]
public virtual void TestOutOfBoundsAccess()
{
int numDocs = Reader.MaxDoc;
try
{
Reader.Document(-1);
Assert.Fail();
}
catch (System.IndexOutOfRangeException expected)
{
}
try
{
Reader.GetTermVectors(-1);
Assert.Fail();
}
catch (System.IndexOutOfRangeException expected)
{
}
try
{
Reader.Document(numDocs);
Assert.Fail();
}
catch (System.IndexOutOfRangeException expected)
{
}
try
{
Reader.GetTermVectors(numDocs);
Assert.Fail();
}
catch (System.IndexOutOfRangeException expected)
{
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Language.StandardClassification;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.InteractiveWindow.Commands
{
internal sealed class Commands : IInteractiveWindowCommands
{
private const string _commandSeparator = ",";
private readonly Dictionary<string, IInteractiveWindowCommand> _commands;
private readonly int _maxCommandNameLength;
private readonly IInteractiveWindow _window;
private readonly IContentType _commandContentType;
private readonly IStandardClassificationService _classificationRegistry;
private IContentType _languageContentType;
private ITextBuffer _previousBuffer;
public string CommandPrefix { get; set; }
public bool InCommand
{
get
{
return _window.CurrentLanguageBuffer.ContentType == _commandContentType;
}
}
internal Commands(IInteractiveWindow window, string prefix, IEnumerable<IInteractiveWindowCommand> commands, IContentTypeRegistryService contentTypeRegistry = null, IStandardClassificationService classificationRegistry = null)
{
CommandPrefix = prefix;
_window = window;
Dictionary<string, IInteractiveWindowCommand> commandsDict = new Dictionary<string, IInteractiveWindowCommand>();
foreach (var command in commands)
{
int length = 0;
foreach (var name in command.Names)
{
if (commandsDict.ContainsKey(name))
{
throw new InvalidOperationException(string.Format(InteractiveWindowResources.DuplicateCommand, string.Join(", ", command.Names)));
}
if (length != 0)
{
length += _commandSeparator.Length;
}
length += name.Length;
commandsDict[name] = command;
}
if (length == 0)
{
throw new InvalidOperationException(string.Format(InteractiveWindowResources.MissingCommandName, command.GetType().Name));
}
_maxCommandNameLength = Math.Max(_maxCommandNameLength, length);
}
_commands = commandsDict;
_classificationRegistry = classificationRegistry;
if (contentTypeRegistry != null)
{
_commandContentType = contentTypeRegistry.GetContentType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName);
}
if (window != null)
{
window.SubmissionBufferAdded += Window_SubmissionBufferAdded;
window.Properties[typeof(IInteractiveWindowCommands)] = this;
}
}
private void Window_SubmissionBufferAdded(object sender, SubmissionBufferAddedEventArgs e)
{
if (_previousBuffer != null)
{
_previousBuffer.Changed -= NewBufferChanged;
}
_languageContentType = e.NewBuffer.ContentType;
e.NewBuffer.Changed += NewBufferChanged;
_previousBuffer = e.NewBuffer;
}
private void NewBufferChanged(object sender, TextContentChangedEventArgs e)
{
bool isCommand = IsCommand(e.After.GetExtent());
ITextBuffer buffer = e.After.TextBuffer;
IContentType contentType = buffer.ContentType;
IContentType newContentType = null;
if (contentType == _languageContentType)
{
if (isCommand)
{
newContentType = _commandContentType;
}
}
else
{
if (!isCommand)
{
newContentType = _languageContentType;
}
}
if (newContentType != null)
{
buffer.ChangeContentType(newContentType, editTag: null);
}
}
internal bool IsCommand(SnapshotSpan span)
{
SnapshotSpan prefixSpan, commandSpan, argumentsSpan;
return TryParseCommand(span, out prefixSpan, out commandSpan, out argumentsSpan) != null;
}
internal IInteractiveWindowCommand TryParseCommand(SnapshotSpan span, out SnapshotSpan prefixSpan, out SnapshotSpan commandSpan, out SnapshotSpan argumentsSpan)
{
string prefix = CommandPrefix;
SnapshotSpan trimmed = span.TrimStart();
if (!trimmed.StartsWith(prefix))
{
prefixSpan = commandSpan = argumentsSpan = default(SnapshotSpan);
return null;
}
prefixSpan = trimmed.SubSpan(0, prefix.Length);
var nameAndArgs = trimmed.SubSpan(prefix.Length).TrimStart();
SnapshotPoint nameEnd = nameAndArgs.IndexOfAnyWhiteSpace() ?? span.End;
commandSpan = new SnapshotSpan(span.Snapshot, Span.FromBounds(nameAndArgs.Start.Position, nameEnd.Position));
argumentsSpan = new SnapshotSpan(span.Snapshot, Span.FromBounds(nameEnd.Position, span.End.Position)).Trim();
return this[commandSpan.GetText()];
}
public IInteractiveWindowCommand this[string name]
{
get
{
IInteractiveWindowCommand command;
_commands.TryGetValue(name, out command);
return command;
}
}
public IEnumerable<IInteractiveWindowCommand> GetCommands()
{
return _commands.Values;
}
internal IEnumerable<string> Help()
{
string format = "{0,-" + _maxCommandNameLength + "} {1}";
return _commands.OrderBy(entry => entry.Key).Select(cmd => string.Format(format, cmd.Key, cmd.Value.Description));
}
public IEnumerable<ClassificationSpan> Classify(SnapshotSpan span)
{
SnapshotSpan prefixSpan, commandSpan, argumentsSpan;
var command = TryParseCommand(span.Snapshot.GetExtent(), out prefixSpan, out commandSpan, out argumentsSpan);
if (command == null)
{
yield break;
}
if (span.OverlapsWith(prefixSpan))
{
yield return Classification(span.Snapshot, prefixSpan, _classificationRegistry.Keyword);
}
if (span.OverlapsWith(commandSpan))
{
yield return Classification(span.Snapshot, commandSpan, _classificationRegistry.Keyword);
}
if (argumentsSpan.Length > 0)
{
foreach (var classifiedSpan in command.ClassifyArguments(span.Snapshot, argumentsSpan.Span, span.Span))
{
yield return classifiedSpan;
}
}
}
private ClassificationSpan Classification(ITextSnapshot snapshot, Span span, IClassificationType classificationType)
{
return new ClassificationSpan(new SnapshotSpan(snapshot, span), classificationType);
}
/// <returns>
/// Null if parsing fails, the result of execution otherwise.
/// </returns>
public Task<ExecutionResult> TryExecuteCommand()
{
var span = _window.CurrentLanguageBuffer.CurrentSnapshot.GetExtent();
SnapshotSpan prefixSpan, commandSpan, argumentsSpan;
var command = TryParseCommand(span, out prefixSpan, out commandSpan, out argumentsSpan);
if (command == null)
{
return null;
}
return ExecuteCommandAsync(command, argumentsSpan.GetText());
}
private async Task<ExecutionResult> ExecuteCommandAsync(IInteractiveWindowCommand command, string arguments)
{
try
{
return await command.Execute(_window, arguments).ConfigureAwait(false);
}
catch (Exception e)
{
_window.ErrorOutputWriter.WriteLine($"Command '{command.Names.First()}' failed: {e.Message}");
return ExecutionResult.Failure;
}
}
private const string HelpIndent = " ";
private static readonly string[] s_shortcutDescriptions = new[]
{
"Enter If the current submission appears to be complete, evaluate it. Otherwise, insert a new line.",
"Ctrl-Enter Within the current submission, evaluate the current submission.",
" Within a previous submission, append the previous submission to the current submission.",
"Shift-Enter Insert a new line.",
"Escape Clear the current submission.",
"Alt-UpArrow Replace the current submission with a previous submission.",
"Alt-DownArrow Replace the current submission with a subsequent submission (after having previously navigated backwards).",
"Ctrl-Alt-UpArrow Replace the current submission with a previous submission beginning with the same text.",
"Ctrl-Alt-DownArrow Replace the current submission with a subsequent submission beginning with the same text (after having previously navigated backwards).",
"UpArrow At the end of the current submission, replace the current submission with a previous submission.",
" Elsewhere, move the cursor up one line.",
"DownArrow At the end of the current submission, replace the current submission with a subsequent submission (after having previously navigated backwards).",
" Elsewhere, move the cursor down one line.",
"Ctrl-K, Ctrl-Enter Paste the selection at the end of interactive buffer, leave caret at the end of input.",
"Ctrl-E, Ctrl-Enter Paste and execute the selection before any pending input in the interactive buffer.",
"Ctrl-A First press, select the submission containing the cursor. Second press, select all text in the window.",
};
public void DisplayHelp()
{
_window.WriteLine("Keyboard shortcuts:");
foreach (var line in s_shortcutDescriptions)
{
_window.Write(HelpIndent);
_window.WriteLine(line);
}
_window.WriteLine("REPL commands:");
foreach (var line in Help())
{
_window.Write(HelpIndent);
_window.WriteLine(line);
}
}
public void DisplayCommandUsage(IInteractiveWindowCommand command, TextWriter writer, bool displayDetails)
{
if (displayDetails)
{
writer.WriteLine(command.Description);
writer.WriteLine(string.Empty);
}
writer.WriteLine("Usage:");
writer.Write(HelpIndent);
writer.Write(CommandPrefix);
writer.Write(string.Join(_commandSeparator, command.Names));
string commandLine = command.CommandLine;
if (commandLine != null)
{
writer.Write(" ");
writer.Write(commandLine);
}
if (displayDetails)
{
writer.WriteLine(string.Empty);
var paramsDesc = command.ParametersDescription;
if (paramsDesc != null && paramsDesc.Any())
{
writer.WriteLine(string.Empty);
writer.WriteLine("Parameters:");
int maxParamNameLength = paramsDesc.Max(entry => entry.Key.Length);
string paramHelpLineFormat = HelpIndent + "{0,-" + maxParamNameLength + "} {1}";
foreach (var paramDesc in paramsDesc)
{
writer.WriteLine(string.Format(paramHelpLineFormat, paramDesc.Key, paramDesc.Value));
}
}
IEnumerable<string> details = command.DetailedDescription;
if (details != null && details.Any())
{
writer.WriteLine(string.Empty);
foreach (var line in details)
{
writer.WriteLine(line);
}
}
}
}
public void DisplayCommandHelp(IInteractiveWindowCommand command)
{
DisplayCommandUsage(command, _window.OutputWriter, displayDetails: 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.Tests.Cache.Store
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Store;
using Apache.Ignite.Core.Impl;
using NUnit.Framework;
/// <summary>
/// Tests cache store functionality.
/// </summary>
public class CacheStoreTest
{
/** */
private const string BinaryStoreCacheName = "binary_store";
/** */
private const string ObjectStoreCacheName = "object_store";
/** */
private const string CustomStoreCacheName = "custom_store";
/** */
private const string TemplateStoreCacheName = "template_store*";
/// <summary>
/// Fixture set up.
/// </summary>
[TestFixtureSetUp]
public virtual void BeforeTests()
{
var cfg = new IgniteConfiguration
{
IgniteInstanceName = GridName,
JvmClasspath = TestUtils.CreateTestClasspath(),
JvmOptions = TestUtils.TestJavaOptions(),
SpringConfigUrl = "config\\native-client-test-cache-store.xml",
BinaryConfiguration = new BinaryConfiguration(typeof (Key), typeof (Value))
};
Ignition.Start(cfg);
}
/// <summary>
/// Fixture tear down.
/// </summary>
[TestFixtureTearDown]
public void AfterTests()
{
Ignition.StopAll(true);
}
/// <summary>
/// Test tear down.
/// </summary>
[TearDown]
public void AfterTest()
{
CacheTestStore.Reset();
var cache = GetCache();
cache.Clear();
Assert.IsTrue(cache.IsEmpty(),
"Cache is not empty: " +
string.Join(", ", cache.Select(x => string.Format("[{0}:{1}]", x.Key, x.Value))));
TestUtils.AssertHandleRegistryHasItems(300, 3, Ignition.GetIgnite(GridName));
}
/// <summary>
/// Tests that simple cache loading works and exceptions are propagated properly.
/// </summary>
[Test]
public void TestLoadCache()
{
var cache = GetCache();
Assert.AreEqual(0, cache.GetSize());
cache.LoadCache(new CacheEntryFilter(), 100, 10);
Assert.AreEqual(5, cache.GetSize());
for (int i = 105; i < 110; i++)
Assert.AreEqual("val_" + i, cache.Get(i));
// Test exception in filter
Assert.Throws<CacheStoreException>(() => cache.LoadCache(new ExceptionalEntryFilter(), 100, 10));
// Test exception in store
CacheTestStore.ThrowError = true;
CheckCustomStoreError(Assert.Throws<CacheStoreException>(() =>
cache.LoadCache(new CacheEntryFilter(), 100, 10)).InnerException);
}
/// <summary>
/// Tests cache loading in local mode.
/// </summary>
[Test]
public void TestLocalLoadCache()
{
var cache = GetCache();
Assert.AreEqual(0, cache.GetSize());
cache.LocalLoadCache(new CacheEntryFilter(), 100, 10);
Assert.AreEqual(5, cache.GetSize());
for (int i = 105; i < 110; i++)
Assert.AreEqual("val_" + i, cache.Get(i));
}
/// <summary>
/// Tests that object metadata propagates properly during cache loading.
/// </summary>
[Test]
public void TestLoadCacheMetadata()
{
CacheTestStore.LoadObjects = true;
var cache = GetCache();
Assert.AreEqual(0, cache.GetSize());
cache.LocalLoadCache(null, 0, 3);
Assert.AreEqual(3, cache.GetSize());
var meta = cache.WithKeepBinary<Key, IBinaryObject>().Get(new Key(0)).GetBinaryType();
Assert.NotNull(meta);
Assert.AreEqual("Apache.Ignite.Core.Tests.Cache.Store.Value", meta.TypeName);
}
/// <summary>
/// Tests asynchronous cache load.
/// </summary>
[Test]
public void TestLoadCacheAsync()
{
var cache = GetCache();
Assert.AreEqual(0, cache.GetSize());
cache.LocalLoadCacheAsync(new CacheEntryFilter(), 100, 10).Wait();
Assert.AreEqual(5, cache.GetSizeAsync().Result);
for (int i = 105; i < 110; i++)
{
Assert.AreEqual("val_" + i, cache.GetAsync(i).Result);
}
// Test errors
CacheTestStore.ThrowError = true;
CheckCustomStoreError(
Assert.Throws<AggregateException>(
() => cache.LocalLoadCacheAsync(new CacheEntryFilter(), 100, 10).Wait())
.InnerException);
}
/// <summary>
/// Tests write-through and read-through behavior.
/// </summary>
[Test]
public void TestPutLoad()
{
var cache = GetCache();
cache.Put(1, "val");
IDictionary map = GetStoreMap();
Assert.AreEqual(1, map.Count);
// TODO: IGNITE-4535
//cache.LocalEvict(new[] { 1 });
//Assert.AreEqual(0, cache.GetSize(CachePeekMode.All));
Assert.AreEqual("val", cache.Get(1));
Assert.AreEqual(1, cache.GetSize());
}
[Test]
public void TestExceptions()
{
var cache = GetCache();
cache.Put(1, "val");
CacheTestStore.ThrowError = true;
CheckCustomStoreError(Assert.Throws<CacheStoreException>(() => cache.Put(-2, "fail")).InnerException);
// TODO: IGNITE-4535
//cache.LocalEvict(new[] {1});
//CheckCustomStoreError(Assert.Throws<CacheStoreException>(() => cache.Get(1)).InnerException);
CacheTestStore.ThrowError = false;
cache.Remove(1);
}
[Test]
[Ignore("IGNITE-4657")]
public void TestExceptionsNoRemove()
{
var cache = GetCache();
cache.Put(1, "val");
CacheTestStore.ThrowError = true;
CheckCustomStoreError(Assert.Throws<CacheStoreException>(() => cache.Put(-2, "fail")).InnerException);
cache.LocalEvict(new[] {1});
CheckCustomStoreError(Assert.Throws<CacheStoreException>(() => cache.Get(1)).InnerException);
}
/// <summary>
/// Tests write-through and read-through behavior with binarizable values.
/// </summary>
[Test]
public void TestPutLoadBinarizable()
{
var cache = GetBinaryStoreCache<int, Value>();
cache.Put(1, new Value(1));
IDictionary map = GetStoreMap();
Assert.AreEqual(1, map.Count);
IBinaryObject v = (IBinaryObject)map[1];
Assert.AreEqual(1, v.GetField<int>("_idx"));
// TODO: IGNITE-4535
//cache.LocalEvict(new[] { 1 });
//Assert.AreEqual(0, cache.GetSize());
Assert.AreEqual(1, cache.Get(1).Index);
Assert.AreEqual(1, cache.GetSize());
}
/// <summary>
/// Tests write-through and read-through behavior with storeKeepBinary=false.
/// </summary>
[Test]
public void TestPutLoadObjects()
{
var cache = GetObjectStoreCache<int, Value>();
cache.Put(1, new Value(1));
IDictionary map = GetStoreMap();
Assert.AreEqual(1, map.Count);
Value v = (Value)map[1];
Assert.AreEqual(1, v.Index);
// TODO: IGNITE-4535
//cache.LocalEvict(new[] { 1 });
//Assert.AreEqual(0, cache.GetSize());
Assert.AreEqual(1, cache.Get(1).Index);
Assert.AreEqual(1, cache.GetSize());
}
/// <summary>
/// Tests cache store LoadAll functionality.
/// </summary>
[Test]
public void TestPutLoadAll()
{
var putMap = new Dictionary<int, string>();
for (int i = 0; i < 10; i++)
putMap.Add(i, "val_" + i);
var cache = GetCache();
cache.PutAll(putMap);
IDictionary map = GetStoreMap();
Assert.AreEqual(10, map.Count);
for (int i = 0; i < 10; i++)
Assert.AreEqual("val_" + i, map[i]);
cache.Clear();
Assert.AreEqual(0, cache.GetSize());
ICollection<int> keys = new List<int>();
for (int i = 0; i < 10; i++)
keys.Add(i);
IDictionary<int, string> loaded = cache.GetAll(keys).ToDictionary(x => x.Key, x => x.Value);
Assert.AreEqual(10, loaded.Count);
for (int i = 0; i < 10; i++)
Assert.AreEqual("val_" + i, loaded[i]);
Assert.AreEqual(10, cache.GetSize());
}
/// <summary>
/// Tests cache store removal.
/// </summary>
[Test]
public void TestRemove()
{
var cache = GetCache();
for (int i = 0; i < 10; i++)
cache.Put(i, "val_" + i);
IDictionary map = GetStoreMap();
Assert.AreEqual(10, map.Count);
for (int i = 0; i < 5; i++)
cache.Remove(i);
Assert.AreEqual(5, map.Count);
for (int i = 5; i < 10; i++)
Assert.AreEqual("val_" + i, map[i]);
}
/// <summary>
/// Tests cache store removal.
/// </summary>
[Test]
public void TestRemoveAll()
{
var cache = GetCache();
for (int i = 0; i < 10; i++)
cache.Put(i, "val_" + i);
IDictionary map = GetStoreMap();
Assert.AreEqual(10, map.Count);
cache.RemoveAll(new List<int> { 0, 1, 2, 3, 4 });
Assert.AreEqual(5, map.Count);
for (int i = 5; i < 10; i++)
Assert.AreEqual("val_" + i, map[i]);
}
/// <summary>
/// Tests cache store with transactions.
/// </summary>
[Test]
public void TestTx()
{
var cache = GetCache();
using (var tx = cache.Ignite.GetTransactions().TxStart())
{
tx.AddMeta("meta", 100);
cache.Put(1, "val");
tx.Commit();
}
IDictionary map = GetStoreMap();
Assert.AreEqual(1, map.Count);
Assert.AreEqual("val", map[1]);
}
/// <summary>
/// Tests multithreaded cache loading.
/// </summary>
[Test]
public void TestLoadCacheMultithreaded()
{
CacheTestStore.LoadMultithreaded = true;
var cache = GetCache();
Assert.AreEqual(0, cache.GetSize());
cache.LocalLoadCache(null, 0, null);
Assert.AreEqual(1000, cache.GetSize());
for (int i = 0; i < 1000; i++)
Assert.AreEqual("val_" + i, cache.Get(i));
}
/// <summary>
/// Tests that cache store property values are propagated from Spring XML.
/// </summary>
[Test]
public void TestCustomStoreProperties()
{
var cache = GetCustomStoreCache();
Assert.IsNotNull(cache);
Assert.AreEqual(42, CacheTestStore.intProperty);
Assert.AreEqual("String value", CacheTestStore.stringProperty);
}
/// <summary>
/// Tests cache store with dynamically started cache.
/// </summary>
[Test]
public void TestDynamicStoreStart()
{
var grid = Ignition.GetIgnite(GridName);
var reg = ((Ignite) grid).HandleRegistry;
var handleCount = reg.Count;
var cache = GetTemplateStoreCache();
Assert.IsNotNull(cache);
cache.Put(1, cache.Name);
Assert.AreEqual(cache.Name, CacheTestStore.Map[1]);
Assert.AreEqual(handleCount + 1, reg.Count);
grid.DestroyCache(cache.Name);
Assert.AreEqual(handleCount, reg.Count);
}
/// <summary>
/// Tests the load all.
/// </summary>
[Test]
public void TestLoadAll([Values(true, false)] bool isAsync)
{
var cache = GetCache();
var loadAll = isAsync
? (Action<IEnumerable<int>, bool>) ((x, y) => { cache.LoadAllAsync(x, y).Wait(); })
: cache.LoadAll;
Assert.AreEqual(0, cache.GetSize());
loadAll(Enumerable.Range(105, 5), false);
Assert.AreEqual(5, cache.GetSize());
for (int i = 105; i < 110; i++)
Assert.AreEqual("val_" + i, cache[i]);
// Test overwrite
cache[105] = "42";
cache.LocalEvict(new[] { 105 });
loadAll(new[] {105}, false);
Assert.AreEqual("42", cache[105]);
loadAll(new[] {105, 106}, true);
Assert.AreEqual("val_105", cache[105]);
Assert.AreEqual("val_106", cache[106]);
}
/// <summary>
/// Tests the argument passing to LoadCache method.
/// </summary>
[Test]
public void TestArgumentPassing()
{
var cache = GetBinaryStoreCache<object, object>();
Action<object> checkValue = o =>
{
cache.Clear();
Assert.AreEqual(0, cache.GetSize());
cache.LoadCache(null, null, 1, o);
Assert.AreEqual(o, cache[1]);
};
// Null.
cache.LoadCache(null, null);
Assert.AreEqual(0, cache.GetSize());
// Empty args array.
cache.LoadCache(null);
Assert.AreEqual(0, cache.GetSize());
// Simple types.
checkValue(1);
checkValue(new[] {1, 2, 3});
checkValue("1");
checkValue(new[] {"1", "2"});
checkValue(Guid.NewGuid());
checkValue(new[] {Guid.NewGuid(), Guid.NewGuid()});
checkValue(DateTime.Now);
checkValue(new[] {DateTime.Now, DateTime.UtcNow});
// Collections.
checkValue(new ArrayList {1, "2", 3.3});
checkValue(new List<int> {1, 2});
checkValue(new Dictionary<int, string> {{1, "foo"}});
}
/// <summary>
/// Get's grid name for this test.
/// </summary>
/// <value>Grid name.</value>
protected virtual string GridName
{
get { return null; }
}
/// <summary>
/// Gets the store map.
/// </summary>
private static IDictionary GetStoreMap()
{
return CacheTestStore.Map;
}
/// <summary>
/// Gets the cache.
/// </summary>
private ICache<int, string> GetCache()
{
return GetBinaryStoreCache<int, string>();
}
/// <summary>
/// Gets the binary store cache.
/// </summary>
private ICache<TK, TV> GetBinaryStoreCache<TK, TV>()
{
return Ignition.GetIgnite(GridName).GetCache<TK, TV>(BinaryStoreCacheName);
}
/// <summary>
/// Gets the object store cache.
/// </summary>
private ICache<TK, TV> GetObjectStoreCache<TK, TV>()
{
return Ignition.GetIgnite(GridName).GetCache<TK, TV>(ObjectStoreCacheName);
}
/// <summary>
/// Gets the custom store cache.
/// </summary>
private ICache<int, string> GetCustomStoreCache()
{
return Ignition.GetIgnite(GridName).GetCache<int, string>(CustomStoreCacheName);
}
/// <summary>
/// Gets the template store cache.
/// </summary>
private ICache<int, string> GetTemplateStoreCache()
{
var cacheName = TemplateStoreCacheName.Replace("*", Guid.NewGuid().ToString());
return Ignition.GetIgnite(GridName).GetOrCreateCache<int, string>(cacheName);
}
/// <summary>
/// Checks the custom store error.
/// </summary>
private static void CheckCustomStoreError(Exception err)
{
var customErr = err as CacheTestStore.CustomStoreException ??
err.InnerException as CacheTestStore.CustomStoreException;
Assert.IsNotNull(customErr);
Assert.AreEqual(customErr.Message, customErr.Details);
}
}
/// <summary>
/// Cache key.
/// </summary>
internal class Key
{
/** */
private readonly int _idx;
/// <summary>
/// Initializes a new instance of the <see cref="Key"/> class.
/// </summary>
public Key(int idx)
{
_idx = idx;
}
/** <inheritdoc /> */
public override bool Equals(object obj)
{
if (obj == null || obj.GetType() != GetType())
return false;
return ((Key)obj)._idx == _idx;
}
/** <inheritdoc /> */
public override int GetHashCode()
{
return _idx;
}
}
/// <summary>
/// Cache value.
/// </summary>
internal class Value
{
/** */
private readonly int _idx;
/// <summary>
/// Initializes a new instance of the <see cref="Value"/> class.
/// </summary>
public Value(int idx)
{
_idx = idx;
}
/// <summary>
/// Gets the index.
/// </summary>
public int Index
{
get { return _idx; }
}
}
/// <summary>
/// Cache entry predicate.
/// </summary>
[Serializable]
public class CacheEntryFilter : ICacheEntryFilter<int, string>
{
/** <inheritdoc /> */
public bool Invoke(ICacheEntry<int, string> entry)
{
return entry.Key >= 105;
}
}
/// <summary>
/// Cache entry predicate that throws an exception.
/// </summary>
[Serializable]
public class ExceptionalEntryFilter : ICacheEntryFilter<int, string>
{
/** <inheritdoc /> */
public bool Invoke(ICacheEntry<int, string> entry)
{
throw new Exception("Expected exception in ExceptionalEntryFilter");
}
}
/// <summary>
/// Filter that can't be serialized.
/// </summary>
public class InvalidCacheEntryFilter : CacheEntryFilter
{
// No-op.
}
}
| |
/// Refly License
///
/// Copyright (c) 2004 Jonathan de Halleux, http://www.dotnetwiki.org
///
/// This software is provided 'as-is', without any express or implied warranty.
/// In no event will the authors be held liable for any damages arising from
/// the use of this software.
///
/// Permission is granted to anyone to use this software for any purpose,
/// including commercial applications, and to alter it and redistribute it
/// freely, subject to the following restrictions:
///
/// 1. The origin of this software must not be misrepresented;
/// you must not claim that you wrote the original software.
/// If you use this software in a product, an acknowledgment in the product
/// documentation would be appreciated but is not required.
///
/// 2. Altered source versions must be plainly marked as such,
/// and must not be misrepresented as being the original software.
///
///3. This notice may not be removed or altered from any source distribution.
using System;
using System.CodeDom;
namespace Refly.CodeDom.Collections
{
using Refly.CodeDom.Statements;
using Refly.CodeDom.Expressions;
/// <summary>
/// A collection of elements of type Statement
/// </summary>
public class StatementCollection: System.Collections.CollectionBase
{
/// <summary>
/// Initializes a new empty instance of the StatementCollection class.
/// </summary>
public StatementCollection()
{
// empty
}
/// <summary>
/// Initializes a new instance of the StatementCollection class, containing elements
/// copied from an array.
/// </summary>
/// <param name="items">
/// The array whose elements are to be added to the new StatementCollection.
/// </param>
public StatementCollection(Statement[] items)
{
this.AddRange(items);
}
/// <summary>
/// Initializes a new instance of the StatementCollection class, containing elements
/// copied from another instance of StatementCollection
/// </summary>
/// <param name="items">
/// The StatementCollection whose elements are to be added to the new StatementCollection.
/// </param>
public StatementCollection(StatementCollection items)
{
this.AddRange(items);
}
/// <summary>
/// Adds the elements of an array to the end of this StatementCollection.
/// </summary>
/// <param name="items">
/// The array whose elements are to be added to the end of this StatementCollection.
/// </param>
public virtual void AddRange(Statement[] items)
{
foreach (Statement item in items)
{
this.List.Add(item);
}
}
/// <summary>
/// Adds the elements of another StatementCollection to the end of this StatementCollection.
/// </summary>
/// <param name="items">
/// The StatementCollection whose elements are to be added to the end of this StatementCollection.
/// </param>
public virtual void AddRange(StatementCollection items)
{
foreach (Statement item in items)
{
this.List.Add(item);
}
}
/// <summary>
/// Adds an instance of type Statement to the end of this StatementCollection.
/// </summary>
/// <param name="value">
/// The Statement to be added to the end of this StatementCollection.
/// </param>
public virtual void Add(Statement value)
{
this.List.Add(value);
}
public virtual void Add(Expression expression)
{
this.Add( new ExpressionStatement(expression) );
}
public virtual void AddAssign(Expression left, Expression right)
{
this.Add( Stm.Assign(left,right));
}
public void Return(Expression expression)
{
this.Add( Stm.Return(expression ) );
}
public virtual void Insert(int index, Statement value)
{
this.List.Insert(index, value);
}
public virtual void Insert(int index, Expression expression)
{
this.Insert(index, new ExpressionStatement(expression));
}
/// <summary>
/// Type-specific enumeration class, used by StatementCollection.GetEnumerator.
/// </summary>
public class Enumerator: System.Collections.IEnumerator
{
private System.Collections.IEnumerator wrapped;
public Enumerator(StatementCollection collection)
{
this.wrapped = ((System.Collections.CollectionBase)collection).GetEnumerator();
}
public Statement Current
{
get
{
return (Statement) (this.wrapped.Current);
}
}
object System.Collections.IEnumerator.Current
{
get
{
return (Statement) (this.wrapped.Current);
}
}
public bool MoveNext()
{
return this.wrapped.MoveNext();
}
public void Reset()
{
this.wrapped.Reset();
}
}
/// <summary>
/// Returns an enumerator that can iterate through the elements of this StatementCollection.
/// </summary>
/// <returns>
/// An object that implements System.Collections.IEnumerator.
/// </returns>
public new virtual StatementCollection.Enumerator GetEnumerator()
{
return new StatementCollection.Enumerator(this);
}
public void ToCodeDom(CodeStatementCollection col)
{
foreach(Statement st in this)
{
st.ToCodeDom(col);
}
}
public CodeStatement[] ToCodeDomArray()
{
CodeStatementCollection col = new CodeStatementCollection();
ToCodeDom(col);
CodeStatement[] sts = new CodeStatement[col.Count];
col.CopyTo(sts,0);
return sts;
}
}
}
| |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
using System.IO;
public class Launch : ModuleRules
{
public Launch(TargetInfo Target)
{
PrivateIncludePaths.Add("Runtime/Launch/Private");
PrivateIncludePathModuleNames.AddRange(
new string[] {
"AutomationController",
"OnlineSubsystem",
"TaskGraph",
}
);
PrivateDependencyModuleNames.AddRange(
new string[] {
"Core",
"CoreUObject",
"Engine",
"InputCore",
"MediaAssets",
"MoviePlayer",
"Networking",
"PakFile",
"Projects",
"RenderCore",
"RHI",
"SandboxFile",
"Serialization",
"ShaderCore",
"Slate",
"SlateCore",
"Sockets",
}
);
if (Target.Type != TargetRules.TargetType.Server)
{
PrivateDependencyModuleNames.AddRange(
new string[] {
"HeadMountedDisplay",
}
);
if ((Target.Platform == UnrealTargetPlatform.Win32) ||
(Target.Platform == UnrealTargetPlatform.Win64))
{
if (!WindowsPlatform.IsWindowsXPSupported())
{
DynamicallyLoadedModuleNames.Add("D3D12RHI");
}
DynamicallyLoadedModuleNames.Add("D3D11RHI");
DynamicallyLoadedModuleNames.Add("XAudio2");
}
else if (Target.Platform == UnrealTargetPlatform.Mac)
{
DynamicallyLoadedModuleNames.Add("CoreAudio");
}
else if (Target.Platform == UnrealTargetPlatform.Linux)
{
DynamicallyLoadedModuleNames.Add("ALAudio");
}
PrivateIncludePathModuleNames.AddRange(
new string[] {
"SlateRHIRenderer",
}
);
DynamicallyLoadedModuleNames.AddRange(
new string[] {
"SlateRHIRenderer",
}
);
}
// UFS clients are not available in shipping builds
if (Target.Configuration != UnrealTargetConfiguration.Shipping)
{
PrivateDependencyModuleNames.AddRange(
new string[] {
"NetworkFile",
"StreamingFile",
"AutomationWorker",
}
);
}
DynamicallyLoadedModuleNames.AddRange(
new string[] {
"Media",
"Renderer",
}
);
if (UEBuildConfiguration.bCompileAgainstEngine)
{
PrivateIncludePathModuleNames.Add("Messaging");
PublicDependencyModuleNames.Add("SessionServices");
PrivateIncludePaths.Add("Developer/DerivedDataCache/Public");
// LaunchEngineLoop.cpp does a LoadModule() on OnlineSubsystem and OnlineSubsystemUtils when compiled WITH_ENGINE, so they must be marked as dependencies so that they get compiled and cleaned
DynamicallyLoadedModuleNames.Add("OnlineSubsystem");
DynamicallyLoadedModuleNames.Add("OnlineSubsystemUtils");
}
if (Target.Configuration != UnrealTargetConfiguration.Shipping)
{
PublicIncludePathModuleNames.Add("ProfilerService");
DynamicallyLoadedModuleNames.AddRange(new string[] { "TaskGraph", "RealtimeProfiler", "ProfilerService" });
}
if (UEBuildConfiguration.bBuildEditor == true)
{
PublicIncludePathModuleNames.Add("ProfilerClient");
PrivateDependencyModuleNames.AddRange(
new string[] {
"SourceControl",
"UnrealEd",
"DesktopPlatform"
}
);
// ExtraModules that are loaded when WITH_EDITOR=1 is true
DynamicallyLoadedModuleNames.AddRange(
new string[] {
"AutomationController",
"AutomationWindow",
"ProfilerClient",
"Toolbox",
"GammaUI",
"ModuleUI",
"OutputLog",
"TextureCompressor",
"MeshUtilities",
"SourceCodeAccess"
}
);
if (Target.Platform == UnrealTargetPlatform.Mac)
{
PrivateDependencyModuleNames.Add("MainFrame");
PrivateDependencyModuleNames.Add("Settings");
}
else
{
DynamicallyLoadedModuleNames.Add("MainFrame");
}
}
if (Target.Platform == UnrealTargetPlatform.IOS)
{
PrivateDependencyModuleNames.Add("OpenGLDrv");
DynamicallyLoadedModuleNames.Add("IOSAudio");
DynamicallyLoadedModuleNames.Add("IOSRuntimeSettings");
PublicFrameworks.Add("OpenGLES");
// this is weak for IOS8 support for CAMetalLayer that is in QuartzCore
PublicWeakFrameworks.Add("QuartzCore");
PrivateDependencyModuleNames.Add("LaunchDaemonMessages");
}
if (Target.Platform == UnrealTargetPlatform.Android)
{
PrivateDependencyModuleNames.Add("OpenGLDrv");
PrivateDependencyModuleNames.Add("AndroidAudio");
DynamicallyLoadedModuleNames.Add("AndroidRuntimeSettings");
}
if ((Target.Platform == UnrealTargetPlatform.Win32) ||
(Target.Platform == UnrealTargetPlatform.Win64) ||
(Target.Platform == UnrealTargetPlatform.Mac) ||
(Target.Platform == UnrealTargetPlatform.Linux && Target.Type != TargetRules.TargetType.Server))
{
// TODO: re-enable after implementing resource tables for OpenGL.
DynamicallyLoadedModuleNames.Add("OpenGLDrv");
}
if (Target.Platform == UnrealTargetPlatform.HTML5 )
{
PrivateDependencyModuleNames.Add("ALAudio");
if (Target.Architecture == "-win32")
{
PrivateDependencyModuleNames.Add("HTML5Win32");
PublicIncludePathModuleNames.Add("HTML5Win32");
}
AddThirdPartyPrivateStaticDependencies(Target, "SDL2");
}
// @todo ps4 clang bug: this works around a PS4/clang compiler bug (optimizations)
if (Target.Platform == UnrealTargetPlatform.PS4)
{
bFasterWithoutUnity = true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using BTDB.IL;
using BTDB.ODBLayer;
namespace BTDB.IOC.CRegs
{
class SingletonImpl : ICReg, ICRegILGen, ICRegFuncOptimized
{
readonly Type _implementationType;
readonly ICRegILGen _wrapping;
readonly int _singletonIndex;
IBuildContext _buildCtx;
public SingletonImpl(Type implementationType, ICRegILGen wrapping, int singletonIndex)
{
_implementationType = implementationType;
_wrapping = wrapping;
_singletonIndex = singletonIndex;
}
public object BuildFuncOfT(ContainerImpl container, Type funcType)
{
var obj = container.Singletons[_singletonIndex];
return obj == null ? null : ClosureOfObjBuilder.Build(funcType, obj);
}
string ICRegILGen.GenFuncName(IGenerationContext context)
{
return "Singleton_" + _implementationType.ToSimpleName();
}
public void GenInitialization(IGenerationContext context)
{
var backupCtx = context.BuildContext;
context.BuildContext = _buildCtx;
_wrapping.GenInitialization(context);
context.GetSpecific<SingletonsLocal>().Prepare();
context.BuildContext = backupCtx;
}
internal class BuildCRegLocals
{
Dictionary<ICReg, IILLocal> _map = new Dictionary<ICReg, IILLocal>(ReferenceEqualityComparer<ICReg>.Instance);
readonly Stack<Dictionary<ICReg, IILLocal>> _stack = new Stack<Dictionary<ICReg, IILLocal>>();
internal void Push()
{
_stack.Push(_map);
_map = new Dictionary<ICReg, IILLocal>(_map, ReferenceEqualityComparer<ICReg>.Instance);
}
internal void Pop()
{
_map = _stack.Pop();
}
internal IILLocal Get(ICReg key)
{
IILLocal result;
return _map.TryGetValue(key, out result) ? result : null;
}
public void Add(ICReg key, IILLocal local)
{
_map.Add(key, local);
}
}
class SingletonsLocal : IGenerationContextSetter
{
IGenerationContext _context;
public void Set(IGenerationContext context)
{
_context = context;
}
internal void Prepare()
{
if (MainLocal != null) return;
MainLocal = _context.IL.DeclareLocal(typeof(object[]), "singletons");
_context.PushToILStack(Need.ContainerNeed);
_context.IL
.Castclass(typeof(ContainerImpl))
.Ldfld(() => default(ContainerImpl).Singletons)
.Stloc(MainLocal);
}
internal IILLocal MainLocal { get; private set; }
}
public bool IsCorruptingILStack(IGenerationContext context)
{
var buildCRegLocals = context.GetSpecific<BuildCRegLocals>();
var localSingleton = buildCRegLocals.Get(this);
if (localSingleton != null) return false;
var obj = context.Container.Singletons[_singletonIndex];
if (obj != null) return false;
return true;
}
public IILLocal GenMain(IGenerationContext context)
{
var backupCtx = context.BuildContext;
context.BuildContext = _buildCtx;
var il = context.IL;
var buildCRegLocals = context.GetSpecific<BuildCRegLocals>();
var localSingleton = buildCRegLocals.Get(this);
if (localSingleton != null)
{
return localSingleton;
}
var localSingletons = context.GetSpecific<SingletonsLocal>().MainLocal;
var safeImplementationType = _implementationType.IsPublic ? _implementationType : typeof (object);
localSingleton = il.DeclareLocal(safeImplementationType, "singleton");
var obj = context.Container.Singletons[_singletonIndex];
if (obj != null)
{
il
.Ldloc(localSingletons)
.LdcI4(_singletonIndex)
.LdelemRef()
.Castclass(_implementationType)
.Stloc(localSingleton);
return localSingleton;
}
var localLockTaken = il.DeclareLocal(typeof(bool), "lockTaken");
var localLock = il.DeclareLocal(typeof(object), "lock");
var labelNull1 = il.DefineLabel();
var labelNotNull2 = il.DefineLabel();
var labelNotTaken = il.DefineLabel();
bool boolPlaceholder = false;
il
.Ldloc(localSingletons)
.LdcI4(_singletonIndex)
.LdelemRef()
.Dup()
.Castclass(safeImplementationType)
.Stloc(localSingleton)
.Brtrue(labelNull1)
.LdcI4(0)
.Stloc(localLockTaken);
context.PushToILStack(Need.ContainerNeed);
il
.Castclass(typeof(ContainerImpl))
.Ldfld(() => default(ContainerImpl).SingletonLocks)
.LdcI4(_singletonIndex)
.LdelemRef()
.Stloc(localLock)
.Try()
.Ldloc(localLock)
.Ldloca(localLockTaken)
.Call(() => Monitor.Enter(null, ref boolPlaceholder))
.Ldloc(localSingletons)
.LdcI4(_singletonIndex)
.LdelemRef()
.Dup()
.Castclass(safeImplementationType)
.Stloc(localSingleton)
.Brtrue(labelNotNull2);
buildCRegLocals.Push();
var nestedLocal = _wrapping.GenMain(context);
if (nestedLocal != null)
{
il.Ldloc(nestedLocal);
}
buildCRegLocals.Pop();
il
.Stloc(localSingleton)
.Ldloc(localSingletons)
.LdcI4(_singletonIndex)
.Ldloc(localSingleton)
.StelemRef()
.Mark(labelNotNull2)
.Finally()
.Ldloc(localLockTaken)
.BrfalseS(labelNotTaken)
.Ldloc(localLock)
.Call(() => Monitor.Exit(null))
.Mark(labelNotTaken)
.EndTry()
.Mark(labelNull1);
buildCRegLocals.Add(this, localSingleton);
context.BuildContext = backupCtx;
return localSingleton;
}
public IEnumerable<INeed> GetNeeds(IGenerationContext context)
{
var backupCtx = context.BuildContext;
_buildCtx = backupCtx.FreezeMulti();
context.BuildContext = _buildCtx;
yield return new Need
{
Kind = NeedKind.CReg,
Key = _wrapping
};
yield return Need.ContainerNeed;
context.BuildContext = backupCtx;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace System.Collections.Tests
{
public class Hashtable_GetEnumeratorTests
{
[Fact]
public void TestGetEnumeratorBasic()
{
Hashtable hash1;
IDictionaryEnumerator dicEnum1;
int ii;
string str1;
string strRetKey;
int iExpValue;
Queue que1;
Queue que2;
//[] 1) Empty Hash table
//Get enumerator for an empty table
hash1 = new Hashtable();
dicEnum1 = hash1.GetEnumerator();
Assert.Equal(dicEnum1.MoveNext(), false);
//[] 2) Full hash table
hash1 = new Hashtable();
for (ii = 0; ii < 100; ii++)
{
str1 = string.Concat("key_", ii.ToString());
hash1.Add(str1, ii);
}
dicEnum1 = hash1.GetEnumerator();
ii = 0;
//Enumerator (well, Hashtable really) does not hold values in the order we put them in!!
//so we will use 2 ques to confirm that all the keys and values we put inside the hashtable was there
que1 = new Queue();
que2 = new Queue();
while (dicEnum1.MoveNext() != false)
{
strRetKey = (string)dicEnum1.Key;
iExpValue = Convert.ToInt32(dicEnum1.Value);
//we make sure that the values are there
Assert.True(hash1.ContainsKey(strRetKey));
Assert.True(hash1.ContainsValue(iExpValue));
//we will make sure that enumerator get all the objects
que1.Enqueue(strRetKey);
que2.Enqueue(iExpValue);
}
//making sure the que size is right
Assert.Equal(100, que1.Count);
Assert.Equal(100, que2.Count);
// 3) Full hash table, allow remove true
hash1 = new Hashtable();
for (ii = 0; ii < 100; ii++)
{
str1 = string.Concat("key_", ii.ToString());
hash1.Add(str1, ii);
}
dicEnum1 = hash1.GetEnumerator();
//Enumerator (well, Hashtable really) does not hold values in the order we put them in!!
//so we will use 2 ques to confirm that all the keys and values we put inside the hashtable was there
que1 = new Queue();
que2 = new Queue();
while (dicEnum1.MoveNext() != false)
{
strRetKey = (string)dicEnum1.Key;
iExpValue = Convert.ToInt32(dicEnum1.Value);
//we make sure that the values are there
Assert.True(hash1.ContainsKey(strRetKey));
Assert.True(hash1.ContainsValue(iExpValue));
//we will make sure that enumerator get all the objects
que1.Enqueue(strRetKey);
que2.Enqueue(iExpValue);
}
//making sure the que size is right
Assert.Equal(100, que1.Count);
Assert.Equal(100, que2.Count);
//[] 3) change hash table externally whilst in the middle of enumerating
hash1 = new Hashtable();
for (ii = 0; ii < 100; ii++)
{
str1 = string.Concat("key_", ii.ToString());
hash1.Add(str1, ii);
}
dicEnum1 = hash1.GetEnumerator();
//this is the first object. we have a true
Assert.True(dicEnum1.MoveNext());
strRetKey = (string)dicEnum1.Key;
iExpValue = Convert.ToInt32(dicEnum1.Value);
//we make sure that the values are there
Assert.True(hash1.ContainsKey(strRetKey));
Assert.True(hash1.ContainsValue(iExpValue));
// we will change the underlying hashtable
ii = 87;
str1 = string.Concat("key_", ii.ToString());
hash1[str1] = ii;
// MoveNext should throw
Assert.Throws<InvalidOperationException>(() =>
{
dicEnum1.MoveNext();
}
);
// Value should NOT throw
object foo = dicEnum1.Value;
object foo1 = dicEnum1.Key;
// Current should NOT throw
object foo2 = dicEnum1.Current;
Assert.Throws<InvalidOperationException>(() =>
{
dicEnum1.Reset();
}
);
//[] 5) try getting object
// a) before moving
// b) twice before moving to next
// c) after next returns false
hash1 = new Hashtable();
for (ii = 0; ii < 100; ii++)
{
str1 = string.Concat("key_", ii.ToString());
hash1.Add(str1, ii);
}
dicEnum1 = hash1.GetEnumerator();
// a) before moving
Assert.Throws<InvalidOperationException>(() =>
{
strRetKey = (string)dicEnum1.Key;
}
);
//Entry dicEnum1 = (IDictionaryEnumerator *)hash1.GetEnumerator();
dicEnum1 = hash1.GetEnumerator();
while (dicEnum1.MoveNext() != false)
{
;//dicEntr1 = (dicEnum1.Entry);
}
Assert.Throws<InvalidOperationException>(() =>
{
strRetKey = (string)dicEnum1.Key;
}
);
//[]We will get a valid enumerator, move to a valid position, then change the underlying HT. Current shouold not throw.
//Only calling MoveNext should throw.
//create the HT
hash1 = new Hashtable();
for (ii = 0; ii < 100; ii++)
{
str1 = string.Concat("key_", ii.ToString());
hash1.Add(str1, ii);
}
//get the enumerator and move to a valid location
dicEnum1 = hash1.GetEnumerator();
dicEnum1.MoveNext();
dicEnum1.MoveNext();
ii = 87;
str1 = string.Concat("key_", ii.ToString());
//if we are currently pointer at the item that we are going to change then move to the next one
if (0 == string.Compare((string)dicEnum1.Key, str1))
{
dicEnum1.MoveNext();
}
//change the underlying HT
hash1[str1] = ii + 50;
//calling current on the Enumerator should not throw
strRetKey = (string)dicEnum1.Key;
iExpValue = Convert.ToInt32(dicEnum1.Value);
Assert.True(hash1.ContainsKey(strRetKey));
Assert.True(hash1.ContainsValue(iExpValue));
strRetKey = (string)dicEnum1.Entry.Key;
iExpValue = Convert.ToInt32(dicEnum1.Entry.Value);
Assert.True(hash1.ContainsKey(strRetKey));
Assert.True(hash1.ContainsValue(iExpValue));
strRetKey = (string)(((DictionaryEntry)(dicEnum1.Current)).Key);
iExpValue = Convert.ToInt32(((DictionaryEntry)dicEnum1.Current).Value);
Assert.True(hash1.ContainsKey(strRetKey));
Assert.True(hash1.ContainsValue(iExpValue));
// calling MoveNExt should throw
Assert.Throws<InvalidOperationException>(() =>
{
dicEnum1.MoveNext();
}
);
//[] Try calling clone on the enumerator
dicEnum1 = hash1.GetEnumerator();
var anotherEnumerator = hash1.GetEnumerator();
Assert.False(object.ReferenceEquals(dicEnum1, anotherEnumerator));
}
}
}
| |
#region Copyright 2008-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Text;
namespace System.Commands
{
/// <summary>
/// This is a private class as the means of sharing is to simply include the source file not
/// reference a library.
/// </summary>
[System.Diagnostics.DebuggerNonUserCode]
partial class ArgumentList : System.Collections.ObjectModel.KeyedCollection<string, ArgumentList.Item>
{
#region Static Configuration Options
static StringComparer _defaultCompare = StringComparer.OrdinalIgnoreCase;
static char[] _prefix = new char[] { '/', '-' };
static char[] _delim = new char[] { ':', '=' };
static readonly string[] EmptyList = new string[0];
/// <summary>
/// Controls the default string comparer used for this class
/// </summary>
public static StringComparer DefaultComparison
{
get { return _defaultCompare; }
set
{
if (value == null) throw new ArgumentNullException();
_defaultCompare = value;
}
}
/// <summary>
/// Controls the allowable prefix characters that will preceed named arguments
/// </summary>
public static char[] PrefixChars
{
get { return (char[])_prefix.Clone(); }
set
{
if (value == null) throw new ArgumentNullException();
if (value.Length == 0) throw new ArgumentOutOfRangeException();
_prefix = (char[])value.Clone();
}
}
/// <summary>
/// Controls the allowable delimeter characters seperate argument names from values
/// </summary>
public static char[] NameDelimeters
{
get { return (char[])_delim.Clone(); }
set
{
if (value == null) throw new ArgumentNullException();
if (value.Length == 0) throw new ArgumentOutOfRangeException();
_delim = (char[])value.Clone();
}
}
#endregion Static Configuration Options
readonly List<string> _unnamed;
/// <summary>
/// Initializes a new instance of the ArgumentList class using the argument list provided
/// </summary>
public ArgumentList(params string[] arguments) : this(DefaultComparison, arguments) { }
/// <summary>
/// Initializes a new instance of the ArgumentList class using the argument list provided
/// and using the string comparer provided, by default this is case-insensitive
/// </summary>
public ArgumentList(StringComparer comparer, params string[] arguments)
: base(comparer, 0)
{
_unnamed = new List<string>();
this.AddRange(arguments);
}
/// <summary>
/// Returns a list of arguments that did not start with a character in the PrefixChars
/// static collection. These arguments can be modified by the methods on the returned
/// collection, or you set this property to a new collection (a copy is made).
/// </summary>
public IList<string> Unnamed
{
get { return _unnamed; }
set
{
_unnamed.Clear();
if (value != null)
_unnamed.AddRange(value);
}
}
/// <summary>
/// Parses the strings provided for switch names and optionally values, by default in one
/// of the following forms: "/name=value", "/name:value", "-name=value", "-name:value"
/// </summary>
public void AddRange(params string[] arguments)
{
if (arguments == null) throw new ArgumentNullException();
foreach (string arg in arguments)
{
string name, value;
if (TryParseNameValue(arg, out name, out value))
Add(name, value);
else
_unnamed.Add(CleanArgument(arg));
}
}
/// <summary>
/// Adds a name/value pair to the collection of arguments, if value is null the name is
/// added with no values.
/// </summary>
public void Add(string name, string value)
{
if (name == null)
throw new ArgumentNullException();
Item item;
if (!TryGetValue(name, out item))
base.Add(item = new Item(name));
if (value != null)
item.Add(value);
}
/// <summary>
/// A string collection of all keys in the arguments
/// </summary>
public string[] Keys
{
get
{
if (Dictionary == null) return new string[0];
List<string> list = new List<string>(Dictionary.Keys);
list.Sort();
return list.ToArray();
}
}
/// <summary>
/// Returns true if the value was found by that name and set the output value
/// </summary>
public bool TryGetValue(string name, out Item value)
{
if (name == null)
throw new ArgumentNullException();
if (Dictionary != null)
return Dictionary.TryGetValue(name, out value);
value = null;
return false;
}
/// <summary>
/// Returns true if the value was found by that name and set the output value
/// </summary>
public bool TryGetValue(string name, out string value)
{
if (name == null)
throw new ArgumentNullException();
Item test;
if (Dictionary != null && Dictionary.TryGetValue(name, out test))
{
value = test.Value;
return true;
}
value = null;
return false;
}
/// <summary>
/// Returns an Item of name even if it does not exist
/// </summary>
public Item SafeGet(string name)
{
Item result;
if (TryGetValue(name, out result))
return result;
return new Item(name, null);
}
#region Protected / Private operations...
static string CleanArgument(string argument)
{
if (argument == null) throw new ArgumentNullException();
if (argument.Length >= 2 && argument[0] == '"' && argument[argument.Length - 1] == '"')
argument = argument.Substring(1, argument.Length - 2).Replace("\"\"", "\"");
return argument;
}
/// <summary>
/// Attempts to parse a name value pair from '/name=value' format
/// </summary>
public static bool TryParseNameValue(string argument, out string name, out string value)
{
argument = CleanArgument(argument);//strip quotes
name = value = null;
if (String.IsNullOrEmpty(argument) || 0 != argument.IndexOfAny(_prefix, 0, 1))
return false;
name = argument.Substring(1);
if (String.IsNullOrEmpty(name))
return false;
int endName = name.IndexOfAny(_delim, 1);
if (endName > 0)
{
value = name.Substring(endName + 1);
name = name.Substring(0, endName);
}
return true;
}
/// <summary>
/// Searches the arguments until it finds a switch or value by the name in find and
/// if found it will:
/// A) Remove the item from the arguments
/// B) Set the out parameter value to any value found, or null if just '/name'
/// C) Returns true that it was found and removed.
/// </summary>
public static bool Remove(ref string[] arguments, string find, out string value)
{
value = null;
for (int i = 0; i < arguments.Length; i++)
{
string name, setting;
if (TryParseNameValue(arguments[i], out name, out setting) &&
_defaultCompare.Equals(name, find))
{
List<string> args = new List<string>(arguments);
args.RemoveAt(i);
arguments = args.ToArray();
value = setting;
return true;
}
}
return false;
}
/// <summary>
/// Abract override for extracting key
/// </summary>
protected override string GetKeyForItem(ArgumentList.Item item)
{
return item.Name;
}
#endregion
#region Item class used for collection
/// <summary>
/// This is a single named argument within an argument list collection, this
/// can be implicitly assigned to a string, or a string[] array
/// </summary>
[System.Diagnostics.DebuggerNonUserCode]
public class Item : System.Collections.ObjectModel.Collection<string>
{
private readonly string _name;
private readonly List<string> _values;
/// <summary>
/// Constructs an item for the name and values provided.
/// </summary>
public Item(string name, params string[] items)
: this(new List<string>(), name, items) { }
private Item(List<string> impl, string name, string[] items)
: base(impl)
{
if (name == null)
throw new ArgumentNullException();
_name = name;
_values = impl;
if (items != null)
_values.AddRange(items);
}
/// <summary>
/// Returns the name of this item
/// </summary>
public string Name { get { return _name; } }
/// <summary>
/// Returns the first value of this named item or null if one doesn't exist
/// </summary>
public string Value
{
get { return _values.Count > 0 ? _values[0] : null; }
set
{
_values.Clear();
if (value != null)
_values.Add(value);
}
}
/// <summary>
/// Returns the collection of items in this named slot
/// </summary>
public string[] Values
{
get { return _values.ToArray(); }
set
{
_values.Clear();
if (value != null)
_values.AddRange(value);
}
}
/// <summary>
/// Same as the .Values property, returns the collection of items in this named slot
/// </summary>
/// <returns></returns>
public string[] ToArray() { return _values.ToArray(); }
/// <summary>
/// Add one or more values to this named item
/// </summary>
public void AddRange(IEnumerable<string> items) { _values.AddRange(items); }
/// <summary>
/// Converts this item to key-value pair to rem to a dictionary
/// </summary>
public static implicit operator KeyValuePair<string, string[]>(Item item)
{
if (item == null) throw new ArgumentNullException();
return new KeyValuePair<string, string[]>(item.Name, item.Values);
}
/// <summary>
/// Converts this item to a string by getting the first value or null if none
/// </summary>
public static implicit operator string(Item item) { return item == null ? null : item.Value; }
/// <summary>
/// Converts this item to array of strings
/// </summary>
public static implicit operator string[](Item item) { return item == null ? null : item.Values; }
}
#endregion Item class used for collection
private class ArgReader
{
const char CharEmpty = (char)0;
char[] _chars;
int _pos;
public ArgReader(string data)
{
_chars = data.ToCharArray();
_pos = 0;
}
public bool MoveNext() { _pos++; return _pos < _chars.Length; }
public char Current { get { return (_pos < _chars.Length) ? _chars[_pos] : CharEmpty; } }
public bool IsWhiteSpace { get { return Char.IsWhiteSpace(Current); } }
public bool IsQuote { get { return (Current == '"'); } }
public bool IsEOF { get { return _pos >= _chars.Length; } }
}
/// <summary> Parses the individual arguments from the given input string. </summary>
public static string[] Parse(string rawtext)
{
List<String> list = new List<string>();
if (rawtext == null)
throw new ArgumentNullException("rawtext");
ArgReader characters = new ArgReader(rawtext.Trim());
while (!characters.IsEOF)
{
if (characters.IsWhiteSpace)
{
characters.MoveNext();
continue;
}
StringBuilder sb = new StringBuilder();
if (characters.IsQuote)
{//quoted string
while (characters.MoveNext())
{
if (characters.IsQuote)
{
if (!characters.MoveNext() || characters.IsWhiteSpace)
break;
}
sb.Append(characters.Current);
}
}
else
{
sb.Append(characters.Current);
while (characters.MoveNext())
{
if (characters.IsWhiteSpace)
break;
sb.Append(characters.Current);
}
}
list.Add(sb.ToString());
}
return list.ToArray();
}
/// <summary> The inverse of Parse, joins the arguments together and properly escapes output </summary>
[Obsolete("Consider migrating to EscapeArguments as it correctly escapes some situations that Join does not.")]
public static string Join(params string[] arguments)
{
if (arguments == null)
throw new ArgumentNullException("arguments");
char[] escaped = " \t\"&()[]{}^=;!'+,`~".ToCharArray();
StringBuilder sb = new StringBuilder();
foreach (string argument in arguments)
{
string arg = argument;
if( arg.IndexOfAny(escaped) >= 0 )
sb.AppendFormat("\"{0}\"", arg.Replace("\"", "\"\""));
else
sb.Append(arg);
sb.Append(' ');
}
return sb.ToString(0, Math.Max(0, sb.Length-1));
}
/// <summary> The 'more' correct escape/join for arguments </summary>
public static string EscapeArguments(params string[] args)
{
StringBuilder arguments = new StringBuilder();
Regex invalidChar = new Regex("[\x00\x0a\x0d]");// these can not be escaped
Regex needsQuotes = new Regex(@"\s|""");// contains whitespace or two quote characters
Regex escapeQuote = new Regex(@"(\\*)(""|$)");// one or more '\' followed with a quote or end of string
for (int carg = 0; args != null && carg < args.Length; carg++)
{
if (args[carg] == null) { throw new ArgumentNullException("args[" + carg + "]"); }
if (invalidChar.IsMatch(args[carg])) { throw new ArgumentOutOfRangeException("args[" + carg + "]"); }
if (args[carg] == String.Empty) { arguments.Append("\"\""); }
else if (!needsQuotes.IsMatch(args[carg])) { arguments.Append(args[carg]); }
else
{
arguments.Append('"');
arguments.Append(escapeQuote.Replace(args[carg],
delegate(Match m)
{
return m.Groups[1].Value + m.Groups[1].Value +
(m.Groups[2].Value == "\"" ? "\\\"" : "");
}
));
arguments.Append('"');
}
if (carg + 1 < args.Length)
arguments.Append(' ');
}
return arguments.ToString();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Xunit;
namespace System.Numerics.Tests
{
public class cast_fromTest
{
public delegate void ExceptionGenerator();
private const int NumberOfRandomIterations = 10;
private static Random s_random = new Random(100);
[Fact]
public static void RunByteExplicitCastFromBigIntegerTests()
{
byte value = 0;
BigInteger bigInteger;
// Byte Explicit Cast from BigInteger: Random value < Byte.MinValue
bigInteger = GenerateRandomBigIntegerLessThan(byte.MinValue, s_random);
value = bigInteger.ToByteArray()[0];
Assert.Throws<OverflowException>(() => VerifyByteExplicitCastFromBigInteger(value, bigInteger));
// Byte Explicit Cast from BigInteger: Byte.MinValue - 1
bigInteger = new BigInteger(byte.MinValue);
bigInteger -= BigInteger.One;
value = bigInteger.ToByteArray()[0];
Assert.Throws<OverflowException>(() => VerifyByteExplicitCastFromBigInteger(value, bigInteger));
// Byte Explicit Cast from BigInteger: Byte.MinValue
VerifyByteExplicitCastFromBigInteger(byte.MinValue);
// Byte Explicit Cast from BigInteger: 0
VerifyByteExplicitCastFromBigInteger(0);
// Byte Explicit Cast from BigInteger: 1
VerifyByteExplicitCastFromBigInteger(1);
// Byte Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyByteExplicitCastFromBigInteger((byte)s_random.Next(1, byte.MaxValue));
}
// Byte Explicit Cast from BigInteger: Byte.MaxValue + 1
bigInteger = new BigInteger(byte.MaxValue);
bigInteger += BigInteger.One;
value = bigInteger.ToByteArray()[0];
Assert.Throws<OverflowException>(() => VerifyByteExplicitCastFromBigInteger(value, bigInteger));
// Byte Explicit Cast from BigInteger: Random value > Byte.MaxValue
bigInteger = GenerateRandomBigIntegerGreaterThan(byte.MaxValue, s_random);
value = bigInteger.ToByteArray()[0];
Assert.Throws<OverflowException>(() => VerifyByteExplicitCastFromBigInteger(value, bigInteger));
}
[Fact]
public static void RunSByteExplicitCastFromBigIntegerTests()
{
sbyte value = 0;
BigInteger bigInteger;
// SByte Explicit Cast from BigInteger: Random value < SByte.MinValue
bigInteger = GenerateRandomBigIntegerLessThan(sbyte.MinValue, s_random);
value = unchecked((sbyte)bigInteger.ToByteArray()[0]);
Assert.Throws<OverflowException>(() => VerifySByteExplicitCastFromBigInteger(value, bigInteger));
// SByte Explicit Cast from BigInteger: SByte.MinValue - 1
bigInteger = new BigInteger(sbyte.MinValue);
bigInteger -= BigInteger.One;
value = (sbyte)bigInteger.ToByteArray()[0];
Assert.Throws<OverflowException>(() => VerifySByteExplicitCastFromBigInteger(value, bigInteger));
// SByte Explicit Cast from BigInteger: SByte.MinValue
VerifySByteExplicitCastFromBigInteger(sbyte.MinValue);
// SByte Explicit Cast from BigInteger: Random Negative
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifySByteExplicitCastFromBigInteger((sbyte)s_random.Next(sbyte.MinValue, 0));
}
// SByte Explicit Cast from BigInteger: -1
VerifySByteExplicitCastFromBigInteger(-1);
// SByte Explicit Cast from BigInteger: 0
VerifySByteExplicitCastFromBigInteger(0);
// SByte Explicit Cast from BigInteger: 1
VerifySByteExplicitCastFromBigInteger(1);
// SByte Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifySByteExplicitCastFromBigInteger((sbyte)s_random.Next(1, sbyte.MaxValue));
}
// SByte Explicit Cast from BigInteger: SByte.MaxValue
VerifySByteExplicitCastFromBigInteger(sbyte.MaxValue);
// SByte Explicit Cast from BigInteger: SByte.MaxValue + 1
bigInteger = new BigInteger(sbyte.MaxValue);
bigInteger += BigInteger.One;
value = unchecked((sbyte)bigInteger.ToByteArray()[0]);
Assert.Throws<OverflowException>(() => VerifySByteExplicitCastFromBigInteger(value, bigInteger));
// SByte Explicit Cast from BigInteger: Random value > SByte.MaxValue
bigInteger = GenerateRandomBigIntegerGreaterThan((ulong)sbyte.MaxValue, s_random);
value = unchecked((sbyte)bigInteger.ToByteArray()[0]);
Assert.Throws<OverflowException>(() => VerifySByteExplicitCastFromBigInteger(value, bigInteger));
}
[Fact]
public static void RunUInt16ExplicitCastFromBigIntegerTests()
{
ushort value;
BigInteger bigInteger;
// UInt16 Explicit Cast from BigInteger: Random value < UInt16.MinValue
bigInteger = GenerateRandomBigIntegerLessThan(ushort.MinValue, s_random);
value = BitConverter.ToUInt16(ByteArrayMakeMinSize(bigInteger.ToByteArray(), 2), 0);
Assert.Throws<OverflowException>(() => VerifyUInt16ExplicitCastFromBigInteger(value, bigInteger));
// UInt16 Explicit Cast from BigInteger: UInt16.MinValue - 1
bigInteger = new BigInteger(ushort.MinValue);
bigInteger -= BigInteger.One;
value = BitConverter.ToUInt16(new byte[] { 0xff, 0xff }, 0);
Assert.Throws<OverflowException>(() => VerifyUInt16ExplicitCastFromBigInteger(value, bigInteger));
// UInt16 Explicit Cast from BigInteger: UInt16.MinValue
VerifyUInt16ExplicitCastFromBigInteger(ushort.MinValue);
// UInt16 Explicit Cast from BigInteger: 0
VerifyUInt16ExplicitCastFromBigInteger(0);
// UInt16 Explicit Cast from BigInteger: 1
VerifyUInt16ExplicitCastFromBigInteger(1);
// UInt16 Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyUInt16ExplicitCastFromBigInteger((ushort)s_random.Next(1, ushort.MaxValue));
}
// UInt16 Explicit Cast from BigInteger: UInt16.MaxValue
VerifyUInt16ExplicitCastFromBigInteger(ushort.MaxValue);
// UInt16 Explicit Cast from BigInteger: UInt16.MaxValue + 1
bigInteger = new BigInteger(ushort.MaxValue);
bigInteger += BigInteger.One;
value = BitConverter.ToUInt16(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyUInt16ExplicitCastFromBigInteger(value, bigInteger));
// UInt16 Explicit Cast from BigInteger: Random value > UInt16.MaxValue
bigInteger = GenerateRandomBigIntegerGreaterThan(ushort.MaxValue, s_random);
value = BitConverter.ToUInt16(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyUInt16ExplicitCastFromBigInteger(value, bigInteger));
}
[Fact]
public static void RunInt16ExplicitCastFromBigIntegerTests()
{
short value;
BigInteger bigInteger;
// Int16 Explicit Cast from BigInteger: Random value < Int16.MinValue
bigInteger = GenerateRandomBigIntegerLessThan(short.MinValue, s_random);
value = BitConverter.ToInt16(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt16ExplicitCastFromBigInteger(value, bigInteger));
// Int16 Explicit Cast from BigInteger: Int16.MinValue - 1
bigInteger = new BigInteger(short.MinValue);
bigInteger -= BigInteger.One;
value = BitConverter.ToInt16(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt16ExplicitCastFromBigInteger(value, bigInteger));
// Int16 Explicit Cast from BigInteger: Int16.MinValue
VerifyInt16ExplicitCastFromBigInteger(short.MinValue);
// Int16 Explicit Cast from BigInteger: Random Negative
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyInt16ExplicitCastFromBigInteger((short)s_random.Next(short.MinValue, 0));
}
// Int16 Explicit Cast from BigInteger: -1
VerifyInt16ExplicitCastFromBigInteger(-1);
// Int16 Explicit Cast from BigInteger: 0
VerifyInt16ExplicitCastFromBigInteger(0);
// Int16 Explicit Cast from BigInteger: 1
VerifyInt16ExplicitCastFromBigInteger(1);
// Int16 Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyInt16ExplicitCastFromBigInteger((short)s_random.Next(1, short.MaxValue));
}
// Int16 Explicit Cast from BigInteger: Int16.MaxValue
VerifyInt16ExplicitCastFromBigInteger(short.MaxValue);
// Int16 Explicit Cast from BigInteger: Int16.MaxValue + 1
bigInteger = new BigInteger(short.MaxValue);
bigInteger += BigInteger.One;
value = BitConverter.ToInt16(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt16ExplicitCastFromBigInteger(value, bigInteger));
// Int16 Explicit Cast from BigInteger: Random value > Int16.MaxValue
bigInteger = GenerateRandomBigIntegerGreaterThan((ulong)short.MaxValue, s_random);
value = BitConverter.ToInt16(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt16ExplicitCastFromBigInteger(value, bigInteger));
}
[Fact]
public static void RunUInt32ExplicitCastFromBigIntegerTests()
{
uint value;
BigInteger bigInteger;
// UInt32 Explicit Cast from BigInteger: Random value < UInt32.MinValue
bigInteger = GenerateRandomBigIntegerLessThan(uint.MinValue, s_random);
value = BitConverter.ToUInt32(ByteArrayMakeMinSize(bigInteger.ToByteArray(), 4), 0);
Assert.Throws<OverflowException>(() => VerifyUInt32ExplicitCastFromBigInteger(value, bigInteger));
// UInt32 Explicit Cast from BigInteger: UInt32.MinValue - 1
bigInteger = new BigInteger(uint.MinValue);
bigInteger -= BigInteger.One;
value = BitConverter.ToUInt32(new byte[] { 0xff, 0xff, 0xff, 0xff }, 0);
Assert.Throws<OverflowException>(() => VerifyUInt32ExplicitCastFromBigInteger(value, bigInteger));
// UInt32 Explicit Cast from BigInteger: UInt32.MinValue
VerifyUInt32ExplicitCastFromBigInteger(uint.MinValue);
// UInt32 Explicit Cast from BigInteger: 0
VerifyUInt32ExplicitCastFromBigInteger(0);
// UInt32 Explicit Cast from BigInteger: 1
VerifyUInt32ExplicitCastFromBigInteger(1);
// UInt32 Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyUInt32ExplicitCastFromBigInteger((uint)(uint.MaxValue * s_random.NextDouble()));
}
// UInt32 Explicit Cast from BigInteger: UInt32.MaxValue
VerifyUInt32ExplicitCastFromBigInteger(uint.MaxValue);
// UInt32 Explicit Cast from BigInteger: UInt32.MaxValue + 1
bigInteger = new BigInteger(uint.MaxValue);
bigInteger += BigInteger.One;
value = BitConverter.ToUInt32(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyUInt32ExplicitCastFromBigInteger(value, bigInteger));
// UInt32 Explicit Cast from BigInteger: Random value > UInt32.MaxValue
bigInteger = GenerateRandomBigIntegerGreaterThan(uint.MaxValue, s_random);
value = BitConverter.ToUInt32(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyUInt32ExplicitCastFromBigInteger(value, bigInteger));
}
[Fact]
public static void RunInt32ExplicitCastFromBigIntegerTests()
{
int value;
BigInteger bigInteger;
// Int32 Explicit Cast from BigInteger: Random value < Int32.MinValue
bigInteger = GenerateRandomBigIntegerLessThan(int.MinValue, s_random);
value = BitConverter.ToInt32(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt32ExplicitCastFromBigInteger(value, bigInteger));
// Int32 Explicit Cast from BigInteger: Int32.MinValue - 1
bigInteger = new BigInteger(int.MinValue);
bigInteger -= BigInteger.One;
value = BitConverter.ToInt32(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt32ExplicitCastFromBigInteger(value, bigInteger));
// Int32 Explicit Cast from BigInteger: Int32.MinValue
VerifyInt32ExplicitCastFromBigInteger(int.MinValue);
// Int32 Explicit Cast from BigInteger: Random Negative
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyInt32ExplicitCastFromBigInteger((int)s_random.Next(int.MinValue, 0));
}
// Int32 Explicit Cast from BigInteger: -1
VerifyInt32ExplicitCastFromBigInteger(-1);
// Int32 Explicit Cast from BigInteger: 0
VerifyInt32ExplicitCastFromBigInteger(0);
// Int32 Explicit Cast from BigInteger: 1
VerifyInt32ExplicitCastFromBigInteger(1);
// Int32 Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyInt32ExplicitCastFromBigInteger((int)s_random.Next(1, int.MaxValue));
}
// Int32 Explicit Cast from BigInteger: Int32.MaxValue
VerifyInt32ExplicitCastFromBigInteger(int.MaxValue);
// Int32 Explicit Cast from BigInteger: Int32.MaxValue + 1
bigInteger = new BigInteger(int.MaxValue);
bigInteger += BigInteger.One;
value = BitConverter.ToInt32(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt32ExplicitCastFromBigInteger(value, bigInteger));
// Int32 Explicit Cast from BigInteger: Random value > Int32.MaxValue
bigInteger = GenerateRandomBigIntegerGreaterThan(int.MaxValue, s_random);
value = BitConverter.ToInt32(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt32ExplicitCastFromBigInteger(value, bigInteger));
}
[Fact]
public static void RunUInt64ExplicitCastFromBigIntegerTests()
{
ulong value;
BigInteger bigInteger;
// UInt64 Explicit Cast from BigInteger: Random value < UInt64.MinValue
bigInteger = GenerateRandomBigIntegerLessThan(0, s_random);
value = BitConverter.ToUInt64(ByteArrayMakeMinSize(bigInteger.ToByteArray(), 8), 0);
Assert.Throws<OverflowException>(() => VerifyUInt64ExplicitCastFromBigInteger(value, bigInteger));
// UInt64 Explicit Cast from BigInteger: UInt64.MinValue - 1
bigInteger = new BigInteger(ulong.MinValue);
bigInteger -= BigInteger.One;
value = BitConverter.ToUInt64(new byte[] { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, 0);
Assert.Throws<OverflowException>(() => VerifyUInt64ExplicitCastFromBigInteger(value, bigInteger));
// UInt64 Explicit Cast from BigInteger: UInt64.MinValue
VerifyUInt64ExplicitCastFromBigInteger(ulong.MinValue);
// UInt64 Explicit Cast from BigInteger: 0
VerifyUInt64ExplicitCastFromBigInteger(0);
// UInt64 Explicit Cast from BigInteger: 1
VerifyUInt64ExplicitCastFromBigInteger(1);
// UInt64 Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyUInt64ExplicitCastFromBigInteger((ulong)(ulong.MaxValue * s_random.NextDouble()));
}
// UInt64 Explicit Cast from BigInteger: UInt64.MaxValue
VerifyUInt64ExplicitCastFromBigInteger(ulong.MaxValue);
// UInt64 Explicit Cast from BigInteger: UInt64.MaxValue + 1
bigInteger = new BigInteger(ulong.MaxValue);
bigInteger += BigInteger.One;
value = BitConverter.ToUInt64(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyUInt64ExplicitCastFromBigInteger(value, bigInteger));
// UInt64 Explicit Cast from BigInteger: Random value > UInt64.MaxValue
bigInteger = GenerateRandomBigIntegerGreaterThan(ulong.MaxValue, s_random);
value = BitConverter.ToUInt64(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyUInt64ExplicitCastFromBigInteger(value, bigInteger));
}
[Fact]
public static void RunInt64ExplicitCastFromBigIntegerTests()
{
long value;
BigInteger bigInteger;
// Int64 Explicit Cast from BigInteger: Random value < Int64.MinValue
bigInteger = GenerateRandomBigIntegerLessThan(long.MinValue, s_random);
value = BitConverter.ToInt64(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt64ExplicitCastFromBigInteger(value, bigInteger));
// Int64 Explicit Cast from BigInteger: Int64.MinValue - 1
bigInteger = new BigInteger(long.MinValue);
bigInteger -= BigInteger.One;
value = BitConverter.ToInt64(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt64ExplicitCastFromBigInteger(value, bigInteger));
// Int64 Explicit Cast from BigInteger: Int64.MinValue
VerifyInt64ExplicitCastFromBigInteger(long.MinValue);
// Int64 Explicit Cast from BigInteger: Random Negative
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyInt64ExplicitCastFromBigInteger(((long)(long.MaxValue * s_random.NextDouble())) - long.MaxValue);
}
// Int64 Explicit Cast from BigInteger: -1
VerifyInt64ExplicitCastFromBigInteger(-1);
// Int64 Explicit Cast from BigInteger: 0
VerifyInt64ExplicitCastFromBigInteger(0);
// Int64 Explicit Cast from BigInteger: 1
VerifyInt64ExplicitCastFromBigInteger(1);
// Int64 Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyInt64ExplicitCastFromBigInteger((long)(long.MaxValue * s_random.NextDouble()));
}
// Int64 Explicit Cast from BigInteger: Int64.MaxValue
VerifyInt64ExplicitCastFromBigInteger(long.MaxValue);
// Int64 Explicit Cast from BigInteger: Int64.MaxValue + 1
bigInteger = new BigInteger(long.MaxValue);
bigInteger += BigInteger.One;
value = BitConverter.ToInt64(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt64ExplicitCastFromBigInteger(value, bigInteger));
// Int64 Explicit Cast from BigInteger: Random value > Int64.MaxValue
bigInteger = GenerateRandomBigIntegerGreaterThan(long.MaxValue, s_random);
value = BitConverter.ToInt64(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt64ExplicitCastFromBigInteger(value, bigInteger));
}
[Fact]
public static void RunSingleExplicitCastFromBigIntegerTests()
{
BigInteger bigInteger;
// Single Explicit Cast from BigInteger: Random value < Single.MinValue
bigInteger = GenerateRandomBigIntegerLessThan(float.MinValue * 2.0, s_random);
VerifySingleExplicitCastFromBigInteger(float.NegativeInfinity, bigInteger);
// Single Explicit Cast from BigInteger: Single.MinValue - 1
bigInteger = new BigInteger(float.MinValue);
bigInteger -= BigInteger.One;
VerifySingleExplicitCastFromBigInteger(float.MinValue, bigInteger);
// Single Explicit Cast from BigInteger: Single.MinValue
VerifySingleExplicitCastFromBigInteger(float.MinValue);
// Single Explicit Cast from BigInteger: Random Negative
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifySingleExplicitCastFromBigInteger(((float)(float.MaxValue * s_random.NextDouble())) - float.MaxValue);
}
// Single Explicit Cast from BigInteger: Random Negative Non-integral > -100
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifySingleExplicitCastFromBigInteger(((float)(100 * s_random.NextDouble())) - 100);
}
// Single Explicit Cast from BigInteger: -1
VerifySingleExplicitCastFromBigInteger(-1);
// Single Explicit Cast from BigInteger: 0
VerifySingleExplicitCastFromBigInteger(0);
// Single Explicit Cast from BigInteger: 1
VerifySingleExplicitCastFromBigInteger(1);
// Single Explicit Cast from BigInteger: Random Positive Non-integral < 100
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifySingleExplicitCastFromBigInteger((float)(100 * s_random.NextDouble()));
}
// Single Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifySingleExplicitCastFromBigInteger((float)(float.MaxValue * s_random.NextDouble()));
}
// Single Explicit Cast from BigInteger: Single.MaxValue + 1
bigInteger = new BigInteger(float.MaxValue);
bigInteger += BigInteger.One;
VerifySingleExplicitCastFromBigInteger(float.MaxValue, bigInteger);
// Single Explicit Cast from BigInteger: Random value > Single.MaxValue
bigInteger = GenerateRandomBigIntegerGreaterThan((double)float.MaxValue * 2, s_random);
VerifySingleExplicitCastFromBigInteger(float.PositiveInfinity, bigInteger);
// Single Explicit Cast from BigInteger: value < Single.MaxValue but can not be accurately represented in a Single
bigInteger = new BigInteger(16777217);
VerifySingleExplicitCastFromBigInteger(16777216f, bigInteger);
// Single Explicit Cast from BigInteger: Single.MinValue < value but can not be accurately represented in a Single
bigInteger = new BigInteger(-16777217);
VerifySingleExplicitCastFromBigInteger(-16777216f, bigInteger);
}
[Fact]
public static void RunDoubleExplicitCastFromBigIntegerTests()
{
BigInteger bigInteger;
// Double Explicit Cast from BigInteger: Random value < Double.MinValue
bigInteger = GenerateRandomBigIntegerLessThan(double.MinValue, s_random);
bigInteger *= 2;
VerifyDoubleExplicitCastFromBigInteger(double.NegativeInfinity, bigInteger);
// Double Explicit Cast from BigInteger: Double.MinValue - 1
bigInteger = new BigInteger(double.MinValue);
bigInteger -= BigInteger.One;
VerifyDoubleExplicitCastFromBigInteger(double.MinValue, bigInteger);
// Double Explicit Cast from BigInteger: Double.MinValue
VerifyDoubleExplicitCastFromBigInteger(double.MinValue);
// Double Explicit Cast from BigInteger: Random Negative
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyDoubleExplicitCastFromBigInteger(((double)(double.MaxValue * s_random.NextDouble())) - double.MaxValue);
}
// Double Explicit Cast from BigInteger: Random Negative Non-integral > -100
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyDoubleExplicitCastFromBigInteger(((double)(100 * s_random.NextDouble())) - 100);
}
// Double Explicit Cast from BigInteger: -1
VerifyDoubleExplicitCastFromBigInteger(-1);
// Double Explicit Cast from BigInteger: 0
VerifyDoubleExplicitCastFromBigInteger(0);
// Double Explicit Cast from BigInteger: 1
VerifyDoubleExplicitCastFromBigInteger(1);
// Double Explicit Cast from BigInteger: Random Positive Non-integral < 100
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyDoubleExplicitCastFromBigInteger((double)(100 * s_random.NextDouble()));
}
// Double Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyDoubleExplicitCastFromBigInteger((double)(double.MaxValue * s_random.NextDouble()));
}
// Double Explicit Cast from BigInteger: Double.MaxValue
VerifyDoubleExplicitCastFromBigInteger(double.MaxValue);
// Double Explicit Cast from BigInteger: Double.MaxValue + 1
bigInteger = new BigInteger(double.MaxValue);
bigInteger += BigInteger.One;
VerifyDoubleExplicitCastFromBigInteger(double.MaxValue, bigInteger);
// Double Explicit Cast from BigInteger: Double.MinValue - 1
bigInteger = new BigInteger(double.MinValue);
bigInteger -= BigInteger.One;
VerifyDoubleExplicitCastFromBigInteger(double.MinValue, bigInteger);
// Double Explicit Cast from BigInteger: Random value > Double.MaxValue
bigInteger = GenerateRandomBigIntegerGreaterThan(double.MaxValue, s_random);
bigInteger *= 2;
VerifyDoubleExplicitCastFromBigInteger(double.PositiveInfinity, bigInteger);
// Double Explicit Cast from BigInteger: Random value < -Double.MaxValue
VerifyDoubleExplicitCastFromBigInteger(double.NegativeInfinity, -bigInteger);
// Double Explicit Cast from BigInteger: very large values (more than Int32.MaxValue bits) should be infinity
DoubleExplicitCastFromLargeBigIntegerTests(128, 1);
// Double Explicit Cast from BigInteger: value < Double.MaxValue but can not be accurately represented in a Double
bigInteger = new BigInteger(9007199254740993);
VerifyDoubleExplicitCastFromBigInteger(9007199254740992, bigInteger);
// Double Explicit Cast from BigInteger: Double.MinValue < value but can not be accurately represented in a Double
bigInteger = new BigInteger(-9007199254740993);
VerifyDoubleExplicitCastFromBigInteger(-9007199254740992, bigInteger);
}
[Fact]
[OuterLoop]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void RunDoubleExplicitCastFromLargeBigIntegerTests()
{
DoubleExplicitCastFromLargeBigIntegerTests(0, 4, 32, 3);
}
[Fact]
public static void RunDecimalExplicitCastFromBigIntegerTests()
{
int[] bits = new int[3];
uint temp2;
bool carry;
byte[] temp;
decimal value;
BigInteger bigInteger;
// Decimal Explicit Cast from BigInteger: Random value < Decimal.MinValue
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
bigInteger = GenerateRandomBigIntegerLessThan(decimal.MinValue, s_random);
temp = bigInteger.ToByteArray();
carry = true;
for (int j = 0; j < 3; j++)
{
temp2 = BitConverter.ToUInt32(temp, 4 * j);
temp2 = ~temp2;
if (carry)
{
carry = false;
temp2 += 1;
if (temp2 == 0)
{
carry = true;
}
}
bits[j] = unchecked((int)temp2);
}
value = new decimal(bits[0], bits[1], bits[2], true, 0);
Assert.Throws<OverflowException>(() => VerifyDecimalExplicitCastFromBigInteger(value, bigInteger));
}
// Decimal Explicit Cast from BigInteger: Decimal.MinValue - 1
bigInteger = new BigInteger(decimal.MinValue);
bigInteger -= BigInteger.One;
temp = bigInteger.ToByteArray();
carry = true;
for (int j = 0; j < 3; j++)
{
temp2 = BitConverter.ToUInt32(temp, 4 * j);
temp2 = ~temp2;
if (carry)
{
carry = false;
temp2 = unchecked(temp2 + 1);
if (temp2 == 0)
{
carry = true;
}
}
bits[j] = (int)temp2;
}
value = new decimal(bits[0], bits[1], bits[2], true, 0);
Assert.Throws<OverflowException>(() => VerifyDecimalExplicitCastFromBigInteger(value, bigInteger));
// Decimal Explicit Cast from BigInteger: Decimal.MinValue
VerifyDecimalExplicitCastFromBigInteger(decimal.MinValue);
// Decimal Explicit Cast from BigInteger: Random Negative
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyDecimalExplicitCastFromBigInteger(((decimal)((double)decimal.MaxValue * s_random.NextDouble())) - decimal.MaxValue);
}
// Decimal Explicit Cast from BigInteger: Random Negative Non-Integral > -100
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
value = (decimal)(100 * s_random.NextDouble() - 100);
VerifyDecimalExplicitCastFromBigInteger(decimal.Truncate(value), new BigInteger(value));
}
// Decimal Explicit Cast from BigInteger: -1
VerifyDecimalExplicitCastFromBigInteger(-1);
// Decimal Explicit Cast from BigInteger: 0
VerifyDecimalExplicitCastFromBigInteger(0);
// Decimal Explicit Cast from BigInteger: 1
VerifyDecimalExplicitCastFromBigInteger(1);
// Decimal Explicit Cast from BigInteger: Random Positive Non-Integral < 100
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
value = (decimal)(100 * s_random.NextDouble());
VerifyDecimalExplicitCastFromBigInteger(decimal.Truncate(value), new BigInteger(value));
}
// Decimal Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyDecimalExplicitCastFromBigInteger((decimal)((double)decimal.MaxValue * s_random.NextDouble()));
}
// Decimal Explicit Cast from BigInteger: Decimal.MaxValue
VerifyDecimalExplicitCastFromBigInteger(decimal.MaxValue);
// Decimal Explicit Cast from BigInteger: Decimal.MaxValue + 1
bigInteger = new BigInteger(decimal.MaxValue);
bigInteger += BigInteger.One;
temp = bigInteger.ToByteArray();
for (int j = 0; j < 3; j++)
{
bits[j] = BitConverter.ToInt32(temp, 4 * j);
}
value = new decimal(bits[0], bits[1], bits[2], false, 0);
Assert.Throws<OverflowException>(() => VerifyDecimalExplicitCastFromBigInteger(value, bigInteger));
// Decimal Explicit Cast from BigInteger: Random value > Decimal.MaxValue
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
bigInteger = GenerateRandomBigIntegerGreaterThan(decimal.MaxValue, s_random);
temp = bigInteger.ToByteArray();
for (int j = 0; j < 3; j++)
{
bits[j] = BitConverter.ToInt32(temp, 4 * j);
}
value = new decimal(bits[0], bits[1], bits[2], false, 0);
Assert.Throws<OverflowException>(() => VerifyDecimalExplicitCastFromBigInteger(value, bigInteger));
}
}
/// <summary>
/// Test cast to Double on Very Large BigInteger more than (1 << Int.MaxValue)
/// Tested BigInteger are: +/-pow(2, startShift + smallLoopShift * [1..smallLoopLimit] + Int32.MaxValue * [1..bigLoopLimit])
/// Expected double is positive and negative infinity
/// Note:
/// ToString() can not operate such large values
/// </summary>
private static void DoubleExplicitCastFromLargeBigIntegerTests(int startShift, int bigShiftLoopLimit, int smallShift = 0, int smallShiftLoopLimit = 1)
{
BigInteger init = BigInteger.One << startShift;
for (int i = 0; i < smallShiftLoopLimit; i++)
{
BigInteger temp = init << ((i + 1) * smallShift);
for (int j = 0; j < bigShiftLoopLimit; j++)
{
temp = temp << (int.MaxValue / 10);
VerifyDoubleExplicitCastFromBigInteger(double.PositiveInfinity, temp);
VerifyDoubleExplicitCastFromBigInteger(double.NegativeInfinity, -temp);
}
}
}
private static BigInteger GenerateRandomNegativeBigInteger(Random random)
{
BigInteger bigInteger;
int arraySize = random.Next(1, 8) * 4;
byte[] byteArray = new byte[arraySize];
for (int i = 0; i < arraySize; ++i)
{
byteArray[i] = (byte)random.Next(0, 256);
}
byteArray[arraySize - 1] |= 0x80;
bigInteger = new BigInteger(byteArray);
return bigInteger;
}
private static BigInteger GenerateRandomPositiveBigInteger(Random random)
{
BigInteger bigInteger;
int arraySize = random.Next(1, 8) * 4;
byte[] byteArray = new byte[arraySize];
for (int i = 0; i < arraySize; ++i)
{
byteArray[i] = (byte)random.Next(0, 256);
}
byteArray[arraySize - 1] &= 0x7f;
bigInteger = new BigInteger(byteArray);
return bigInteger;
}
private static BigInteger GenerateRandomBigIntegerLessThan(long value, Random random)
{
return (GenerateRandomNegativeBigInteger(random) + value) - 1;
}
private static BigInteger GenerateRandomBigIntegerLessThan(double value, Random random)
{
return (GenerateRandomNegativeBigInteger(random) + (BigInteger)value) - 1;
}
private static BigInteger GenerateRandomBigIntegerLessThan(decimal value, Random random)
{
return (GenerateRandomNegativeBigInteger(random) + (BigInteger)value) - 1;
}
private static BigInteger GenerateRandomBigIntegerGreaterThan(ulong value, Random random)
{
return (GenerateRandomPositiveBigInteger(random) + value) + 1;
}
private static BigInteger GenerateRandomBigIntegerGreaterThan(double value, Random random)
{
return (GenerateRandomPositiveBigInteger(random) + (BigInteger)value) + 1;
}
private static BigInteger GenerateRandomBigIntegerGreaterThan(decimal value, Random random)
{
return (GenerateRandomPositiveBigInteger(random) + (BigInteger)value) + 1;
}
private static void VerifyByteExplicitCastFromBigInteger(byte value)
{
BigInteger bigInteger = new BigInteger(value);
VerifyByteExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifyByteExplicitCastFromBigInteger(byte value, BigInteger bigInteger)
{
Assert.Equal(value, (byte)bigInteger);
}
private static void VerifySByteExplicitCastFromBigInteger(sbyte value)
{
BigInteger bigInteger = new BigInteger(value);
VerifySByteExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifySByteExplicitCastFromBigInteger(sbyte value, BigInteger bigInteger)
{
Assert.Equal(value, (sbyte)bigInteger);
}
private static void VerifyUInt16ExplicitCastFromBigInteger(ushort value)
{
BigInteger bigInteger = new BigInteger(value);
VerifyUInt16ExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifyUInt16ExplicitCastFromBigInteger(ushort value, BigInteger bigInteger)
{
Assert.Equal(value, (ushort)bigInteger);
}
private static void VerifyInt16ExplicitCastFromBigInteger(short value)
{
BigInteger bigInteger = new BigInteger(value);
VerifyInt16ExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifyInt16ExplicitCastFromBigInteger(short value, BigInteger bigInteger)
{
Assert.Equal(value, (short)bigInteger);
}
private static void VerifyUInt32ExplicitCastFromBigInteger(uint value)
{
BigInteger bigInteger = new BigInteger(value);
VerifyUInt32ExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifyUInt32ExplicitCastFromBigInteger(uint value, BigInteger bigInteger)
{
Assert.Equal(value, (uint)bigInteger);
}
private static void VerifyInt32ExplicitCastFromBigInteger(int value)
{
BigInteger bigInteger = new BigInteger(value);
VerifyInt32ExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifyInt32ExplicitCastFromBigInteger(int value, BigInteger bigInteger)
{
Assert.Equal(value, (int)bigInteger);
}
private static void VerifyUInt64ExplicitCastFromBigInteger(ulong value)
{
BigInteger bigInteger = new BigInteger(value);
VerifyUInt64ExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifyUInt64ExplicitCastFromBigInteger(ulong value, BigInteger bigInteger)
{
Assert.Equal(value, (ulong)bigInteger);
}
private static void VerifyInt64ExplicitCastFromBigInteger(long value)
{
BigInteger bigInteger = new BigInteger(value);
VerifyInt64ExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifyInt64ExplicitCastFromBigInteger(long value, BigInteger bigInteger)
{
Assert.Equal(value, (long)bigInteger);
}
private static void VerifySingleExplicitCastFromBigInteger(float value)
{
BigInteger bigInteger = new BigInteger(value);
VerifySingleExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifySingleExplicitCastFromBigInteger(float value, BigInteger bigInteger)
{
Assert.Equal((float)Math.Truncate(value), (float)bigInteger);
}
private static void VerifyDoubleExplicitCastFromBigInteger(double value)
{
BigInteger bigInteger = new BigInteger(value);
VerifyDoubleExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifyDoubleExplicitCastFromBigInteger(double value, BigInteger bigInteger)
{
Assert.Equal(Math.Truncate(value), (double)bigInteger);
}
private static void VerifyDecimalExplicitCastFromBigInteger(decimal value)
{
BigInteger bigInteger = new BigInteger(value);
VerifyDecimalExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifyDecimalExplicitCastFromBigInteger(decimal value, BigInteger bigInteger)
{
Assert.Equal(value, (decimal)bigInteger);
}
public static byte[] ByteArrayMakeMinSize(byte[] input, int minSize)
{
if (input.Length >= minSize)
{
return input;
}
byte[] output = new byte[minSize];
byte filler = 0;
if ((input[input.Length - 1] & 0x80) != 0)
{
filler = 0xff;
}
for (int i = 0; i < output.Length; i++)
{
output[i] = (i < input.Length) ? input[i] : filler;
}
return output;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Xunit;
using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier<
Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier<
Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.NetFramework.Analyzers.UnitTests
{
public partial class DoNotUseInsecureDtdProcessingAnalyzerTests
{
private static DiagnosticResult GetCA3075SchemaReadCSharpResultAt(int line, int column)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments("Read");
#pragma warning restore RS0030 // Do not used banned APIs
private static DiagnosticResult GetCA3075SchemaReadBasicResultAt(int line, int column)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments("Read");
#pragma warning restore RS0030 // Do not used banned APIs
[Fact]
public async Task UseXmlSchemaReadWithoutXmlTextReaderShouldGenerateDiagnosticAsync()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.IO;
using System.Xml.Schema;
namespace TestNamespace
{
public class TestClass
{
public void TestMethod(string path)
{
TextReader tr = new StreamReader(path);
XmlSchema schema = XmlSchema.Read(tr, null);
}
}
}",
GetCA3075SchemaReadCSharpResultAt(12, 32)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.IO
Imports System.Xml.Schema
Namespace TestNamespace
Public Class TestClass
Public Sub TestMethod(path As String)
Dim tr As TextReader = New StreamReader(path)
Dim schema As XmlSchema = XmlSchema.Read(tr, Nothing)
End Sub
End Class
End Namespace",
GetCA3075SchemaReadBasicResultAt(9, 39)
);
}
[Fact]
public async Task UseXmlSchemaReadWithoutXmlTextReaderInGetShouldGenerateDiagnosticAsync()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.IO;
using System.Xml.Schema;
class TestClass
{
public XmlSchema Test
{
get
{
var src = """";
TextReader tr = new StreamReader(src);
XmlSchema schema = XmlSchema.Read(tr, null);
return schema;
}
}
}",
GetCA3075SchemaReadCSharpResultAt(13, 32)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.IO
Imports System.Xml.Schema
Class TestClass
Public ReadOnly Property Test() As XmlSchema
Get
Dim src = """"
Dim tr As TextReader = New StreamReader(src)
Dim schema As XmlSchema = XmlSchema.Read(tr, Nothing)
Return schema
End Get
End Property
End Class",
GetCA3075SchemaReadBasicResultAt(10, 39)
);
}
[Fact]
public async Task UseUseXmlSchemaReadWithoutXmlTextReaderInSetShouldGenerateDiagnosticAsync()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Data;
using System.IO;
using System.Xml.Schema;
class TestClass
{
XmlSchema privateDoc;
public XmlSchema GetDoc
{
set
{
if (value == null)
{
var src = """";
TextReader tr = new StreamReader(src);
XmlSchema schema = XmlSchema.Read(tr, null);
privateDoc = schema;
}
else
privateDoc = value;
}
}
}",
GetCA3075SchemaReadCSharpResultAt(17, 36)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Data
Imports System.IO
Imports System.Xml.Schema
Class TestClass
Private privateDoc As XmlSchema
Public WriteOnly Property GetDoc() As XmlSchema
Set
If value Is Nothing Then
Dim src = """"
Dim tr As TextReader = New StreamReader(src)
Dim schema As XmlSchema = XmlSchema.Read(tr, Nothing)
privateDoc = schema
Else
privateDoc = value
End If
End Set
End Property
End Class",
GetCA3075SchemaReadBasicResultAt(13, 43)
);
}
[Fact]
public async Task UseXmlSchemaReadWithoutXmlTextReaderInTryBlockShouldGenerateDiagnosticAsync()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Data;
using System.IO;
using System.Xml.Schema;
class TestClass
{
private void TestMethod()
{
try
{
var src = """";
TextReader tr = new StreamReader(src);
XmlSchema schema = XmlSchema.Read(tr, null);
}
catch (Exception) { throw; }
finally { }
}
}",
GetCA3075SchemaReadCSharpResultAt(14, 32)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.Data
Imports System.IO
Imports System.Xml.Schema
Class TestClass
Private Sub TestMethod()
Try
Dim src = """"
Dim tr As TextReader = New StreamReader(src)
Dim schema As XmlSchema = XmlSchema.Read(tr, Nothing)
Catch generatedExceptionName As Exception
Throw
Finally
End Try
End Sub
End Class",
GetCA3075SchemaReadBasicResultAt(11, 39)
);
}
[Fact]
public async Task UseXmlSchemaReadWithoutXmlTextReaderInCatchBlockShouldGenerateDiagnosticAsync()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Data;
using System.IO;
using System.Xml.Schema;
class TestClass
{
private void TestMethod()
{
try { }
catch (Exception)
{
var src = """";
TextReader tr = new StreamReader(src);
XmlSchema schema = XmlSchema.Read(tr, null);
}
finally { }
}
}",
GetCA3075SchemaReadCSharpResultAt(15, 36)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.Data
Imports System.IO
Imports System.Xml.Schema
Class TestClass
Private Sub TestMethod()
Try
Catch generatedExceptionName As Exception
Dim src = """"
Dim tr As TextReader = New StreamReader(src)
Dim schema As XmlSchema = XmlSchema.Read(tr, Nothing)
Finally
End Try
End Sub
End Class",
GetCA3075SchemaReadBasicResultAt(12, 39)
);
}
[Fact]
public async Task UseXmlSchemaReadWithoutXmlTextReaderInFinallyBlockShouldGenerateDiagnosticAsync()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Data;
using System.IO;
using System.Xml.Schema;
class TestClass
{
private void TestMethod()
{
try { }
catch (Exception) { throw; }
finally
{
var src = """";
TextReader tr = new StreamReader(src);
XmlSchema schema = XmlSchema.Read(tr, null);
}
}
}",
GetCA3075SchemaReadCSharpResultAt(16, 36)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.Data
Imports System.IO
Imports System.Xml.Schema
Class TestClass
Private Sub TestMethod()
Try
Catch generatedExceptionName As Exception
Throw
Finally
Dim src = """"
Dim tr As TextReader = New StreamReader(src)
Dim schema As XmlSchema = XmlSchema.Read(tr, Nothing)
End Try
End Sub
End Class",
GetCA3075SchemaReadBasicResultAt(14, 39)
);
}
[Fact]
public async Task UseXmlSchemaReadWithoutXmlTextReaderInAsyncAwaitShouldGenerateDiagnosticAsync()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Threading.Tasks;
using System.Data;
using System.IO;
using System.Xml.Schema;
class TestClass
{
private async Task TestMethod()
{
await Task.Run(() => {
var src = """";
TextReader tr = new StreamReader(src);
XmlSchema schema = XmlSchema.Read(tr, null);
});
}
private async void TestMethod2()
{
await TestMethod();
}
}",
GetCA3075SchemaReadCSharpResultAt(13, 36)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Threading.Tasks
Imports System.Data
Imports System.IO
Imports System.Xml.Schema
Class TestClass
Private Async Function TestMethod() As Task
Await Task.Run(Function()
Dim src = """"
Dim tr As TextReader = New StreamReader(src)
Dim schema As XmlSchema = XmlSchema.Read(tr, Nothing)
End Function)
End Function
Private Async Sub TestMethod2()
Await TestMethod()
End Sub
End Class",
GetCA3075SchemaReadBasicResultAt(11, 35)
);
}
[Fact]
public async Task UseXmlSchemaReadWithoutXmlTextReaderInDelegateShouldGenerateDiagnosticAsync()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Data;
using System.IO;
using System.Xml.Schema;
class TestClass
{
delegate void Del();
Del d = delegate () {
var src = """";
TextReader tr = new StreamReader(src);
XmlSchema schema = XmlSchema.Read(tr, null);
};
}",
GetCA3075SchemaReadCSharpResultAt(12, 32)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Data
Imports System.IO
Imports System.Xml.Schema
Class TestClass
Private Delegate Sub Del()
Private d As Del = Sub()
Dim src = """"
Dim tr As TextReader = New StreamReader(src)
Dim schema As XmlSchema = XmlSchema.Read(tr, Nothing)
End Sub
End Class",
GetCA3075SchemaReadBasicResultAt(11, 31)
);
}
[Fact]
public async Task UseXmlSchemaReadWithXmlTextReaderShouldNotGenerateDiagnosticAsync()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Xml;
using System.Xml.Schema;
namespace TestNamespace
{
public class UseXmlReaderForSchemaRead
{
public void TestMethod19(XmlTextReader reader)
{
XmlSchema schema = XmlSchema.Read(reader, null);
}
}
}"
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Xml
Imports System.Xml.Schema
Namespace TestNamespace
Public Class UseXmlReaderForSchemaRead
Public Sub TestMethod19(reader As XmlTextReader)
Dim schema As XmlSchema = XmlSchema.Read(reader, Nothing)
End Sub
End Class
End Namespace");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#pragma warning disable 0420 //passing volatile field by reference
using System;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
namespace System.Threading
{
public sealed class Lock
{
//
// NOTE: Lock must not have a static (class) constructor, as Lock itself is used to synchronize
// class construction. If Lock has its own class constructor, this can lead to infinite recursion.
// All static data in Lock must be pre-initialized.
//
[PreInitialized]
private static int s_maxSpinCount = -1; // -1 means the spin count has not yet beeen determined.
//
// IsLock is faster that "obj as Lock()", as it avoids the overhead of the full
// casting logic in the runtime. This is only safe because a) EETypePtr
// overloads operator == to do the right thing, and b) Lock is sealed, so we
// don't need to waste time traversing the inheritence heirarchy.
//
internal static bool IsLock(object obj)
{
return obj.EETypePtr == EETypePtr.EETypePtrOf<Lock>();
}
//
// m_state layout:
//
// bit 0: True if the lock is held, false otherwise.
//
// bit 1: True if we've set the event to wake a waiting thread. The waiter resets this to false when it
// wakes up. This avoids the overhead of setting the event multiple times.
//
// everything else: A count of the number of threads waiting on the event.
//
private const int Locked = 1;
private const int WaiterWoken = 2;
private const int WaiterCountIncrement = 4;
private const int Uncontended = 0;
private volatile int _state;
private int _owningThreadId;
private uint _recursionCount;
private volatile AutoResetEvent _lazyEvent;
private AutoResetEvent Event
{
get
{
//
// Can't use LazyInitializer.EnsureInitialized because Lock needs to stay low level enough
// for the purposes of lazy generic lookups. LazyInitializer uses a generic delegate.
//
if (_lazyEvent == null)
Interlocked.CompareExchange(ref _lazyEvent, new AutoResetEvent(false), null);
return _lazyEvent;
}
}
/// <remarks>Inlined version of Lock.Acquire has CurrentManagedThreadId not inlined, non-inlined version has it inlined.
/// So it saves code to keep this function non inlining while keep the same runtime cost</remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
public void Acquire()
{
int currentThreadId = Environment.CurrentManagedThreadId;
//
// Make one quick attempt to acquire an uncontended lock
//
if (Interlocked.CompareExchange(ref _state, Locked, Uncontended) == Uncontended)
{
Contract.Assert(_owningThreadId == 0);
Contract.Assert(_recursionCount == 0);
_owningThreadId = currentThreadId;
return;
}
//
// Fall back to the slow path for contention
//
bool success = TryAcquireContended(currentThreadId, Timeout.Infinite);
Contract.Assert(success);
}
public bool TryAcquire(TimeSpan timeout)
{
long tm = (long)timeout.TotalMilliseconds;
if (tm < -1 || tm > (long)Int32.MaxValue)
throw new ArgumentOutOfRangeException("timeout", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return TryAcquire((int)tm);
}
public bool TryAcquire(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
throw new ArgumentOutOfRangeException("millisecondsTimeout", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
int currentThreadId = Environment.CurrentManagedThreadId;
//
// Make one quick attempt to acquire an uncontended lock
//
if (Interlocked.CompareExchange(ref _state, Locked, Uncontended) == Uncontended)
{
Contract.Assert(_owningThreadId == 0);
Contract.Assert(_recursionCount == 0);
_owningThreadId = currentThreadId;
return true;
}
//
// Fall back to the slow path for contention
//
return TryAcquireContended(currentThreadId, millisecondsTimeout);
}
private bool TryAcquireContended(int currentThreadId, int millisecondsTimeout)
{
//
// If we already own the lock, just increment the recursion count.
//
if (_owningThreadId == currentThreadId)
{
checked { _recursionCount++; }
return true;
}
//
// We've already made one lock attempt at this point, so bail early if the timeout is zero.
//
if (millisecondsTimeout == 0)
return false;
int spins = 1;
if (s_maxSpinCount < 0)
{
s_maxSpinCount = (Environment.ProcessorCount > 1) ? 10000 : 0;
}
while (true)
{
//
// Try to grab the lock. We may take the lock here even if there are existing waiters. This creates the possibility
// of starvation of waiters, but it also prevents lock convoys from destroying perf.
// The starvation issue is largely mitigated by the priority boost the OS gives to a waiter when we set
// the event, after we release the lock. Eventually waiters will be boosted high enough to preempt this thread.
//
int oldState = _state;
if ((oldState & Locked) == 0 && Interlocked.CompareExchange(ref _state, oldState | Locked, oldState) == oldState)
goto GotTheLock;
//
// Back off by a factor of 2 for each attempt, up to MaxSpinCount
//
if (spins <= s_maxSpinCount)
{
System.Runtime.RuntimeImports.RhSpinWait(spins);
spins *= 2;
}
else
{
//
// We reached our spin limit, and need to wait. Increment the waiter count.
// Note that we do not do any overflow checking on this increment. In order to overflow,
// we'd need to have about 1 billion waiting threads, which is inconceivable anytime in the
// forseeable future.
//
int newState = (oldState + WaiterCountIncrement) & ~WaiterWoken;
if (Interlocked.CompareExchange(ref _state, newState, oldState) == oldState)
break;
}
}
//
// Now we wait.
//
TimeoutTracker timeoutTracker = TimeoutTracker.Start(millisecondsTimeout);
AutoResetEvent ev = Event;
while (true)
{
Contract.Assert(_state >= WaiterCountIncrement);
bool waitSucceeded = ev.WaitOne(timeoutTracker.Remaining);
while (true)
{
int oldState = _state;
Contract.Assert(oldState >= WaiterCountIncrement);
// Clear the "waiter woken" bit.
int newState = oldState & ~WaiterWoken;
if ((oldState & Locked) == 0)
{
// The lock is available, try to get it.
newState |= Locked;
newState -= WaiterCountIncrement;
if (Interlocked.CompareExchange(ref _state, newState, oldState) == oldState)
goto GotTheLock;
}
else if (!waitSucceeded)
{
// The lock is not available, and we timed out. We're not going to wait agin.
newState -= WaiterCountIncrement;
if (Interlocked.CompareExchange(ref _state, newState, oldState) == oldState)
return false;
}
else
{
// The lock is not available, and we didn't time out. We're going to wait again.
if (Interlocked.CompareExchange(ref _state, newState, oldState) == oldState)
break;
}
}
}
GotTheLock:
Contract.Assert((_state | Locked) != 0);
Contract.Assert(_owningThreadId == 0);
Contract.Assert(_recursionCount == 0);
_owningThreadId = currentThreadId;
return true;
}
public bool IsAcquired
{
get
{
//
// Compare the current owning thread ID with the current thread ID. We need
// to read the current thread's ID before we read m_owningThreadId. Otherwise,
// the following might happen:
//
// 1) We read m_owningThreadId, and get, say 42, which belongs to another thread.
// 2) Thread 42 releases the lock, and exits.
// 3) We call CurrentManagedThreadId. If this is the first time it's been called
// on this thread, we'll go get a new ID. We may reuse thread 42's ID, since
// that thread is dead.
// 4) Now we're thread 42, and it looks like we own the lock, even though we don't.
//
// However, as long as we get this thread's ID first, we know it won't be reused,
// because while we're doing this check the current thread is definitely still
// alive.
//
int currentManagedThreadId = Environment.CurrentManagedThreadId;
bool acquired = (currentManagedThreadId == _owningThreadId);
if (acquired)
Contract.Assert((_state & Locked) != 0);
return acquired;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public void Release()
{
if (!IsAcquired)
throw new SynchronizationLockException();
if (_recursionCount > 0)
_recursionCount--;
else
ReleaseCore();
}
internal uint ReleaseAll()
{
Contract.Assert(IsAcquired);
uint recursionCount = _recursionCount;
_recursionCount = 0;
ReleaseCore();
return recursionCount;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ReleaseCore()
{
Contract.Assert(_recursionCount == 0);
_owningThreadId = 0;
//
// Make one quick attempt to release an uncontended lock
//
if (Interlocked.CompareExchange(ref _state, Uncontended, Locked) == Locked)
return;
//
// We have waiters; take the slow path.
//
ReleaseContended();
}
private void ReleaseContended()
{
Contract.Assert(_recursionCount == 0);
Contract.Assert(_owningThreadId == 0);
while (true)
{
int oldState = _state;
// clear the lock bit.
int newState = oldState & ~Locked;
if (oldState >= WaiterCountIncrement && (oldState & WaiterWoken) == 0)
{
// there are waiters, and nobody has woken one.
newState |= WaiterWoken;
if (Interlocked.CompareExchange(ref _state, newState, oldState) == oldState)
{
Event.Set();
return;
}
}
else
{
// no need to wake a waiter.
if (Interlocked.CompareExchange(ref _state, newState, oldState) == oldState)
return;
}
}
}
internal void Reacquire(uint previousRecursionCount)
{
Acquire();
Contract.Assert(_recursionCount == 0);
_recursionCount = previousRecursionCount;
}
internal struct TimeoutTracker
{
private int _start;
private int _timeout;
public static TimeoutTracker Start(int timeout)
{
TimeoutTracker tracker = new TimeoutTracker();
tracker._timeout = timeout;
if (timeout != Timeout.Infinite)
tracker._start = Environment.TickCount;
return tracker;
}
public int Remaining
{
get
{
if (_timeout == Timeout.Infinite)
return Timeout.Infinite;
int elapsed = Environment.TickCount - _start;
if (elapsed > _timeout)
return 0;
return _timeout - elapsed;
}
}
}
}
}
| |
// ReSharper disable All
using Irony.Ast;
using Irony.Interpreter;
using Irony.Interpreter.Ast;
using Irony.Parsing;
using iSukces.Code.Irony;
using System.Collections.Generic;
namespace Samples.Irony.AmmyGrammar
{
partial class AmmyGrammar : InterpretedLanguageGrammar
{
public void AutoInit()
{
// generator : IronyAutocodeGenerator.Add_AutoInit:164
// init 1
__identifier = TerminalFactory.CreateCSharpIdentifier("identifier");
__stringLiteral = TerminalFactory.CreateCSharpString("stringLiteral");
__numberLiteral = TerminalFactory.CreateCSharpNumber("numberLiteral");
__numberLiteral.Options = NumberOptions.AllowSign
| NumberOptions.AllowUnderscore;
__end_of_using_statement = new NonTerminal("end_of_using_statement", typeof(Samples.Irony.AmmyGrammar.Ast.BaseAstNode));
__domain_style_name = new NonTerminal("domain_style_name", typeof(Samples.Irony.AmmyGrammar.Ast.AstDomainStyleName));
__using_statement = new NonTerminal("using_statement", typeof(Samples.Irony.AmmyGrammar.Ast.AstUsingStatement));
__using_statement_collection = new NonTerminal("using_statement_collection", typeof(Samples.Irony.AmmyGrammar.Ast.AstUsingStatementCollection));
__boolean_value = new NonTerminal("boolean_value", typeof(Samples.Irony.AmmyGrammar.Ast.AstBooleanValue));
__ammy_value = new NonTerminal("ammy_value", typeof(Samples.Irony.AmmyGrammar.Ast.AstAmmyValue));
__property_set_statement = new NonTerminal("property_set_statement", typeof(Samples.Irony.AmmyGrammar.Ast.AstPropertySetStatement));
__object_body_element = new NonTerminal("object_body_element", typeof(Samples.Irony.AmmyGrammar.Ast.AstObjectBodyElement));
__object_body_one_line = new NonTerminal("object_body_one_line", typeof(Samples.Irony.AmmyGrammar.Ast.AstObjectBodyOneLine));
__object_body = new NonTerminal("object_body", typeof(Samples.Irony.AmmyGrammar.Ast.AstObjectBody));
__object_body_in_curly_brackets = new NonTerminal("object_body_in_curly_brackets", typeof(Samples.Irony.AmmyGrammar.Ast.AstObjectBodyInCurlyBrackets));
__main_object_statement = new NonTerminal("main_object_statement", typeof(Samples.Irony.AmmyGrammar.Ast.AstMainObjectStatement));
__object_name_key_prefix = new NonTerminal("object_name_key_prefix", typeof(Samples.Irony.AmmyGrammar.Ast.AstObjectNameKeyPrefix));
__object_name_key_prefix_optional = new NonTerminal("object_name_key_prefix_optional", typeof(Samples.Irony.AmmyGrammar.Ast.AstObjectNameKeyPrefixOptional));
__object_name = new NonTerminal("object_name", typeof(Samples.Irony.AmmyGrammar.Ast.AstObjectName));
__object_name_optional = new NonTerminal("object_name_optional", typeof(Samples.Irony.AmmyGrammar.Ast.AstObjectNameOptional));
__object_statement = new NonTerminal("object_statement", typeof(Samples.Irony.AmmyGrammar.Ast.AstObjectStatement));
__ammy_program = new NonTerminal("ammy_program", typeof(Samples.Irony.AmmyGrammar.Ast.AstAmmyProgram));
// == init Terminals
__comma = ToTerm(",");
__dot = ToTerm(".");
__doubledot = ToTerm(":");
__parOpen = ToTerm("(");
__parClose = ToTerm(")");
__curlyOpen = ToTerm("{");
__curlyClose = ToTerm("}");
__squareOpen = ToTerm("[");
__squareClose = ToTerm("]");
__true = ToTerm("true");
__false = ToTerm("false");
__using = ToTerm("using");
__key = ToTerm("Key");
// == init NonTerminals
__end_of_using_statement.Rule = NewLinePlus | Eof;
__domain_style_name.Rule = MakeStarRule(__domain_style_name, __dot, __identifier);
__using_statement.Rule = ToTerm("using") + __domain_style_name + __end_of_using_statement;
__using_statement_collection.Rule = MakeStarRule(__using_statement_collection, null, __using_statement);
__boolean_value.Rule = __true | __false;
__ammy_value.Rule = __stringLiteral | __numberLiteral | __boolean_value;
__property_set_statement.Rule = __identifier + __doubledot + __ammy_value;
__object_body_element.Rule = __property_set_statement | __ammy_value;
__object_body_one_line.Rule = MakePlusRule(__object_body_one_line, __comma, __object_body_element);
__object_body.Rule = MakeListRule(__object_body, NewLinePlus, __object_body_one_line, TermListOptions.StarList | TermListOptions.AllowTrailingDelimiter);
__object_body_in_curly_brackets.Rule = ToTerm("{") + __object_body + ToTerm("}");
__main_object_statement.Rule = __domain_style_name + __stringLiteral + this.PreferShiftHere() + __object_body_in_curly_brackets;
__object_name_key_prefix.Rule = ToTerm("Key") + ToTerm("=");
__object_name_key_prefix_optional.Rule = Empty | __object_name_key_prefix;
__object_name.Rule = __object_name_key_prefix_optional + __stringLiteral;
__object_name_optional.Rule = Empty | __object_name;
__object_statement.Rule = __domain_style_name + __object_name_optional + __object_body_in_curly_brackets;
__ammy_program.Rule = __using_statement_collection + __main_object_statement + NewLineStar;
// == brackets
RegisterBracePair("(", ")");
RegisterBracePair("{", "}");
RegisterBracePair("[", "]");
// == mark reserved words
MarkReservedWords("true", "false", "using", "Key");
// == mark punctuations
MarkPunctuation(",", ".", ":");
NonGrammarTerminals.Add(SingleLineComment);
NonGrammarTerminals.Add(DelimitedComment);
Root = __ammy_program;
}
public CommentTerminal SingleLineComment = new CommentTerminal("SingleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029");
public CommentTerminal DelimitedComment = new CommentTerminal("DelimitedComment", "/*", "*/");
private IdentifierTerminal __identifier;
private NumberLiteral __numberLiteral;
private StringLiteral __stringLiteral;
private KeyTerm __comma;
private KeyTerm __curlyClose;
private KeyTerm __curlyOpen;
private KeyTerm __dot;
private KeyTerm __doubledot;
private KeyTerm __false;
private KeyTerm __key;
private KeyTerm __parClose;
private KeyTerm __parOpen;
private KeyTerm __squareClose;
private KeyTerm __squareOpen;
private KeyTerm __true;
private KeyTerm __using;
private NonTerminal __ammy_program;
private NonTerminal __ammy_value;
private NonTerminal __boolean_value;
private NonTerminal __domain_style_name;
private NonTerminal __end_of_using_statement;
private NonTerminal __main_object_statement;
private NonTerminal __object_body;
private NonTerminal __object_body_element;
private NonTerminal __object_body_in_curly_brackets;
private NonTerminal __object_body_one_line;
private NonTerminal __object_name;
private NonTerminal __object_name_key_prefix;
private NonTerminal __object_name_key_prefix_optional;
private NonTerminal __object_name_optional;
private NonTerminal __object_statement;
private NonTerminal __property_set_statement;
private NonTerminal __using_statement;
private NonTerminal __using_statement_collection;
}
}
namespace Samples.Irony.AmmyGrammar.Ast
{
using Samples.Irony.AmmyGrammar.Data;
/// <summary>
/// sequence of __using_statement_collection [AstUsingStatementCollection, AmmyUsingStatementCollection], __main_object_statement [AstMainObjectStatement, AmmyMainObjectStatement]
/// </summary>
public partial class AstAmmyProgram : BaseAstNode
{
public AmmyMainObjectStatement GetObjectDefinitionValue(ScriptThread thread)
{
// generator : AstClassesGenerator.Process_SequenceRule:335
var tmp = ObjectDefinition.Evaluate(thread);
var result = (AmmyMainObjectStatement)tmp;
return result;
}
public AmmyUsingStatementCollection GetUsingsValue(ScriptThread thread)
{
// generator : AstClassesGenerator.Process_SequenceRule:335
var tmp = Usings.Evaluate(thread);
var result = (AmmyUsingStatementCollection)tmp;
return result;
}
public override void Init(AstContext context, ParseTreeNode treeNode)
{
base.Init(context, treeNode);
AsString = "Sequence ammy_program";
}
protected override object DoEvaluate(ScriptThread thread)
{
// generator : ForSequenceRule.Create:44
var usings = GetUsingsValue(thread);
var objectDefinition = GetObjectDefinitionValue(thread);
var doEvaluateResult = new AmmyProgram(Span, usings, objectDefinition);
return doEvaluateResult;
}
// created AstClassesGenerator.Add_GetMap:96
protected override int[] GetMap()
{
return new [] { 0, 1 };
}
// created AstClassesGenerator.Process_SequenceRule:314
/// <summary>
/// Index = 0
/// </summary>
public AstUsingStatementCollection Usings
{
get { return (AstUsingStatementCollection)ChildNodes[0]; }
}
// created AstClassesGenerator.Process_SequenceRule:314
/// <summary>
/// Index = 1
/// </summary>
public AstMainObjectStatement ObjectDefinition
{
get { return (AstMainObjectStatement)ChildNodes[1]; }
}
}
/// <summary>
/// rule = alternative: __stringLiteral, __numberLiteral, __boolean_value
/// </summary>
public partial class AstAmmyValue : BaseAstNode
{
public AstAmmyValueNodeKinds GetNodeKind()
{
// generator : AstClassesGenerator.Process_Alternative:203
switch (OptionNode)
{
// AstType = StringLiteral
// DataType = string
// NodeType = LiteralValueNode
case LiteralValueNode _:
return AstAmmyValueNodeKinds.StringLiteral;
// AstType = NumberLiteral
// DataType = int
// NodeType = FakeCSharpNumber
case FakeCSharpNumber _:
return AstAmmyValueNodeKinds.NumberLiteral;
// AstType = AstBooleanValue
// DataType = AmmyBooleanValue
// NodeType = AstBooleanValue
case AstBooleanValue _:
return AstAmmyValueNodeKinds.BooleanValue;
}
return AstAmmyValueNodeKinds.Unknown;
}
public override void Init(AstContext context, ParseTreeNode treeNode)
{
base.Init(context, treeNode);
}
protected override object DoEvaluate(ScriptThread thread)
{
// generator : ForAlternative.Create:44
var altValue = base.DoEvaluate(thread);
var nodeKind = GetNodeKind();
var doEvaluateResult = new AmmyValue(Span, altValue, nodeKind);
return doEvaluateResult;
}
// created AstClassesGenerator.Add_GetMap:96
protected override int[] GetMap()
{
return new [] { 0 };
}
// created AstClassesGenerator.Process_Alternative:182
public AstNode OptionNode
{
get { return ChildNodes[0]; }
}
}
/// <summary>
/// rule = alternative: __true, __false
/// </summary>
public partial class AstBooleanValue : BaseAstNode
{
public AstBooleanValueNodeKinds GetNodeKind()
{
// generator : AstClassesGenerator.Process_Alternative:203
switch (OptionNode)
{
}
return AstBooleanValueNodeKinds.Unknown;
}
public override void Init(AstContext context, ParseTreeNode treeNode)
{
base.Init(context, treeNode);
}
protected override object DoEvaluate(ScriptThread thread)
{
// generator : ForAlternative.Create:44
var altValue = base.DoEvaluate(thread);
var nodeKind = GetNodeKind();
var doEvaluateResult = new AmmyBooleanValue(Span, altValue, nodeKind);
return doEvaluateResult;
}
// created AstClassesGenerator.Add_GetMap:96
protected override int[] GetMap()
{
return new [] { 0 };
}
// created AstClassesGenerator.Process_Alternative:182
public AstNode OptionNode
{
get { return ChildNodes[0]; }
}
}
/// <summary>
/// zero or more __identifierIdentifierTerminal, string
/// </summary>
public partial class AstDomainStyleName : BaseAstNode
{
public IReadOnlyList<string> EvaluateItems()
{
var cnt = ChildNodes.Count;
var result = new string[cnt];
for (var i = cnt - 1; i >= 0; i--)
{
var childNode = ChildNodes[i];
result[i] = ((IdentifierNode)childNode).Symbol;
}
return result;
}
public IEnumerable<IdentifierNode> GetItems()
{
var cnt = ChildNodes.Count;
for (var i = 0; i < cnt; i++)
{
var el = ChildNodes[i];
yield return (IdentifierNode)el;
}
}
public override void Init(AstContext context, ParseTreeNode treeNode)
{
base.Init(context, treeNode);
AsString = "Collection of identifier";
}
protected override object DoEvaluate(ScriptThread thread)
{
// generator : ForPlusOrStar.Create:44
var items = EvaluateItems();
var doEvaluateResult = new AmmyDomainStyleName(Span, items);
return doEvaluateResult;
}
}
/// <summary>
/// sequence of __domain_style_name [AstDomainStyleName, AmmyDomainStyleName], __stringLiteral [StringLiteral, string], __object_body_in_curly_brackets [AstObjectBodyInCurlyBrackets, AmmyObjectBodyInCurlyBrackets]
/// </summary>
public partial class AstMainObjectStatement : BaseAstNode
{
public AmmyDomainStyleName GetBaseObjectTypeValue(ScriptThread thread)
{
// generator : AstClassesGenerator.Process_SequenceRule:335
var tmp = BaseObjectType.Evaluate(thread);
var result = (AmmyDomainStyleName)tmp;
return result;
}
public AmmyObjectBodyInCurlyBrackets GetBodyValue(ScriptThread thread)
{
// generator : AstClassesGenerator.Process_SequenceRule:335
var tmp = Body.Evaluate(thread);
var result = (AmmyObjectBodyInCurlyBrackets)tmp;
return result;
}
public string GetFullTypeNameValue()
{
// generator : AstClassesGenerator.Process_SequenceRule:335
var result = FullTypeName.Value?.ToString();
return result;
}
public override void Init(AstContext context, ParseTreeNode treeNode)
{
base.Init(context, treeNode);
AsString = "Sequence main_object_statement";
}
protected override object DoEvaluate(ScriptThread thread)
{
// generator : ForSequenceRule.Create:44
var baseObjectType = GetBaseObjectTypeValue(thread);
var fullTypeName = GetFullTypeNameValue();
var body = GetBodyValue(thread);
var doEvaluateResult = new AmmyMainObjectStatement(Span, baseObjectType, fullTypeName, body);
return doEvaluateResult;
}
// created AstClassesGenerator.Add_GetMap:96
protected override int[] GetMap()
{
return new [] { 0, 1, 2 };
}
// created AstClassesGenerator.Process_SequenceRule:314
/// <summary>
/// Index = 0
/// </summary>
public AstDomainStyleName BaseObjectType
{
get { return (AstDomainStyleName)ChildNodes[0]; }
}
// created AstClassesGenerator.Process_SequenceRule:314
/// <summary>
/// Index = 1
/// </summary>
public LiteralValueNode FullTypeName
{
get { return (LiteralValueNode)ChildNodes[1]; }
}
// created AstClassesGenerator.Process_SequenceRule:314
/// <summary>
/// Index = 2
/// </summary>
public AstObjectBodyInCurlyBrackets Body
{
get { return (AstObjectBodyInCurlyBrackets)ChildNodes[2]; }
}
}
/// <summary>
/// zero or more __object_body_one_line
/// </summary>
public partial class AstObjectBody : BaseAstNode
{
public IReadOnlyList<AmmyObjectBodyOneLine> EvaluateItems(ScriptThread thread)
{
var cnt = ChildNodes.Count;
var result = new AmmyObjectBodyOneLine[cnt];
for (var i = cnt - 1; i >= 0; i--)
{
var childNode = ChildNodes[i];
result[i] = (AmmyObjectBodyOneLine)childNode.Evaluate(thread);
}
return result;
}
public IEnumerable<AstObjectBodyOneLine> GetItems()
{
var cnt = ChildNodes.Count;
for (var i = 0; i < cnt; i++)
{
var el = ChildNodes[i];
yield return (AstObjectBodyOneLine)el;
}
}
public override void Init(AstContext context, ParseTreeNode treeNode)
{
base.Init(context, treeNode);
AsString = "Collection of object_body_one_line";
}
protected override object DoEvaluate(ScriptThread thread)
{
// generator : ForPlusOrStar.Create:44
var items = EvaluateItems(thread);
var doEvaluateResult = new AmmyObjectBody(Span, items);
return doEvaluateResult;
}
}
/// <summary>
/// rule = alternative: __property_set_statement, __ammy_value
/// </summary>
public partial class AstObjectBodyElement : BaseAstNode
{
public AstObjectBodyElementNodeKinds GetNodeKind()
{
// generator : AstClassesGenerator.Process_Alternative:203
switch (OptionNode)
{
// AstType = AstPropertySetStatement
// DataType = AmmyPropertySetStatement
// NodeType = AstPropertySetStatement
case AstPropertySetStatement _:
return AstObjectBodyElementNodeKinds.PropertySetStatement;
// AstType = AstAmmyValue
// DataType = AmmyValue
// NodeType = AstAmmyValue
case AstAmmyValue _:
return AstObjectBodyElementNodeKinds.AmmyValue;
}
return AstObjectBodyElementNodeKinds.Unknown;
}
public override void Init(AstContext context, ParseTreeNode treeNode)
{
base.Init(context, treeNode);
}
protected override object DoEvaluate(ScriptThread thread)
{
// generator : ForAlternative.Create:44
var altValue = base.DoEvaluate(thread);
var nodeKind = GetNodeKind();
var doEvaluateResult = new AmmyObjectBodyElement(Span, altValue, nodeKind);
return doEvaluateResult;
}
// created AstClassesGenerator.Add_GetMap:96
protected override int[] GetMap()
{
return new [] { 0 };
}
// created AstClassesGenerator.Process_Alternative:182
public AstNode OptionNode
{
get { return ChildNodes[0]; }
}
}
/// <summary>
/// sequence of __object_body [AstObjectBody, AmmyObjectBody]
/// </summary>
public partial class AstObjectBodyInCurlyBrackets : BaseAstNode
{
public AmmyObjectBody GetBodyValue(ScriptThread thread)
{
// generator : AstClassesGenerator.Process_SequenceRule:335
var tmp = Body.Evaluate(thread);
var result = (AmmyObjectBody)tmp;
return result;
}
public override void Init(AstContext context, ParseTreeNode treeNode)
{
base.Init(context, treeNode);
AsString = "Sequence object_body_in_curly_brackets";
}
protected override object DoEvaluate(ScriptThread thread)
{
// generator : ForSequenceRule.Create:44
var body = GetBodyValue(thread);
var doEvaluateResult = new AmmyObjectBodyInCurlyBrackets(Span, body);
return doEvaluateResult;
}
// created AstClassesGenerator.Add_GetMap:96
protected override int[] GetMap()
{
return new [] { 1 };
}
// created AstClassesGenerator.Process_SequenceRule:314
/// <summary>
/// Index = 1
/// </summary>
public AstObjectBody Body
{
get { return (AstObjectBody)ChildNodes[1]; }
}
}
/// <summary>
/// one or more __object_body_element
/// </summary>
public partial class AstObjectBodyOneLine : BaseAstNode
{
public IReadOnlyList<AmmyObjectBodyElement> EvaluateItems(ScriptThread thread)
{
var cnt = ChildNodes.Count;
var result = new AmmyObjectBodyElement[cnt];
for (var i = cnt - 1; i >= 0; i--)
{
var childNode = ChildNodes[i];
result[i] = (AmmyObjectBodyElement)childNode.Evaluate(thread);
}
return result;
}
public IEnumerable<AstObjectBodyElement> GetItems()
{
var cnt = ChildNodes.Count;
for (var i = 0; i < cnt; i++)
{
var el = ChildNodes[i];
yield return (AstObjectBodyElement)el;
}
}
public override void Init(AstContext context, ParseTreeNode treeNode)
{
base.Init(context, treeNode);
AsString = "Collection of object_body_element";
}
protected override object DoEvaluate(ScriptThread thread)
{
// generator : ForPlusOrStar.Create:44
var items = EvaluateItems(thread);
var doEvaluateResult = new AmmyObjectBodyOneLine(Span, items);
return doEvaluateResult;
}
}
/// <summary>
/// sequence of
/// </summary>
public partial class AstObjectName : BaseAstNode
{
public override void Init(AstContext context, ParseTreeNode treeNode)
{
base.Init(context, treeNode);
AsString = "Sequence object_name";
}
protected override object DoEvaluate(ScriptThread thread)
{
// generator : ForSequenceRule.Create:44
var doEvaluateResult = new AmmyObjectName(Span);
return doEvaluateResult;
}
}
/// <summary>
/// sequence of
/// </summary>
public partial class AstObjectNameKeyPrefix : BaseAstNode
{
public override void Init(AstContext context, ParseTreeNode treeNode)
{
base.Init(context, treeNode);
AsString = "Sequence object_name_key_prefix";
}
protected override object DoEvaluate(ScriptThread thread)
{
// generator : ForSequenceRule.Create:44
var doEvaluateResult = new AmmyObjectNameKeyPrefix(Span);
return doEvaluateResult;
}
}
/// <summary>
/// rule = alternative: Empty, __object_name_key_prefix
/// </summary>
public partial class AstObjectNameKeyPrefixOptional : BaseAstNode
{
public override void Init(AstContext context, ParseTreeNode treeNode)
{
base.Init(context, treeNode);
}
// created AstClassesGenerator.Process_OptionAlternative:239
public AstObjectNameKeyPrefix Optional { get; private set; }
}
/// <summary>
/// rule = alternative: Empty, __object_name
/// </summary>
public partial class AstObjectNameOptional : BaseAstNode
{
public override void Init(AstContext context, ParseTreeNode treeNode)
{
base.Init(context, treeNode);
}
// created AstClassesGenerator.Process_OptionAlternative:239
public AstObjectName Optional { get; private set; }
}
/// <summary>
/// sequence of __domain_style_name [AstDomainStyleName, AmmyDomainStyleName], __object_name_optional [AstObjectNameOptional, AmmyObjectNameOptional]
/// </summary>
public partial class AstObjectStatement : BaseAstNode
{
public AmmyObjectNameOptional GetObjectNameValue(ScriptThread thread)
{
// generator : AstClassesGenerator.Process_SequenceRule:335
var tmp = ObjectName.Evaluate(thread);
var result = (AmmyObjectNameOptional)tmp;
return result;
}
public AmmyDomainStyleName GetObjectTypeValue(ScriptThread thread)
{
// generator : AstClassesGenerator.Process_SequenceRule:335
var tmp = ObjectType.Evaluate(thread);
var result = (AmmyDomainStyleName)tmp;
return result;
}
public override void Init(AstContext context, ParseTreeNode treeNode)
{
base.Init(context, treeNode);
AsString = "Sequence object_statement";
}
protected override object DoEvaluate(ScriptThread thread)
{
// generator : ForSequenceRule.Create:44
var objectType = GetObjectTypeValue(thread);
var objectName = GetObjectNameValue(thread);
var doEvaluateResult = new AmmyObjectStatement(Span, objectType, objectName);
return doEvaluateResult;
}
// created AstClassesGenerator.Add_GetMap:96
protected override int[] GetMap()
{
return new [] { 0, 1 };
}
// created AstClassesGenerator.Process_SequenceRule:314
/// <summary>
/// Index = 0
/// </summary>
public AstDomainStyleName ObjectType
{
get { return (AstDomainStyleName)ChildNodes[0]; }
}
// created AstClassesGenerator.Process_SequenceRule:314
/// <summary>
/// Index = 1
/// </summary>
public AstObjectNameOptional ObjectName
{
get { return (AstObjectNameOptional)ChildNodes[1]; }
}
}
/// <summary>
/// sequence of __identifier [IdentifierTerminal, string], __ammy_value [AstAmmyValue, AmmyValue]
/// </summary>
public partial class AstPropertySetStatement : BaseAstNode
{
public string GetPropertyNameValue()
{
// generator : AstClassesGenerator.Process_SequenceRule:335
var result = PropertyName.Symbol;
return result;
}
public AmmyValue GetPropertyValueValue(ScriptThread thread)
{
// generator : AstClassesGenerator.Process_SequenceRule:335
var tmp = PropertyValue.Evaluate(thread);
var result = (AmmyValue)tmp;
return result;
}
public override void Init(AstContext context, ParseTreeNode treeNode)
{
base.Init(context, treeNode);
AsString = "Sequence property_set_statement";
}
protected override object DoEvaluate(ScriptThread thread)
{
// generator : ForSequenceRule.Create:44
var propertyName = GetPropertyNameValue();
var propertyValue = GetPropertyValueValue(thread);
var doEvaluateResult = new AmmyPropertySetStatement(Span, propertyName, propertyValue);
return doEvaluateResult;
}
// created AstClassesGenerator.Add_GetMap:96
protected override int[] GetMap()
{
return new [] { 0, 1 };
}
// created AstClassesGenerator.Process_SequenceRule:314
/// <summary>
/// Index = 0
/// </summary>
public IdentifierNode PropertyName
{
get { return (IdentifierNode)ChildNodes[0]; }
}
// created AstClassesGenerator.Process_SequenceRule:314
/// <summary>
/// Index = 1
/// </summary>
public AstAmmyValue PropertyValue
{
get { return (AstAmmyValue)ChildNodes[1]; }
}
}
/// <summary>
/// sequence of __domain_style_name [AstDomainStyleName, AmmyDomainStyleName]
/// </summary>
public partial class AstUsingStatement : BaseAstNode
{
public AmmyDomainStyleName GetNamespaceNameValue(ScriptThread thread)
{
// generator : AstClassesGenerator.Process_SequenceRule:335
var tmp = NamespaceName.Evaluate(thread);
var result = (AmmyDomainStyleName)tmp;
return result;
}
public override void Init(AstContext context, ParseTreeNode treeNode)
{
base.Init(context, treeNode);
AsString = "Sequence using_statement";
}
protected override object DoEvaluate(ScriptThread thread)
{
// generator : ForSequenceRule.Create:44
var namespaceName = GetNamespaceNameValue(thread);
var doEvaluateResult = new AmmyUsingStatement(Span, namespaceName);
return doEvaluateResult;
}
// created AstClassesGenerator.Add_GetMap:96
protected override int[] GetMap()
{
return new [] { 1 };
}
// created AstClassesGenerator.Process_SequenceRule:314
/// <summary>
/// Index = 1
/// </summary>
public AstDomainStyleName NamespaceName
{
get { return (AstDomainStyleName)ChildNodes[1]; }
}
}
/// <summary>
/// zero or more __using_statement
/// </summary>
public partial class AstUsingStatementCollection : BaseAstNode
{
public IReadOnlyList<AmmyUsingStatement> EvaluateItems(ScriptThread thread)
{
var cnt = ChildNodes.Count;
var result = new AmmyUsingStatement[cnt];
for (var i = cnt - 1; i >= 0; i--)
{
var childNode = ChildNodes[i];
result[i] = (AmmyUsingStatement)childNode.Evaluate(thread);
}
return result;
}
public IEnumerable<AstUsingStatement> GetItems()
{
var cnt = ChildNodes.Count;
for (var i = 0; i < cnt; i++)
{
var el = ChildNodes[i];
yield return (AstUsingStatement)el;
}
}
public override void Init(AstContext context, ParseTreeNode treeNode)
{
base.Init(context, treeNode);
AsString = "Collection of using_statement";
}
protected override object DoEvaluate(ScriptThread thread)
{
// generator : ForPlusOrStar.Create:44
var items = EvaluateItems(thread);
var doEvaluateResult = new AmmyUsingStatementCollection(Span, items);
return doEvaluateResult;
}
}
/// <summary>
/// one of: stringLiteral, numberLiteral, boolean_value
/// </summary>
public partial interface IAstAmmyValue
{
}
/// <summary>
/// one of: NewLinePlus, Eof
/// </summary>
public partial interface IAstEndOfUsingStatement
{
}
/// <summary>
/// one of: property_set_statement, ammy_value
/// </summary>
public partial interface IAstObjectBodyElement
{
}
/// <summary>
/// optional Name = object_name_key_prefix
/// </summary>
public partial interface IAstObjectNameKeyPrefixOptional
{
}
/// <summary>
/// optional Name = object_name
/// </summary>
public partial interface IAstObjectNameOptional
{
}
public enum AstBooleanValueNodeKinds
{
Unknown,
True,
False
}
public enum AstAmmyValueNodeKinds
{
Unknown,
StringLiteral,
NumberLiteral,
BooleanValue
}
public enum AstObjectBodyElementNodeKinds
{
Unknown,
PropertySetStatement,
AmmyValue
}
}
namespace Samples.Irony.AmmyGrammar.Data
{
/// <summary>
/// rule = alternative: __true, __false
/// </summary>
public partial class AmmyBooleanValue : AmmyStatement
{
public AmmyBooleanValue(SourceSpan span, object tmpValue, Samples.Irony.AmmyGrammar.Ast.AstBooleanValueNodeKinds nodeKind)
: base(span)
{
// generator : ConstructorBuilder.CreateConstructor:37
TmpValue = tmpValue;
NodeKind = nodeKind;
}
public override string ToString()
{
return TmpValue?.ToString() ?? string.Empty;
}
public object TmpValue { get; set; }
public Samples.Irony.AmmyGrammar.Ast.AstBooleanValueNodeKinds NodeKind { get; }
}
/// <summary>
/// zero or more __identifierIdentifierTerminal, string
/// </summary>
public partial class AmmyDomainStyleName : AmmyStatement
{
public AmmyDomainStyleName(SourceSpan span, IReadOnlyList<string> items)
: base(span)
{
// generator : ConstructorBuilder.CreateConstructor:37
Items = items;
}
public override string ToString()
{
return string.Join(".", Items);
}
public IReadOnlyList<string> Items { get; }
}
/// <summary>
/// sequence of __domain_style_name [Samples.Irony.AmmyGrammar.Ast.AstDomainStyleName, AmmyDomainStyleName], __stringLiteral [StringLiteral, string], __object_body_in_curly_brackets [Samples.Irony.AmmyGrammar.Ast.AstObjectBodyInCurlyBrackets, AmmyObjectBodyInCurlyBrackets]
/// </summary>
public partial class AmmyMainObjectStatement : AmmyStatement
{
public AmmyMainObjectStatement(SourceSpan span, AmmyDomainStyleName baseObjectType, string fullTypeName, AmmyObjectBodyInCurlyBrackets body)
: base(span)
{
// generator : ConstructorBuilder.CreateConstructor:37
BaseObjectType = baseObjectType;
FullTypeName = fullTypeName;
Body = body;
}
public AmmyDomainStyleName BaseObjectType { get; }
public string FullTypeName { get; }
public AmmyObjectBodyInCurlyBrackets Body { get; }
}
/// <summary>
/// zero or more __object_body_one_line
/// </summary>
public partial class AmmyObjectBody : AmmyStatement
{
public AmmyObjectBody(SourceSpan span, IReadOnlyList<AmmyObjectBodyOneLine> items)
: base(span)
{
// generator : ConstructorBuilder.CreateConstructor:37
Items = items;
}
public override string ToString()
{
return string.Join(".", Items);
}
public IReadOnlyList<AmmyObjectBodyOneLine> Items { get; }
}
/// <summary>
/// rule = alternative: __property_set_statement, __ammy_value
/// </summary>
public partial class AmmyObjectBodyElement : AmmyStatement
{
public AmmyObjectBodyElement(SourceSpan span, object tmpValue, Samples.Irony.AmmyGrammar.Ast.AstObjectBodyElementNodeKinds nodeKind)
: base(span)
{
// generator : ConstructorBuilder.CreateConstructor:37
TmpValue = tmpValue;
NodeKind = nodeKind;
}
public override string ToString()
{
return TmpValue?.ToString() ?? string.Empty;
}
public object TmpValue { get; set; }
public Samples.Irony.AmmyGrammar.Ast.AstObjectBodyElementNodeKinds NodeKind { get; }
}
/// <summary>
/// sequence of __object_body [Samples.Irony.AmmyGrammar.Ast.AstObjectBody, AmmyObjectBody]
/// </summary>
public partial class AmmyObjectBodyInCurlyBrackets : AmmyStatement
{
public AmmyObjectBodyInCurlyBrackets(SourceSpan span, AmmyObjectBody body)
: base(span)
{
// generator : ConstructorBuilder.CreateConstructor:37
Body = body;
}
public AmmyObjectBody Body { get; }
}
/// <summary>
/// one or more __object_body_element
/// </summary>
public partial class AmmyObjectBodyOneLine : AmmyStatement
{
public AmmyObjectBodyOneLine(SourceSpan span, IReadOnlyList<AmmyObjectBodyElement> items)
: base(span)
{
// generator : ConstructorBuilder.CreateConstructor:37
Items = items;
}
public override string ToString()
{
return string.Join(".", Items);
}
public IReadOnlyList<AmmyObjectBodyElement> Items { get; }
}
/// <summary>
/// sequence of
/// </summary>
public partial class AmmyObjectName : AmmyStatement
{
public AmmyObjectName(SourceSpan span)
: base(span)
{
// generator : ConstructorBuilder.CreateConstructor:37
}
}
/// <summary>
/// sequence of
/// </summary>
public partial class AmmyObjectNameKeyPrefix : AmmyStatement
{
public AmmyObjectNameKeyPrefix(SourceSpan span)
: base(span)
{
// generator : ConstructorBuilder.CreateConstructor:37
}
}
/// <summary>
/// rule = alternative: Empty, __object_name_key_prefix
/// </summary>
public partial class AmmyObjectNameKeyPrefixOptional : AmmyStatement
{
public AmmyObjectNameKeyPrefixOptional(SourceSpan span, object tmpValue)
: base(span)
{
// generator : ConstructorBuilder.CreateConstructor:37
TmpValue = tmpValue;
}
public override string ToString()
{
return TmpValue?.ToString() ?? string.Empty;
}
public object TmpValue { get; set; }
}
/// <summary>
/// rule = alternative: Empty, __object_name
/// </summary>
public partial class AmmyObjectNameOptional : AmmyStatement
{
public AmmyObjectNameOptional(SourceSpan span, object tmpValue)
: base(span)
{
// generator : ConstructorBuilder.CreateConstructor:37
TmpValue = tmpValue;
}
public override string ToString()
{
return TmpValue?.ToString() ?? string.Empty;
}
public object TmpValue { get; set; }
}
/// <summary>
/// sequence of __domain_style_name [Samples.Irony.AmmyGrammar.Ast.AstDomainStyleName, AmmyDomainStyleName], __object_name_optional [Samples.Irony.AmmyGrammar.Ast.AstObjectNameOptional, AmmyObjectNameOptional]
/// </summary>
public partial class AmmyObjectStatement : AmmyStatement
{
public AmmyObjectStatement(SourceSpan span, AmmyDomainStyleName objectType, AmmyObjectNameOptional objectName)
: base(span)
{
// generator : ConstructorBuilder.CreateConstructor:37
ObjectType = objectType;
ObjectName = objectName;
}
public AmmyDomainStyleName ObjectType { get; }
public AmmyObjectNameOptional ObjectName { get; }
}
/// <summary>
/// sequence of __using_statement_collection [Samples.Irony.AmmyGrammar.Ast.AstUsingStatementCollection, AmmyUsingStatementCollection], __main_object_statement [Samples.Irony.AmmyGrammar.Ast.AstMainObjectStatement, AmmyMainObjectStatement]
/// </summary>
public partial class AmmyProgram : AmmyStatement
{
public AmmyProgram(SourceSpan span, AmmyUsingStatementCollection usings, AmmyMainObjectStatement objectDefinition)
: base(span)
{
// generator : ConstructorBuilder.CreateConstructor:37
Usings = usings;
ObjectDefinition = objectDefinition;
}
public AmmyUsingStatementCollection Usings { get; }
public AmmyMainObjectStatement ObjectDefinition { get; }
}
/// <summary>
/// sequence of __identifier [IdentifierTerminal, string], __ammy_value [Samples.Irony.AmmyGrammar.Ast.AstAmmyValue, AmmyValue]
/// </summary>
public partial class AmmyPropertySetStatement : AmmyStatement
{
public AmmyPropertySetStatement(SourceSpan span, string propertyName, AmmyValue propertyValue)
: base(span)
{
// generator : ConstructorBuilder.CreateConstructor:37
PropertyName = propertyName;
PropertyValue = propertyValue;
}
public string PropertyName { get; }
public AmmyValue PropertyValue { get; }
}
/// <summary>
/// sequence of __domain_style_name [Samples.Irony.AmmyGrammar.Ast.AstDomainStyleName, AmmyDomainStyleName]
/// </summary>
public partial class AmmyUsingStatement : AmmyStatement
{
public AmmyUsingStatement(SourceSpan span, AmmyDomainStyleName namespaceName)
: base(span)
{
// generator : ConstructorBuilder.CreateConstructor:37
NamespaceName = namespaceName;
}
public AmmyDomainStyleName NamespaceName { get; }
}
/// <summary>
/// zero or more __using_statement
/// </summary>
public partial class AmmyUsingStatementCollection : AmmyStatement
{
public AmmyUsingStatementCollection(SourceSpan span, IReadOnlyList<AmmyUsingStatement> items)
: base(span)
{
// generator : ConstructorBuilder.CreateConstructor:37
Items = items;
}
public override string ToString()
{
return string.Join(".", Items);
}
public IReadOnlyList<AmmyUsingStatement> Items { get; }
}
/// <summary>
/// rule = alternative: __stringLiteral, __numberLiteral, __boolean_value
/// </summary>
public partial class AmmyValue : AmmyStatement
{
public AmmyValue(SourceSpan span, object tmpValue, Samples.Irony.AmmyGrammar.Ast.AstAmmyValueNodeKinds nodeKind)
: base(span)
{
// generator : ConstructorBuilder.CreateConstructor:37
TmpValue = tmpValue;
NodeKind = nodeKind;
}
public override string ToString()
{
return TmpValue?.ToString() ?? string.Empty;
}
public object TmpValue { get; set; }
public Samples.Irony.AmmyGrammar.Ast.AstAmmyValueNodeKinds NodeKind { get; }
}
}
| |
using System.Collections.Generic;
using System.Linq;
using NetGore;
using NetGore.Graphics.GUI;
using SFML.Graphics;
using SFML.Window;
namespace DemoGame.Client
{
/// <summary>
/// A <see cref="Form"/> that displays the chat messages and allows the user to enter chat text.
/// </summary>
class ChatForm : Form
{
readonly TextBox _input;
readonly TextBox _output;
int _bufferOffset = 0;
/// <summary>
/// Initializes a new instance of the <see cref="ChatForm"/> class.
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="pos">The pos.</param>
public ChatForm(Control parent, Vector2 pos) : base(parent, pos, new Vector2(300, 150))
{
// Create the input and output TextBoxes
_input = new TextBox(this, Vector2.Zero, new Vector2(32, 32))
{
IsMultiLine = false,
IsEnabled = true,
Font = GameScreenHelper.DefaultChatFont,
MaxInputTextLength = GameData.MaxClientSayLength,
BorderColor = new Color(255, 255, 255, 100)
};
_output = new TextBox(this, Vector2.Zero, new Vector2(32, 32))
{
IsMultiLine = true,
IsEnabled = false,
Font = GameScreenHelper.DefaultChatFont,
BorderColor = new Color(255, 255, 255, 100)
};
_input.KeyPressed -= Input_KeyPressed;
_input.KeyPressed += Input_KeyPressed;
// Force the initial repositioning
RepositionTextBoxes();
}
/// <summary>
/// Notifies listeners that a message is trying to be sent from the ChatForm's input box.
/// </summary>
public event TypedEventHandler<ChatForm, EventArgs<string>> Say;
/// <summary>
/// Appends a set of styled text to the output TextBox.
/// </summary>
/// <param name="text">Text to append to the output TextBox.</param>
public void AppendToOutput(string text)
{
_output.AppendLine(text);
}
/// <summary>
/// Appends a string of text to the output TextBox.
/// </summary>
/// <param name="text">Text to append to the output TextBox.</param>
/// <param name="color">Color of the text to append.</param>
public void AppendToOutput(string text, Color color)
{
_output.AppendLine(new StyledText(text, color));
}
/// <summary>
/// Appends a set of styled text to the output TextBox.
/// </summary>
/// <param name="text">Text to append to the output TextBox.</param>
public void AppendToOutput(IEnumerable<StyledText> text)
{
_output.AppendLine(text);
}
/// <summary>
/// Clears the input text.
/// </summary>
public void ClearInput()
{
_input.Clear();
}
/// <summary>
/// Clears the output text.
/// </summary>
public void ClearOutput()
{
_output.Clear();
}
void Input_KeyPressed(object sender, KeyEventArgs e)
{
const int bufferScrollRate = 3;
switch (e.Code)
{
case Keyboard.Key.Return:
if (Say != null)
{
var text = _input.Text;
if (!string.IsNullOrEmpty(text))
{
_input.Text = string.Empty;
Say.Raise(this, EventArgsHelper.Create(text));
}
}
break;
case Keyboard.Key.PageUp:
_bufferOffset += bufferScrollRate;
break;
case Keyboard.Key.PageDown:
_bufferOffset -= bufferScrollRate;
break;
}
}
/// <summary>
/// Handles when the <see cref="Control.Border"/> has changed.
/// This is called immediately before <see cref="Control.BorderChanged"/>.
/// Override this method instead of using an event hook on <see cref="Control.BorderChanged"/> when possible.
/// </summary>
protected override void OnBorderChanged()
{
base.OnBorderChanged();
RepositionTextBoxes();
}
/// <summary>
/// Handles when the <see cref="TextControl.Font"/> has changed.
/// This is called immediately before <see cref="TextControl.FontChanged"/>.
/// Override this method instead of using an event hook on <see cref="TextControl.FontChanged"/> when possible.
/// </summary>
protected override void OnFontChanged()
{
base.OnFontChanged();
if (_input == null || _output == null)
return;
_input.Font = Font;
_output.Font = Font;
RepositionTextBoxes();
}
/// <summary>
/// Handles when the <see cref="Control.Size"/> of this <see cref="Control"/> has changed.
/// This is called immediately before <see cref="Control.Resized"/>.
/// Override this method instead of using an event hook on <see cref="Control.Resized"/> when possible.
/// </summary>
protected override void OnResized()
{
base.OnResized();
RepositionTextBoxes();
}
/// <summary>
/// Repositions the input and output TextBoxes on the form.
/// </summary>
void RepositionTextBoxes()
{
if (_input == null || _output == null)
return;
var inputSize = new Vector2(ClientSize.X, Font.GetLineSpacing() + _input.Border.Height);
var outputSize = new Vector2(ClientSize.X, ClientSize.Y - inputSize.Y);
var inputPos = new Vector2(0, outputSize.Y);
var outputPos = Vector2.Zero;
_input.Size = inputSize;
_input.Position = inputPos;
_output.Size = outputSize;
_output.Position = outputPos;
}
/// <summary>
/// Sets the default values for the <see cref="Control"/>. This should always begin with a call to the
/// base class's method to ensure that changes to settings are hierchical.
/// </summary>
protected override void SetDefaultValues()
{
base.SetDefaultValues();
Text = "Chat";
IsCloseButtonVisible = false;
}
void UpdateBufferOffset()
{
if (_bufferOffset > _output.LineCount - _output.MaxVisibleLines)
_bufferOffset = _output.LineCount - _output.MaxVisibleLines;
if (_bufferOffset < 0)
_bufferOffset = 0;
var pos = _output.LineCount - _bufferOffset - _output.MaxVisibleLines - 1;
if (pos < 0)
pos = 0;
else if (pos >= _output.LineCount)
pos = _output.LineCount - 1;
_output.LineBufferOffset = pos;
}
/// <summary>
/// Updates the <see cref="Control"/>. This is called for every <see cref="Control"/>, even if it is disabled or
/// not visible.
/// </summary>
/// <param name="currentTime">The current time in milliseconds.</param>
protected override void UpdateControl(TickCount currentTime)
{
UpdateBufferOffset();
base.UpdateControl(currentTime);
}
/// <summary>
/// Gets if the input text box has focus.
/// </summary>
public bool HasInputFocus()
{
return _input.HasFocus;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Newtonsoft.Json.Linq;
using ReactNative.Bridge;
using ReactNative.Modules.Core;
using ReactNative.Tracing;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.UI.Core;
namespace ReactNative.UIManager
{
/// <summary>
/// This class acts as a buffer for command executed on
/// <see cref="NativeViewHierarchyManager"/>. It exposes similar methods as
/// mentioned classes but instead of executing commands immediately, it
/// enqueues those operations in a queue that is then flushed from
/// <see cref="UIManagerModule"/> once a JavaScript batch of UI operations
/// is finished.
/// There is one queue instance created for each top level window since
/// each of these windows run on a different thread.
/// </summary>
public class UIViewOperationQueue
{
private readonly ReactContext _reactContext;
private readonly ViewManagerRegistry _viewManagerRegistry;
private class QueueInstanceInfo
{
public UIViewOperationQueueInstance queueInstance;
public int rootViewCount;
}
// Thread safe dictionary using a single lock
private class SimpleLockedDictionary<TKey, TValue>
{
private readonly object _lock = new object();
private readonly Dictionary<TKey, TValue> _dict = new Dictionary<TKey, TValue>();
public void Add(TKey key, TValue value)
{
lock(_lock)
{
_dict.Add(key, value);
}
}
public bool TryGetValue(TKey key, out TValue value)
{
lock (_lock)
{
return _dict.TryGetValue(key, out value);
}
}
public void RemoveList(IList<TKey> keyList)
{
lock (_lock)
{
foreach (var key in keyList)
{
_dict.Remove(key);
}
}
}
}
// Maps tags to corresponding UIViewOperationQueueInstance.
// Uses a simple serialized Dictionary that depends on a single lock (rather than one per bucket), allows fast removal of list of keys, etc.
private readonly SimpleLockedDictionary<int, UIViewOperationQueueInstance> _reactTagToOperationQueue = new SimpleLockedDictionary<int, UIViewOperationQueueInstance>();
// The _dispatcherToOperationQueueInfo (all entries but the main window related one) & _active combo are protected by this lock
// This allows for consistent lifecycle OnSuspend/OnResume events to be sent to each queue instance
private readonly object _lock = new object();
private bool _active;
// Maps CoreDispatcher to corresponding UIViewOperationQueueInstance + rootView accounting
// The concurrent dictionary allows for thread safe ".Values" calls, crash-safe enumerating, etc.
private readonly ConcurrentDictionary<CoreDispatcher, QueueInstanceInfo> _dispatcherToOperationQueueInfo = new ConcurrentDictionary<CoreDispatcher, QueueInstanceInfo>();
/// <summary>
/// Instantiates the <see cref="UIViewOperationQueue"/>.
/// </summary>
/// <param name="reactContext">The React context.</param>
/// <param name="viewManagerRegistry">
/// The view manager registry.
/// </param>
public UIViewOperationQueue(ReactContext reactContext, ViewManagerRegistry viewManagerRegistry)
{
_reactContext = reactContext;
_viewManagerRegistry = viewManagerRegistry;
_active = false;
// Corner case: UWP scenarios that start with no main window.
// We create the UIViewOperationQueueInstance for main dispatcher thread ahead of time so animations
// in secondary windows can work.
var queueInfo = new QueueInstanceInfo()
{
queueInstance = new UIViewOperationQueueInstance(
_reactContext,
new NativeViewHierarchyManager(_viewManagerRegistry, DispatcherHelpers.MainDispatcher, OnViewsDropped),
ReactChoreographer.Instance)
};
_dispatcherToOperationQueueInfo.AddOrUpdate(DispatcherHelpers.MainDispatcher, queueInfo, (k, v) => throw new InvalidOperationException("Duplicate key"));
MainUIViewOperationQueue = queueInfo.queueInstance;
}
/// <summary>
/// The native view hierarchy manager.
/// </summary>
internal UIViewOperationQueueInstance MainUIViewOperationQueue { get; }
/// <summary>
/// Checks if the operation queue is empty.
/// </summary>
/// <returns>
/// <b>true</b> if the queue is empty, <b>false</b> otherwise.
/// </returns>
public bool IsEmpty()
{
return _dispatcherToOperationQueueInfo.Values.All(qi => qi.queueInstance.IsEmpty());
}
/// <summary>
/// Adds a root view to the hierarchy.
/// </summary>
/// <param name="tag">The root view tag.</param>
/// <param name="rootView">The root view.</param>
/// <param name="themedRootContext">The React context.</param>
public void AddRootView(
int tag,
SizeMonitoringCanvas rootView,
ThemedReactContext themedRootContext)
{
// This is called on layout manager thread
// Extract dispatcher
var rootViewDispatcher = rootView.Dispatcher;
// _dispatcherToOperationQueueInfo contains a mapping of CoreDispatcher to <UIViewOperationQueueInstance, # of ReactRootView instances>.
// Operation queue instances are created lazily whenever an "unknown" CoreDispatcher is detected. Each operation queue instance
// works together with one dedicated NativeViewHierarchyManager and one ReactChoreographer.
// One operation queue is the "main" one:
// - is coupled with the CoreApplication.MainView dispatcher
// - drives animations in ALL views
if (!_dispatcherToOperationQueueInfo.TryGetValue(rootViewDispatcher, out var queueInfo))
{
// Queue instance doesn't exist for this dispatcher, we need to create
// Find the CoreApplicationView associated to the new CoreDispatcher
CoreApplicationView foundView = CoreApplication.Views.First(v => v.Dispatcher == rootViewDispatcher);
// Create new ReactChoreographer for this view/dispatcher. It will only be used for its DispatchUICallback services
var reactChoreographer = ReactChoreographer.CreateSecondaryInstance(foundView);
queueInfo = new QueueInstanceInfo()
{
queueInstance = new UIViewOperationQueueInstance(
_reactContext,
new NativeViewHierarchyManager(_viewManagerRegistry, rootViewDispatcher, OnViewsDropped),
reactChoreographer),
rootViewCount = 1
};
lock (_lock)
{
// Add new tuple to map
_dispatcherToOperationQueueInfo.AddOrUpdate(rootViewDispatcher, queueInfo, (k, v) => throw new InvalidOperationException("Duplicate key"));
if (_active)
{
// Simulate an OnResume from the correct dispatcher thread
// (OnResume/OnSuspend/OnDestroy have this thread affinity, all other methods do enqueuings in a thread safe manner)
// (No inlining here so we don't hold lock during call outs. Not a big deal since inlining
// is only useful for main UI thread, and this code is not executed for that one)
DispatcherHelpers.RunOnDispatcher(rootViewDispatcher, queueInfo.queueInstance.OnResume);
}
}
}
else
{
// Queue instance does exist.
// Increment the count of root views. This is helpful for the case the count reaches 0 so we can cleanup the queue.
queueInfo.rootViewCount++;
}
// Add tag
_reactTagToOperationQueue.Add(tag, queueInfo.queueInstance);
// Send forward
queueInfo.queueInstance.AddRootView(tag, rootView, themedRootContext);
}
/// <summary>
/// Enqueues an operation to remove the root view.
/// </summary>
/// <param name="rootViewTag">The root view tag.</param>
public Task RemoveRootViewAsync(int rootViewTag)
{
// Called on layout manager thread
UIViewOperationQueueInstance queue = GetQueueByTag(rootViewTag);
// Send forward
queue.EnqueueRemoveRootView(rootViewTag);
// Do some maintenance/cleanup if needed.
// Find the queue info
var pair = _dispatcherToOperationQueueInfo.First(p => p.Value.queueInstance == queue);
// Decrement number of root views
pair.Value.rootViewCount--;
if (queue != MainUIViewOperationQueue)
{
if (pair.Value.rootViewCount == 0)
{
// We can remove this queue and then destroy
_dispatcherToOperationQueueInfo.TryRemove(pair.Key, out _);
// Simulate an OnDestroy from the correct dispatcher thread
// (OnResume/OnSuspend/OnDestroy have this thread affinity, all other methods do enqueuings in a thread safe manner)
return DispatcherHelpers.CallOnDispatcher(pair.Key, () =>
{
queue.OnDestroy();
return true;
});
}
else
{
return Task.CompletedTask;
}
}
else
{
return Task.CompletedTask;
}
}
/// <summary>
/// Refreshes RTL/LTR direction on all root views.
/// </summary>
public void UpdateRootViewNodesDirection()
{
// Called on layout manager thread
// Dispatch to all queues
foreach (var queue in _dispatcherToOperationQueueInfo.Values)
{
queue.queueInstance.UpdateRootViewNodesDirection();
}
}
/// <summary>
/// Enqueues an operation to dispatch a command.
/// </summary>
/// <param name="tag">The view tag.</param>
/// <param name="commandId">The command identifier.</param>
/// <param name="commandArgs">The command arguments.</param>
public void EnqueueDispatchCommand(int tag, int commandId, JArray commandArgs)
{
// Called on layout manager thread
GetQueueByTag(tag).EnqueueDispatchCommand(tag, commandId, commandArgs);
}
/// <summary>
/// Enqueues an operation to update the extra data for a view.
/// </summary>
/// <param name="tag">The view tag.</param>
/// <param name="extraData">The extra data.</param>
public void EnqueueUpdateExtraData(int tag, object extraData)
{
// Called on layout manager thread
GetQueueByTag(tag).EnqueueUpdateExtraData(tag, extraData);
}
/// <summary>
/// Enqueues an operation to show a popup menu.
/// </summary>
/// <param name="tag">The view tag.</param>
/// <param name="items">The menu items.</param>
/// <param name="error">Called on error.</param>
/// <param name="success">Called on success.</param>
public void EnqueueShowPopupMenu(int tag, string[] items, ICallback error, ICallback success)
{
// Called on layout manager thread
GetQueueByTag(tag).EnqueueShowPopupMenu(tag, items, error, success);
}
/// <summary>
/// Enqueues a operation to execute a UIBlock.
/// </summary>
/// <param name="block">The UI block.</param>
/// <param name="tag">Optional react tag hint that triggers the choice of the dispatcher thread that executes the block .</param>
public void EnqueueUIBlock(IUIBlock block, int? tag)
{
// Called on layout manager thread
(tag.HasValue ? GetQueueByTag(tag.Value) : MainUIViewOperationQueue).EnqueueUIBlock(block);
}
/// <summary>
/// Enqueues a operation to execute a UIBlock.
/// </summary>
/// <param name="block">The UI block.</param>
/// <param name="tag">Optional react tag hint that triggers the choice of the dispatcher thread that executes the block .</param>
public void PrependUIBlock(IUIBlock block, int? tag)
{
// Called on layout manager thread
(tag.HasValue ? GetQueueByTag(tag.Value) : MainUIViewOperationQueue).PrependUIBlock(block);
}
/// <summary>
/// Enqueues an operation to create a view.
/// </summary>
/// <param name="themedContext">The React context.</param>
/// <param name="viewReactTag">The view React tag.</param>
/// <param name="viewClassName">The view class name.</param>
/// <param name="initialProps">The initial props.</param>
/// <param name="rootViewTag">Root view tag.</param>
public void EnqueueCreateView(
ThemedReactContext themedContext,
int viewReactTag,
string viewClassName,
JObject initialProps,
int rootViewTag)
{
// Called on layout manager thread
UIViewOperationQueueInstance queue = GetQueueByTag(rootViewTag);
_reactTagToOperationQueue.Add(viewReactTag, queue);
queue.EnqueueCreateView(themedContext, viewReactTag, viewClassName, initialProps);
}
/// <summary>
/// Enqueue a configure layout animation operation.
/// </summary>
/// <param name="config">The configuration.</param>
/// <param name="success">The success callback.</param>
/// <param name="error">The error callback.</param>
public void EnqueueConfigureLayoutAnimation(JObject config, ICallback success, ICallback error)
{
// Called on layout manager thread
// We have to dispatch this to all queues. Each queue will reset the "animating layout" at the end of the current batch.
foreach (var queue in _dispatcherToOperationQueueInfo.Values)
{
queue.queueInstance.EnqueueConfigureLayoutAnimation(config, success, error);
}
}
/// <summary>
/// Enqueues an operation to update the props of a view.
/// </summary>
/// <param name="tag">The view tag.</param>
/// <param name="className">The class name.</param>
/// <param name="props">The props.</param>
public void EnqueueUpdateProps(int tag, string className, JObject props)
{
// Called on layout manager thread
GetQueueByTag(tag).EnqueueUpdateProps(tag, className, props);
}
/// <summary>
/// Enqueues an operation to update the layout of a view.
/// </summary>
/// <param name="parentTag">The parent tag.</param>
/// <param name="tag">The view tag.</param>
/// <param name="dimensions">The dimensions.</param>
public void EnqueueUpdateLayout(
int parentTag,
int tag,
Dimensions dimensions)
{
// Called on layout manager thread
GetQueueByTag(tag).EnqueueUpdateLayout(parentTag, tag, dimensions);
}
/// <summary>
/// Enqueues an operation to manage the children of a view.
/// </summary>
/// <param name="tag">The view to manage.</param>
/// <param name="indexesToRemove">The indices to remove.</param>
/// <param name="viewsToAdd">The views to add.</param>
/// <param name="tagsToDelete">The tags to delete.</param>
public void EnqueueManageChildren(
int tag,
int[] indexesToRemove,
ViewAtIndex[] viewsToAdd,
int[] tagsToDelete)
{
// Called on layout manager thread
GetQueueByTag(tag).EnqueueManageChildren(tag, indexesToRemove, viewsToAdd, tagsToDelete);
}
/// <summary>
/// Enqueues an operation to set the children of a view.
/// </summary>
/// <param name="tag">The view to manage.</param>
/// <param name="childrenTags">The children tags.</param>
public void EnqueueSetChildren(int tag, int[] childrenTags)
{
// Called on layout manager thread
GetQueueByTag(tag).EnqueueSetChildren(tag, childrenTags);
}
/// <summary>
/// Enqueues an operation to measure the view.
/// </summary>
/// <param name="tag">The tag of the view to measure.</param>
/// <param name="callback">The measurement result callback.</param>
public void EnqueueMeasure(int tag, ICallback callback)
{
// Called on layout manager thread
UIViewOperationQueueInstance queue = GetQueueByTag(tag, true);
if (queue == null)
{
// This is called bypassing the optimizer, so we need to fake a result for layout only nodes.
callback.Invoke();
return;
}
queue.EnqueueMeasure(tag, callback);
}
/// <summary>
/// Enqueues an operation to measure the view relative to the window.
/// </summary>
/// <param name="tag">The tag of the view to measure.</param>
/// <param name="callback">The measurement result callback.</param>
public void EnqueueMeasureInWindow(int tag, ICallback callback)
{
// Called on layout manager thread
UIViewOperationQueueInstance queue = GetQueueByTag(tag, true);
if (queue == null)
{
// This is called bypassing the optimizer, so we need to fake a result for layout only nodes.
callback.Invoke();
return;
}
queue.EnqueueMeasureInWindow(tag, callback);
}
/// <summary>
/// Enqueues an operation to find a touch target.
/// </summary>
/// <param name="tag">The parent view to search from.</param>
/// <param name="targetX">The x-coordinate of the touch event.</param>
/// <param name="targetY">The y-coordinate of the touch event.</param>
/// <param name="callback">The callback.</param>
public void EnqueueFindTargetForTouch(
int tag,
double targetX,
double targetY,
ICallback callback)
{
// Called on layout manager thread
UIViewOperationQueueInstance queue = GetQueueByTag(tag, true);
if (queue == null)
{
// This is called bypassing the optimizer, so we need to fake a result for layout only nodes.
callback.Invoke();
return;
}
queue.EnqueueFindTargetForTouch(tag, targetX, targetY, callback);
}
/// <summary>
/// Called when the host receives the suspend event.
/// </summary>
public void OnSuspend()
{
MainUIViewOperationQueue.OnSuspend();
lock (_lock)
{
_active = false;
foreach (var pair in _dispatcherToOperationQueueInfo)
{
if (pair.Key != MainUIViewOperationQueue.Dispatcher)
{
// Simulate an OnSuspend from the correct dispatcher thread
// (OnResume/OnSuspend/OnDestroy have this thread affinity, all other methods do enqueuings in a thread safe manner)
DispatcherHelpers.RunOnDispatcher(pair.Key, pair.Value.queueInstance.OnSuspend);
}
}
}
}
/// <summary>
/// Called when the host receives the resume event.
/// </summary>
public void OnResume()
{
MainUIViewOperationQueue.OnResume();
lock (_lock)
{
_active = true;
foreach (var pair in _dispatcherToOperationQueueInfo)
{
if (pair.Key != MainUIViewOperationQueue.Dispatcher)
{
// Simulate an OnResume from the correct dispatcher thread
// (OnResume/OnSuspend/OnDestroy have this thread affinity, all other methods do enqueuings in a thread safe manner)
DispatcherHelpers.RunOnDispatcher(pair.Key, pair.Value.queueInstance.OnResume);
}
}
}
}
/// <summary>
/// Called when the host is shutting down.
/// </summary>
public void OnDestroy()
{
MainUIViewOperationQueue.OnDestroy();
lock (_lock)
{
_active = false;
foreach (var pair in _dispatcherToOperationQueueInfo)
{
if (pair.Key != MainUIViewOperationQueue.Dispatcher)
{
// Simulate an OnDestroy from the correct dispatcher thread
// (OnResume/OnSuspend/OnDestroy have this thread affinity, all other methods do enqueuings in a thread safe manner)
DispatcherHelpers.RunOnDispatcher(pair.Key, pair.Value.queueInstance.OnDestroy);
}
}
}
}
/// <summary>
/// Used by the native animated module to bypass the process of
/// updating the values through the shadow view hierarchy. This method
/// will directly update the native views, which means that updates for
/// layout-related props won't be handled properly.
/// </summary>
/// <param name="tag">The view tag.</param>
/// <param name="props">The props.</param>
/// <remarks>
/// Make sure you know what you're doing before calling this method :)
/// </remarks>
public bool SynchronouslyUpdateViewOnDispatcherThread(int tag, JObject props)
{
// The native animations module is a single threaded implementation affinitized to the "main" dispatcher thread.
// As a result all calls of this method are on main dispatcher thread.
// Yet, for secondary views we have to dispatch to correct dispatcher as fast as possible
DispatcherHelpers.AssertOnDispatcher();
UIViewOperationQueueInstance queue = GetQueueByTag(tag, true);
if (queue == null)
{
// Returns false as per the caller's expectation
return false;
}
if (queue == MainUIViewOperationQueue)
{
// Main queue case. Just forward.
if (!MainUIViewOperationQueue.NativeViewHierarchyManager.ViewExists(tag))
{
return false;
}
MainUIViewOperationQueue.NativeViewHierarchyManager.UpdateProps(tag, props);
}
else
{
// Dispatch to the correct thread.
DispatcherHelpers.RunOnDispatcher(queue.Dispatcher, CoreDispatcherPriority.High, () =>
{
if (queue.NativeViewHierarchyManager.ViewExists(tag))
{
queue.NativeViewHierarchyManager.UpdateProps(tag, props);
}
else
{
RnLog.Warn(nameof(UIViewOperationQueue), $"View with tag '{tag}' not found due to race condition");
}
});
}
return true;
}
/// <summary>
/// Dispatches the view updates.
/// </summary>
/// <param name="batchId">The batch identifier.</param>
internal void DispatchViewUpdates(int batchId)
{
// Called on layout manager thread
// Dispatch to all queues
foreach (var queue in _dispatcherToOperationQueueInfo.Values)
{
queue.queueInstance.DispatchViewUpdates(batchId);
}
}
private UIViewOperationQueueInstance GetQueueByTag(int tag, bool dontThrow = false)
{
if (!_reactTagToOperationQueue.TryGetValue(tag, out var queue))
{
if (dontThrow)
{
return null;
}
else
{
throw new InvalidOperationException("No queue for tag " + tag);
}
}
return queue;
}
/// <summary>
/// Hook needed to cleanup the local state (_reactTagToOperationQueue)
/// </summary>
/// <param name="tags">List of deleted tags..</param>
private void OnViewsDropped(List<int> tags)
{
_reactTagToOperationQueue.RemoveList(tags);
}
}
}
| |
// Copyright 2020 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Kms.V1;
using Google.Cloud.Spanner.Admin.Database.V1;
using Google.Cloud.Spanner.Admin.Instance.V1;
using Google.Cloud.Spanner.Common.V1;
using Google.Cloud.Spanner.Data;
using Google.Rpc;
using GoogleCloudSamples;
using Grpc.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using CryptoKeyName = Google.Cloud.Spanner.Admin.Database.V1.CryptoKeyName;
[CollectionDefinition(nameof(SpannerFixture))]
public class SpannerFixture : IAsyncLifetime, ICollectionFixture<SpannerFixture>
{
public string ProjectId { get; } = Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ID");
// Allow environment variables to override the default instance and database names.
public string InstanceId { get; } = Environment.GetEnvironmentVariable("TEST_SPANNER_INSTANCE") ?? "my-instance";
public string DatabaseId { get; } = Environment.GetEnvironmentVariable("TEST_SPANNER_DATABASE") ?? $"my-db-{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}";
public string BackupDatabaseId { get; } = "my-test-database";
public string BackupId { get; } = "my-test-database-backup";
public string ToBeCancelledBackupId { get; } = $"my-backup-{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}";
public string RestoredDatabaseId { get; } = $"my-restore-db-{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}";
public bool RunCmekBackupSampleTests { get; private set; }
public const string SkipCmekBackupSamplesMessage = "Spanner CMEK backup sample tests are disabled by default for performance reasons. Set the environment variable RUN_SPANNER_CMEK_BACKUP_SAMPLES_TESTS=true to enable the test.";
public string EncryptedDatabaseId { get; } = $"my-enc-db-{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}";
public string EncryptedBackupId { get; } = $"my-enc-backup-{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}";
// 'restore' is abbreviated to prevent the name from becoming longer than 30 characters.
public string EncryptedRestoreDatabaseId { get; } = $"my-enc-r-db-{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}";
// These are intentionally kept on the instance to avoid the need to create a new encrypted database and backup for each run.
public string FixedEncryptedDatabaseId { get; } = "fixed-enc-backup-db";
public string FixedEncryptedBackupId { get; } = "fixed-enc-backup";
public string InstanceIdWithProcessingUnits { get; } = $"my-instance-processing-units-{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}";
public string InstanceIdWithMultiRegion { get; } = $"my-instance-multi-region-{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}";
public string InstanceConfigId { get; } = "nam6";
private DatabaseAdminClient DatabaseAdminClient { get; set; }
public RetryRobot Retryable { get; } = new RetryRobot
{
ShouldRetry = ex => ex.IsTransientSpannerFault()
};
// Encryption key identifiers.
private static readonly string _testKeyProjectId = Environment.GetEnvironmentVariable("spanner.test.key.project") ?? Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ID");
private static readonly string _testKeyLocationId = Environment.GetEnvironmentVariable("spanner.test.key.location") ?? "us-central1";
private static readonly string _testKeyRingId = Environment.GetEnvironmentVariable("spanner.test.key.ring") ?? "spanner-test-keyring";
private static readonly string _testKeyId = Environment.GetEnvironmentVariable("spanner.test.key.name") ?? "spanner-test-key";
public CryptoKeyName KmsKeyName { get; } = new CryptoKeyName(_testKeyProjectId, _testKeyLocationId, _testKeyRingId, _testKeyId);
public string ConnectionString { get; private set; }
public async Task InitializeAsync()
{
DatabaseAdminClient = await DatabaseAdminClient.CreateAsync();
bool.TryParse(Environment.GetEnvironmentVariable("RUN_SPANNER_CMEK_BACKUP_SAMPLES_TESTS"), out var runCmekBackupSampleTests);
RunCmekBackupSampleTests = runCmekBackupSampleTests;
ConnectionString = $"Data Source=projects/{ProjectId}/instances/{InstanceId}/databases/{DatabaseId}";
// Don't need to cleanup stale Backups and Databases when instance is new.
var isExistingInstance = await InitializeInstanceAsync();
if (isExistingInstance)
{
await DeleteStaleBackupsAsync();
await DeleteStaleDatabasesAsync();
}
await CreateInstanceWithMultiRegionAsync();
await DeleteStaleInstancesAsync();
await InitializeDatabaseAsync();
await InitializeBackupAsync();
// Create encryption key for creating an encrypted database and optionally backing up and restoring an encrypted database.
await InitializeEncryptionKeys();
if (RunCmekBackupSampleTests)
{
await InitializeEncryptedBackupAsync();
}
}
public Task DisposeAsync()
{
DeleteInstance(InstanceIdWithProcessingUnits);
DeleteInstance(InstanceIdWithMultiRegion);
return Task.CompletedTask;
}
public async Task<T> SafeCreateInstanceAsync<T>(Func<Task<T>> createInstanceAsync)
{
int attempt = 0;
do
{
try
{
attempt++;
return await createInstanceAsync();
}
catch(RpcException ex) when (attempt <= 10)
{
if (StatusCode.Unavailable == ex.StatusCode)
{
await RecommendedDelayAsync(ex);
}
else if (StatusCode.ResourceExhausted == ex.StatusCode && ex.Status.Detail.Contains("requests per minute"))
{
await RecommendedDelayAsync(ex, 60);
}
else
{
throw;
}
}
}
while (true);
}
private static readonly string s_retryInfoMetadataKey = RetryInfo.Descriptor.FullName + "-bin";
public static async Task RecommendedDelayAsync(RpcException exception, int fallbackSeconds = 5)
{
TimeSpan delay = TimeSpan.FromSeconds(fallbackSeconds);
var retryInfoEntry = exception.Trailers.FirstOrDefault(
entry => s_retryInfoMetadataKey.Equals(entry.Key, StringComparison.InvariantCultureIgnoreCase));
if (retryInfoEntry != null)
{
var retryInfo = RetryInfo.Parser.ParseFrom(retryInfoEntry.ValueBytes);
var recommended = retryInfo.RetryDelay.ToTimeSpan();
if (recommended != TimeSpan.Zero)
{
delay = recommended;
}
}
await Task.Delay(delay);
}
private async Task<bool> InitializeInstanceAsync()
{
InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync();
InstanceName instanceName = InstanceName.FromProjectInstance(ProjectId, InstanceId);
try
{
Instance response = await instanceAdminClient.GetInstanceAsync(instanceName);
return true;
}
catch (RpcException ex) when (ex.Status.StatusCode == StatusCode.NotFound)
{
CreateInstanceSample createInstanceSample = new CreateInstanceSample();
await SafeCreateInstanceAsync(() => Task.FromResult(createInstanceSample.CreateInstance(ProjectId, InstanceId)));
return false;
}
}
private async Task CreateInstanceWithMultiRegionAsync()
{
InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync();
var projectName = ProjectName.FromProject(ProjectId);
Instance instance = new Instance
{
DisplayName = "Multi-region samples test",
ConfigAsInstanceConfigName = InstanceConfigName.FromProjectInstanceConfig(ProjectId, InstanceConfigId),
InstanceName = InstanceName.FromProjectInstance(ProjectId, InstanceIdWithMultiRegion),
NodeCount = 1,
};
await SafeCreateInstanceAsync(async () =>
{
var response = await instanceAdminClient.CreateInstanceAsync(projectName, InstanceIdWithMultiRegion, instance);
// Poll until the returned long-running operation is complete
response = await response.PollUntilCompletedAsync();
return response.Result;
});
}
private void DeleteInstance(string instanceId)
{
InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create();
InstanceName instanceName = InstanceName.FromProjectInstance(ProjectId, instanceId);
try
{
instanceAdminClient.DeleteInstance(instanceName);
}
catch (Exception)
{
// Silently ignore errors to prevent tests from failing.
}
}
private async Task DeleteStaleDatabasesAsync()
{
var instanceName = InstanceName.FromProjectInstance(ProjectId, InstanceId);
var databases = DatabaseAdminClient.ListDatabases(instanceName, pageSize: 200).ToList();
if (databases.Count < 50)
{
return;
}
var deleteCount = Math.Max(30, databases.Count - 50);
var databasesToDelete = databases
.OrderBy(db => long.TryParse(
db.DatabaseName.DatabaseId
.Replace("my-db-", "").Replace("my-restore-db-", "")
.Replace("my-enc-db-", "").Replace("my-enc-restore-db-", ""),
out long creationDate) ? creationDate : long.MaxValue)
.Take(deleteCount);
// Delete the databases.
foreach (var database in databasesToDelete)
{
try
{
await DeleteDatabaseAsync(database.DatabaseName.DatabaseId);
}
catch (Exception e)
{
Console.WriteLine($"Failed to delete stale test database {database.DatabaseName.DatabaseId}: {e.Message}");
}
}
}
private async Task DeleteStaleBackupsAsync()
{
var instanceName = InstanceName.FromProjectInstance(ProjectId, InstanceId);
var backups = DatabaseAdminClient.ListBackups(instanceName, pageSize: 200).ToList();
if (backups.Count < 50)
{
return;
}
var deleteCount = Math.Max(30, backups.Count - 50);
var backupsToDelete = backups
.OrderBy(db => long.TryParse(
db.BackupName.BackupId.Replace("my-enc-backup-", ""),
out long creationDate) ? creationDate : long.MaxValue)
.Take(deleteCount);
// Delete the backups.
foreach (var backup in backupsToDelete)
{
try
{
await DatabaseAdminClient.DeleteBackupAsync(backup.BackupName);
}
catch (Exception) { }
}
}
/// <summary>
/// Deletes 10 oldest instances if the number of instances is more than 14.
/// This is to clean up the stale instances in case of instance cleanup code may not get triggered.
/// </summary>
private async Task DeleteStaleInstancesAsync()
{
InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create();
var listInstancesRequest = new ListInstancesRequest
{
Filter = "name:my-instance-processing-units- OR name:my-instance-multi-region-",
ParentAsProjectName = ProjectName.FromProject(ProjectId)
};
var instances = instanceAdminClient.ListInstances(listInstancesRequest);
if (instances.Count() < 15)
{
return;
}
long fiveHoursAgo = DateTimeOffset.UtcNow.AddHours(-5).ToUnixTimeMilliseconds();
var instancesToDelete = instances
.Select(db => (db, CreationUnixTimeMilliseconds(db)))
.Where(pair => pair.Item2 < fiveHoursAgo)
.Select(pair => pair.db);
// Delete the instances.
foreach (var instance in instancesToDelete)
{
try
{
await instanceAdminClient.DeleteInstanceAsync(instance.InstanceName);
}
catch (Exception) { }
}
static long CreationUnixTimeMilliseconds(Instance db) =>
long.TryParse(
db.InstanceName.InstanceId
.Replace("my-instance-processing-units-", "")
.Replace("my-instance-multi-region-", ""),
out long creationDate) ? creationDate : long.MaxValue;
}
private async Task InitializeDatabaseAsync()
{
// If the database has not been initialized, retry.
CreateDatabaseAsyncSample createDatabaseAsyncSample = new CreateDatabaseAsyncSample();
InsertDataAsyncSample insertDataAsyncSample = new InsertDataAsyncSample();
InsertStructSampleDataAsyncSample insertStructSampleDataAsyncSample = new InsertStructSampleDataAsyncSample();
AddColumnAsyncSample addColumnAsyncSample = new AddColumnAsyncSample();
AddCommitTimestampAsyncSample addCommitTimestampAsyncSample = new AddCommitTimestampAsyncSample();
AddIndexAsyncSample addIndexAsyncSample = new AddIndexAsyncSample();
AddStoringIndexAsyncSample addStoringIndexAsyncSample = new AddStoringIndexAsyncSample();
CreateTableWithDataTypesAsyncSample createTableWithDataTypesAsyncSample = new CreateTableWithDataTypesAsyncSample();
InsertDataTypesDataAsyncSample insertDataTypesDataAsyncSample = new InsertDataTypesDataAsyncSample();
CreateTableWithTimestampColumnAsyncSample createTableWithTimestampColumnAsyncSample =
new CreateTableWithTimestampColumnAsyncSample();
await createDatabaseAsyncSample.CreateDatabaseAsync(ProjectId, InstanceId, DatabaseId);
await insertDataAsyncSample.InsertDataAsync(ProjectId, InstanceId, DatabaseId);
await insertStructSampleDataAsyncSample.InsertStructSampleDataAsync(ProjectId, InstanceId, DatabaseId);
await addColumnAsyncSample.AddColumnAsync(ProjectId, InstanceId, DatabaseId);
await addCommitTimestampAsyncSample.AddCommitTimestampAsync(ProjectId, InstanceId, DatabaseId);
await addIndexAsyncSample.AddIndexAsync(ProjectId, InstanceId, DatabaseId);
// Create a new table that includes supported datatypes.
await createTableWithDataTypesAsyncSample.CreateTableWithDataTypesAsync(ProjectId, InstanceId, DatabaseId);
// Write data to the new table.
await insertDataTypesDataAsyncSample.InsertDataTypesDataAsync(ProjectId, InstanceId, DatabaseId);
// Add storing Index on table.
await addStoringIndexAsyncSample.AddStoringIndexAsync(ProjectId, InstanceId, DatabaseId);
// Update the value of MarketingBudgets.
await RefillMarketingBudgetsAsync(300000, 300000);
// Create table with Timestamp column
await createTableWithTimestampColumnAsyncSample.CreateTableWithTimestampColumnAsync(ProjectId, InstanceId, DatabaseId);
}
private async Task InitializeBackupAsync()
{
// Sample database for backup and restore tests.
try
{
CreateDatabaseAsyncSample createDatabaseAsyncSample = new CreateDatabaseAsyncSample();
InsertDataAsyncSample insertDataAsyncSample = new InsertDataAsyncSample();
await createDatabaseAsyncSample.CreateDatabaseAsync(ProjectId, InstanceId, BackupDatabaseId);
await insertDataAsyncSample.InsertDataAsync(ProjectId, InstanceId, BackupDatabaseId);
}
catch (Exception e) when (e.ToString().Contains("Database already exists"))
{
// We intentionally keep an existing database around to reduce
// the likelihood of test timeouts when creating a backup so
// it's ok to get an AlreadyExists error.
Console.WriteLine($"Database {BackupDatabaseId} already exists.");
}
using var connection = new SpannerConnection(ConnectionString);
await connection.OpenAsync();
var currentTimestamp = (DateTime)connection.CreateSelectCommand("SELECT CURRENT_TIMESTAMP").ExecuteScalar();
try
{
CreateBackupSample createBackupSample = new CreateBackupSample();
createBackupSample.CreateBackup(ProjectId, InstanceId, BackupDatabaseId, BackupId, currentTimestamp);
}
catch (RpcException e) when (e.StatusCode == StatusCode.AlreadyExists)
{
// We intentionally keep an existing backup around to reduce
// the likelihood of test timeouts when creating a backup so
// it's ok to get an AlreadyExists error.
Console.WriteLine($"Backup {BackupId} already exists.");
}
catch (RpcException e) when (e.StatusCode == StatusCode.FailedPrecondition
&& e.Message.Contains("maximum number of pending backups (1) for the database has been reached"))
{
// It's ok backup has been in progress in another test cycle.
Console.WriteLine($"Backup {BackupId} already in progress.");
}
}
public async Task CreateVenuesTableAndInsertDataAsync(string databaseId)
{
// Create connection to Cloud Spanner.
using var connection = new SpannerConnection($"Data Source=projects/{ProjectId}/instances/{InstanceId}/databases/{databaseId}");
// Define create table statement for Venues.
string createTableStatement =
@"CREATE TABLE Venues (
VenueId INT64 NOT NULL,
VenueName STRING(1024),
) PRIMARY KEY (VenueId)";
using var cmd = connection.CreateDdlCommand(createTableStatement);
await cmd.ExecuteNonQueryAsync();
List<Venue> venues = new List<Venue>
{
new Venue { VenueId = 4, VenueName = "Venue 4" },
new Venue { VenueId = 19, VenueName = "Venue 19" },
new Venue { VenueId = 42, VenueName = "Venue 42" },
};
await Task.WhenAll(venues.Select(venue =>
{
// Insert rows into the Venues table.
using var cmd = connection.CreateInsertCommand("Venues", new SpannerParameterCollection
{
{ "VenueId", SpannerDbType.Int64, venue.VenueId },
{ "VenueName", SpannerDbType.String, venue.VenueName }
});
return cmd.ExecuteNonQueryAsync();
}));
}
private class Venue
{
public int VenueId { get; set; }
public string VenueName { get; set; }
}
private async Task InitializeEncryptedBackupAsync()
{
// Sample backup for encrypted restore test.
try
{
CreateDatabaseWithEncryptionKeyAsyncSample createDatabaseAsyncSample = new CreateDatabaseWithEncryptionKeyAsyncSample();
InsertDataAsyncSample insertDataAsyncSample = new InsertDataAsyncSample();
await createDatabaseAsyncSample.CreateDatabaseWithEncryptionKeyAsync(ProjectId, InstanceId, FixedEncryptedDatabaseId, KmsKeyName);
await insertDataAsyncSample.InsertDataAsync(ProjectId, InstanceId, FixedEncryptedDatabaseId);
}
catch (Exception e) when (e.ToString().Contains("Database already exists"))
{
// We intentionally keep an existing database around to reduce
// the likelihood of test timeouts when creating a backup so
// it's ok to get an AlreadyExists error.
Console.WriteLine($"Database {FixedEncryptedDatabaseId} already exists.");
}
try
{
CreateBackupWithEncryptionKeyAsyncSample createBackupSample = new CreateBackupWithEncryptionKeyAsyncSample();
await createBackupSample.CreateBackupWithEncryptionKeyAsync(ProjectId, InstanceId, FixedEncryptedDatabaseId, FixedEncryptedBackupId, KmsKeyName);
}
catch (RpcException e) when (e.StatusCode == StatusCode.AlreadyExists)
{
// We intentionally keep an existing backup around to reduce
// the likelihood of test timeouts when creating a backup so
// it's ok to get an AlreadyExists error.
Console.WriteLine($"Backup {FixedEncryptedBackupId} already exists.");
}
}
private async Task InitializeEncryptionKeys()
{
var client = await KeyManagementServiceClient.CreateAsync();
var keyRingName = KeyRingName.FromProjectLocationKeyRing(KmsKeyName.ProjectId, KmsKeyName.LocationId, KmsKeyName.KeyRingId);
try
{
await client.GetKeyRingAsync(keyRingName);
}
catch (RpcException e) when (e.StatusCode == StatusCode.NotFound)
{
await client.CreateKeyRingAsync(new CreateKeyRingRequest
{
ParentAsLocationName = LocationName.FromProjectLocation(keyRingName.ProjectId, keyRingName.LocationId),
KeyRingId = KmsKeyName.KeyRingId,
KeyRing = new KeyRing(),
});
}
var keyName = Google.Cloud.Kms.V1.CryptoKeyName.FromProjectLocationKeyRingCryptoKey(KmsKeyName.ProjectId, KmsKeyName.LocationId, KmsKeyName.KeyRingId, KmsKeyName.CryptoKeyId);
try
{
await client.GetCryptoKeyAsync(keyName);
}
catch (RpcException e) when (e.StatusCode == StatusCode.NotFound)
{
await client.CreateCryptoKeyAsync(new CreateCryptoKeyRequest
{
ParentAsKeyRingName = keyRingName,
CryptoKeyId = keyName.CryptoKeyId,
CryptoKey = new CryptoKey
{
Purpose = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
},
});
}
}
private async Task DeleteDatabaseAsync(string databaseId)
{
string adminConnectionString = $"Data Source=projects/{ProjectId}/instances/{InstanceId}";
using var connection = new SpannerConnection(adminConnectionString);
using var cmd = connection.CreateDdlCommand($@"DROP DATABASE {databaseId}");
await cmd.ExecuteNonQueryAsync();
}
public IEnumerable<Database> GetDatabases()
{
InstanceName instanceName = InstanceName.FromProjectInstance(ProjectId, InstanceId);
var databases = DatabaseAdminClient.ListDatabases(instanceName);
return databases;
}
public async Task RefillMarketingBudgetsAsync(int firstAlbumBudget, int secondAlbumBudget)
{
using var connection = new SpannerConnection(ConnectionString);
await connection.OpenAsync();
for (int i = 1; i <= 2; ++i)
{
var cmd = connection.CreateUpdateCommand("Albums", new SpannerParameterCollection
{
{ "SingerId", SpannerDbType.Int64, i },
{ "AlbumId", SpannerDbType.Int64, i },
{ "MarketingBudget", SpannerDbType.Int64, i == 1 ? firstAlbumBudget : secondAlbumBudget },
});
await cmd.ExecuteNonQueryAsync();
}
}
public async Task RunWithTemporaryDatabaseAsync(Func<string, Task> testFunction, params string[] extraStatements)
=> await RunWithTemporaryDatabaseAsync(InstanceId, testFunction, extraStatements);
public async Task RunWithTemporaryDatabaseAsync(string instanceId, Func<string, Task> testFunction,
params string[] extraStatements)
{
// For temporary DBs we don't need a time based ID, as we delete them inmediately.
var databaseId = $"temp-db-{Guid.NewGuid().ToString("N").Substring(0, 20)}";
await RunWithTemporaryDatabaseAsync(instanceId, databaseId, testFunction, extraStatements);
}
public async Task RunWithTemporaryDatabaseAsync(string instanceId, string databaseId, Func<string, Task> testFunction, params string[] extraStatements)
{
var operation = await DatabaseAdminClient.CreateDatabaseAsync(new CreateDatabaseRequest
{
ParentAsInstanceName = InstanceName.FromProjectInstance(ProjectId, instanceId),
CreateStatement = $"CREATE DATABASE `{databaseId}`",
ExtraStatements = { extraStatements },
});
var completedResponse = await operation.PollUntilCompletedAsync();
if (completedResponse.IsFaulted)
{
throw completedResponse.Exception;
}
try
{
await testFunction(databaseId);
}
finally
{
// Cleanup the test database.
await DatabaseAdminClient.DropDatabaseAsync(DatabaseName.FormatProjectInstanceDatabase(ProjectId, instanceId, databaseId));
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Dns;
using Microsoft.Azure.Management.Dns.Models;
namespace Microsoft.Azure.Management.Dns
{
/// <summary>
/// Client for managing DNS zones and record.
/// </summary>
public static partial class ZoneOperationsExtensions
{
/// <summary>
/// Creates a DNS zone within a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the CreateOrUpdate operation.
/// </param>
/// <returns>
/// The response to a Zone CreateOrUpdate operation.
/// </returns>
public static ZoneCreateOrUpdateResponse CreateOrUpdate(this IZoneOperations operations, string resourceGroupName, string zoneName, ZoneCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IZoneOperations)s).CreateOrUpdateAsync(resourceGroupName, zoneName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a DNS zone within a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the CreateOrUpdate operation.
/// </param>
/// <returns>
/// The response to a Zone CreateOrUpdate operation.
/// </returns>
public static Task<ZoneCreateOrUpdateResponse> CreateOrUpdateAsync(this IZoneOperations operations, string resourceGroupName, string zoneName, ZoneCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, zoneName, parameters, CancellationToken.None);
}
/// <summary>
/// Removes a DNS zone from a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to delete a zone
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IZoneOperations operations, string resourceGroupName, string zoneName, ZoneDeleteParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IZoneOperations)s).DeleteAsync(resourceGroupName, zoneName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Removes a DNS zone from a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to delete a zone
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IZoneOperations operations, string resourceGroupName, string zoneName, ZoneDeleteParameters parameters)
{
return operations.DeleteAsync(resourceGroupName, zoneName, parameters, CancellationToken.None);
}
/// <summary>
/// Gets a DNS zone.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <returns>
/// The response to a Zone Get operation.
/// </returns>
public static ZoneGetResponse Get(this IZoneOperations operations, string resourceGroupName, string zoneName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IZoneOperations)s).GetAsync(resourceGroupName, zoneName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a DNS zone.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <returns>
/// The response to a Zone Get operation.
/// </returns>
public static Task<ZoneGetResponse> GetAsync(this IZoneOperations operations, string resourceGroupName, string zoneName)
{
return operations.GetAsync(resourceGroupName, zoneName, CancellationToken.None);
}
/// <summary>
/// Lists the DNS zones within a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters. If null is passed returns the default
/// number of zones.
/// </param>
/// <returns>
/// The response to a Zone List or ListAll operation.
/// </returns>
public static ZoneListResponse List(this IZoneOperations operations, string resourceGroupName, ZoneListParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IZoneOperations)s).ListAsync(resourceGroupName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the DNS zones within a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters. If null is passed returns the default
/// number of zones.
/// </param>
/// <returns>
/// The response to a Zone List or ListAll operation.
/// </returns>
public static Task<ZoneListResponse> ListAsync(this IZoneOperations operations, string resourceGroupName, ZoneListParameters parameters)
{
return operations.ListAsync(resourceGroupName, parameters, CancellationToken.None);
}
/// <summary>
/// Lists the DNS zones within a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// The response to a Zone List or ListAll operation.
/// </returns>
public static ZoneListResponse ListNext(this IZoneOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IZoneOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the DNS zones within a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// The response to a Zone List or ListAll operation.
/// </returns>
public static Task<ZoneListResponse> ListNextAsync(this IZoneOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
}
}
| |
//
// Authors:
// Christian Hergert <chris@mosaix.net>
// Ben Motmans <ben.motmans@gmail.com>
//
// Copyright (C) 2005 Mosaix Communications, Inc.
// Copyright (c) 2007 Ben Motmans
//
// 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 Gtk;
using System;
using System.Threading;
using MonoDevelop.Database.Sql;
using MonoDevelop.Core;
using MonoDevelop.Ide;
using MonoDevelop.Ide.Gui.Pads;
using MonoDevelop.Database.Query;
using MonoDevelop.Database.Components;
using MonoDevelop.Components.Commands;
using MonoDevelop.Ide.Gui.Components;
namespace MonoDevelop.Database.ConnectionManager
{
public class ConnectionContextNodeBuilder : TypeNodeBuilder
{
public ConnectionContextNodeBuilder ()
: base ()
{
}
public override Type NodeDataType {
get { return typeof (DatabaseConnectionContext); }
}
public override string ContextMenuAddinPath {
get { return "/MonoDevelop/Database/ContextMenu/ConnectionManagerPad/ConnectionNode"; }
}
public override Type CommandHandlerType {
get { return typeof (ConnectionContextCommandHandler); }
}
public override void GetNodeAttributes (ITreeNavigator treeNavigator, object dataObject, ref NodeAttributes attributes)
{
attributes |= NodeAttributes.AllowRename;
}
public override string GetNodeName (ITreeNavigator thisNode, object dataObject)
{
DatabaseConnectionContext context = dataObject as DatabaseConnectionContext;
return context.ConnectionSettings.Name;
}
public override void BuildNode (ITreeBuilder builder, object dataObject, NodeInfo nodeInfo)
{
DatabaseConnectionContext context = dataObject as DatabaseConnectionContext;
if (((bool)builder.Options["ShowDatabaseName"]))
nodeInfo.Label = string.Format ("{0} - ({1})",
context.ConnectionSettings.Name, context.ConnectionSettings.Database);
else
nodeInfo.Label = context.ConnectionSettings.Name;
if (context.HasConnectionPool) {
IConnectionPool pool = context.ConnectionPool;
if (pool.IsInitialized) {
nodeInfo.Icon = Context.GetIcon ("md-db-database-ok");
} else if (pool.HasErrors) {
nodeInfo.Icon = Context.GetIcon ("md-db-database-error");
MessageService.ShowError (AddinCatalog.GetString ("Unable to connect:") + Environment.NewLine + pool.Error);
} else {
nodeInfo.Icon = Context.GetIcon ("md-db-database");
}
} else {
nodeInfo.Icon = Context.GetIcon ("md-db-database");
}
}
public override void BuildChildNodes (ITreeBuilder builder, object dataObject)
{
ThreadPool.QueueUserWorkItem (new WaitCallback (BuildChildNodesThreaded), dataObject);
}
private void BuildChildNodesThreaded (object state)
{
QueryService.EnsureConnection (state as DatabaseConnectionContext, new DatabaseConnectionContextCallback (BuildChildNodesGui), state);
}
private void BuildChildNodesGui (DatabaseConnectionContext context, bool connected, object state)
{
ITreeBuilder builder = Context.GetTreeBuilder (state);
builder.Update ();
if (connected) {
ISchemaProvider provider = context.SchemaProvider;
if (provider.IsSchemaActionSupported (SchemaType.Table, SchemaActions.Schema))
builder.AddChild (new TablesNode (context));
if (provider.IsSchemaActionSupported (SchemaType.View, SchemaActions.Schema))
builder.AddChild (new ViewsNode (context));
if (provider.IsSchemaActionSupported (SchemaType.Procedure, SchemaActions.Schema))
builder.AddChild (new ProceduresNode (context));
if (provider.IsSchemaActionSupported (SchemaType.User, SchemaActions.Schema))
builder.AddChild (new UsersNode (context));
//TODO: custom datatypes, sequences, roles, operators, languages, groups and aggregates
builder.Expanded = true;
}
}
public override bool HasChildNodes (ITreeBuilder builder, object dataObject)
{
return true;
}
}
public class ConnectionContextCommandHandler : NodeCommandHandler
{
public override void RenameItem (string newName)
{
DatabaseConnectionContext context = (DatabaseConnectionContext) CurrentNode.DataItem;
if (context.ConnectionSettings.Name != newName) {
if (ConnectionContextService.DatabaseConnections.Contains (newName)) {
MessageService.ShowError (String.Format (
"Unable to rename connection '{0}' to '{1}'! (duplicate name)",
context.ConnectionSettings.Name, newName
));
} else {
context.ConnectionSettings.Name = newName;
context.Refresh ();
}
}
}
[CommandHandler (ConnectionManagerCommands.RemoveConnection)]
protected void OnRemoveConnection ()
{
DatabaseConnectionContext context = (DatabaseConnectionContext) CurrentNode.DataItem;
if (MessageService.Confirm (
AddinCatalog.GetString ("Are you sure you want to remove connection '{0}'?", context.ConnectionSettings.Name),
AlertButton.Remove)) {
ConnectionContextService.RemoveDatabaseConnectionContext (context);
}
}
[CommandHandler (ConnectionManagerCommands.EditConnection)]
protected void OnEditConnection ()
{
DatabaseConnectionContext context = (DatabaseConnectionContext) CurrentNode.DataItem;
DatabaseConnectionSettings newSettings;
if (context.DbFactory.GuiProvider.ShowEditConnectionDialog (context.DbFactory,
context.ConnectionSettings,
out newSettings)) {
DatabaseConnectionContext newContext = new DatabaseConnectionContext (newSettings);
ConnectionContextService.RemoveDatabaseConnectionContext (context);
ConnectionContextService.AddDatabaseConnectionContext (newContext);
newContext.Refresh ();
}
}
[CommandHandler (ConnectionManagerCommands.DisconnectConnection)]
protected void OnDisconnectConnection ()
{
DatabaseConnectionContext context = (DatabaseConnectionContext) CurrentNode.DataItem;
if (context.HasConnectionPool) {
context.ConnectionPool.Close ();
context.Refresh ();
CurrentNode.Expanded = false;
}
}
[CommandUpdateHandler (ConnectionManagerCommands.DisconnectConnection)]
protected void OnUpdateDisconnectConnection (CommandInfo info)
{
DatabaseConnectionContext context = (DatabaseConnectionContext) CurrentNode.DataItem;
info.Enabled = context.HasConnectionPool && context.ConnectionPool.IsInitialized;
}
[CommandHandler (ConnectionManagerCommands.ConnectConnection)]
protected void OnConnectConnection ()
{
CurrentNode.Expanded = true;
}
[CommandUpdateHandler (ConnectionManagerCommands.ConnectConnection)]
protected void OnUpdateConnectConnection (CommandInfo info)
{
DatabaseConnectionContext context = (DatabaseConnectionContext) CurrentNode.DataItem;
if (context.HasConnectionPool)
info.Enabled = !context.ConnectionPool.IsInitialized;
else
info.Enabled = true;
}
public override void ActivateItem ()
{
OnQueryCommand ();
}
[CommandHandler (ConnectionManagerCommands.Query)]
protected void OnQueryCommand ()
{
SqlQueryView view = new SqlQueryView ();
view.SelectedConnectionContext = (DatabaseConnectionContext) CurrentNode.DataItem;
IdeApp.Workbench.OpenDocument (view, true);
}
[CommandHandler (ConnectionManagerCommands.DropDatabase)]
protected void OnDropDatabase ()
{
DatabaseConnectionContext context = (DatabaseConnectionContext) CurrentNode.DataItem;
AlertButton dropButton = new AlertButton (AddinCatalog.GetString ("Drop"), Gtk.Stock.Delete);
if (MessageService.Confirm (
AddinCatalog.GetString ("Are you sure you want to drop database '{0}'", context.ConnectionSettings.Database),
dropButton
)) {
ThreadPool.QueueUserWorkItem (new WaitCallback (OnDropDatabaseThreaded), CurrentNode.DataItem);
}
}
private void OnDropDatabaseThreaded (object state)
{
DatabaseConnectionContext context = (DatabaseConnectionContext) CurrentNode.DataItem;
try {
context.ConnectionPool.Initialize ();
ISchemaProvider provider = context.SchemaProvider;
DatabaseSchema db = provider.CreateDatabaseSchema (context.ConnectionSettings.Database);
IEditSchemaProvider schemaProvider = (IEditSchemaProvider)context.SchemaProvider;
schemaProvider.DropDatabase (db);
ConnectionContextService.RemoveDatabaseConnectionContext (context);
} catch (Exception ex) {
DispatchService.GuiDispatch (delegate {
MessageService.ShowException (ex);
});
}
}
[CommandUpdateHandler (ConnectionManagerCommands.DropDatabase)]
protected void OnUpdateDropDatabase (CommandInfo info)
{
DatabaseConnectionContext context = (DatabaseConnectionContext) CurrentNode.DataItem;
//info.Enabled = context.DbFactory.IsActionSupported ("Database", SchemaActions.Drop);
}
[CommandUpdateHandler (ConnectionManagerCommands.AlterDatabase)]
protected void OnUpdateAlterDatabase (CommandInfo info)
{
DatabaseConnectionContext context = (DatabaseConnectionContext) CurrentNode.DataItem;
//info.Enabled = context.DbFactory.IsActionSupported ("Database", SchemaActions.Alter);
}
[CommandHandler (MonoDevelop.Ide.Commands.EditCommands.Rename)]
protected void OnRenameDatabase ()
{
//TODO: show a dialog, since inline tree renaming for this node renames the custom name
}
[CommandUpdateHandler (ConnectionManagerCommands.RenameDatabase)]
protected void OnUpdateRenameDatabase (CommandInfo info)
{
DatabaseConnectionContext context = (DatabaseConnectionContext) CurrentNode.DataItem;
//info.Enabled = context.DbFactory.IsActionSupported ("Database", SchemaActions.Rename);
}
}
}
| |
// 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.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
namespace System.Reflection
{
// This file defines an internal class used to throw exceptions. The main purpose is to reduce code size.
// Also it improves the likelihood that callers will be inlined.
internal static class Throw
{
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidCast()
{
throw new InvalidCastException();
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void LitteEndianArchitectureRequired()
{
throw new PlatformNotSupportedException(SR.LitteEndianArchitectureRequired);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidArgument(string message, string parameterName)
{
throw new ArgumentException(message, parameterName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidArgument_OffsetForVirtualHeapHandle()
{
throw new ArgumentException(SR.CantGetOffsetForVirtualHeapHandle, "handle");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static Exception InvalidArgument_UnexpectedHandleKind(HandleKind kind)
{
throw new ArgumentException(SR.Format(SR.UnexpectedHandleKind, kind));
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static Exception InvalidArgument_Handle(string parameterName)
{
throw new ArgumentException(SR.Format(SR.InvalidHandle), parameterName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void SignatureNotVarArg()
{
throw new InvalidOperationException(SR.SignatureNotVarArg);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void BranchBuilderNotAvailable()
{
throw new InvalidOperationException(SR.BranchBuilderNotAvailable);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperationBuilderAlreadyLinked()
{
throw new InvalidOperationException(SR.BuilderAlreadyLinked);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperation(string message)
{
throw new InvalidOperationException(message);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void LabelDoesntBelongToBuilder(string parameterName)
{
throw new ArgumentException(SR.LabelDoesntBelongToBuilder, parameterName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void HeapHandleRequired()
{
throw new ArgumentException(SR.NotMetadataHeapHandle, "handle");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void EntityOrUserStringHandleRequired()
{
throw new ArgumentException(SR.NotMetadataTableOrUserStringHandle, "handle");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidToken()
{
throw new ArgumentException(SR.InvalidToken, "token");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentNull(string parameterName)
{
throw new ArgumentNullException(parameterName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentEmptyString(string parameterName)
{
throw new ArgumentException(SR.ExpectedNonEmptyString, parameterName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ValueArgumentNull()
{
throw new ArgumentNullException("value");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void BuilderArgumentNull()
{
throw new ArgumentNullException("builder");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentOutOfRange(string parameterName)
{
throw new ArgumentOutOfRangeException(parameterName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void BlobTooLarge(string parameterName)
{
throw new ArgumentOutOfRangeException(parameterName, SR.BlobTooLarge);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void IndexOutOfRange()
{
throw new ArgumentOutOfRangeException("index");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TableIndexOutOfRange()
{
throw new ArgumentOutOfRangeException("tableIndex");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ValueArgumentOutOfRange()
{
throw new ArgumentOutOfRangeException("value");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void OutOfBounds()
{
throw new BadImageFormatException(SR.OutOfBoundsRead);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void WriteOutOfBounds()
{
throw new InvalidOperationException(SR.OutOfBoundsWrite);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidCodedIndex()
{
throw new BadImageFormatException(SR.InvalidCodedIndex);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidHandle()
{
throw new BadImageFormatException(SR.InvalidHandle);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidCompressedInteger()
{
throw new BadImageFormatException(SR.InvalidCompressedInteger);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidSerializedString()
{
throw new BadImageFormatException(SR.InvalidSerializedString);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ImageTooSmall()
{
throw new BadImageFormatException(SR.ImageTooSmall);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ImageTooSmallOrContainsInvalidOffsetOrCount()
{
throw new BadImageFormatException(SR.ImageTooSmallOrContainsInvalidOffsetOrCount);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ReferenceOverflow()
{
throw new BadImageFormatException(SR.RowIdOrHeapOffsetTooLarge);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TableNotSorted(TableIndex tableIndex)
{
throw new BadImageFormatException(SR.Format(SR.MetadataTableNotSorted, (int)tableIndex));
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TooManySubnamespaces()
{
throw new BadImageFormatException(SR.TooManySubnamespaces);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ValueOverflow()
{
throw new BadImageFormatException(SR.ValueTooLarge);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void SequencePointValueOutOfRange()
{
throw new BadImageFormatException(SR.SequencePointValueOutOfRange);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void HeapSizeLimitExceeded(HeapIndex heap)
{
throw new ImageFormatLimitationException(SR.Format(SR.HeapSizeLimitExceeded, heap));
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Management.ServiceBus;
using Microsoft.WindowsAzure.Management.ServiceBus.Models;
namespace Microsoft.WindowsAzure
{
/// <summary>
/// The Service Bus Management API is a REST API for managing Service Bus
/// queues, topics, rules and subscriptions. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/hh780776.aspx for
/// more information)
/// </summary>
public static partial class NamespaceOperationsExtensions
{
/// <summary>
/// Checks the availability of the given service namespace across all
/// Windows Azure subscriptions. This is useful because the domain
/// name is created based on the service namespace name. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj870968.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <returns>
/// The response to a query for the availability status of a namespace
/// name.
/// </returns>
public static CheckNamespaceAvailabilityResponse CheckAvailability(this INamespaceOperations operations, string namespaceName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).CheckAvailabilityAsync(namespaceName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Checks the availability of the given service namespace across all
/// Windows Azure subscriptions. This is useful because the domain
/// name is created based on the service namespace name. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj870968.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <returns>
/// The response to a query for the availability status of a namespace
/// name.
/// </returns>
public static Task<CheckNamespaceAvailabilityResponse> CheckAvailabilityAsync(this INamespaceOperations operations, string namespaceName)
{
return operations.CheckAvailabilityAsync(namespaceName, CancellationToken.None);
}
/// <summary>
/// Creates a new service namespace. Once created, this namespace's
/// resource manifest is immutable. This operation is idempotent.
/// (see http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='region'>
/// Optional. The namespace region.
/// </param>
/// <returns>
/// The response to a request for a particular namespace.
/// </returns>
public static ServiceBusNamespaceResponse Create(this INamespaceOperations operations, string namespaceName, string region)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).CreateAsync(namespaceName, region);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new service namespace. Once created, this namespace's
/// resource manifest is immutable. This operation is idempotent.
/// (see http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='region'>
/// Optional. The namespace region.
/// </param>
/// <returns>
/// The response to a request for a particular namespace.
/// </returns>
public static Task<ServiceBusNamespaceResponse> CreateAsync(this INamespaceOperations operations, string namespaceName, string region)
{
return operations.CreateAsync(namespaceName, region, CancellationToken.None);
}
/// <summary>
/// The create namespace authorization rule operation creates an
/// authorization rule for a namespace
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='rule'>
/// Required. The shared access authorization rule.
/// </param>
/// <returns>
/// A response to a request for a particular authorization rule.
/// </returns>
public static ServiceBusAuthorizationRuleResponse CreateAuthorizationRule(this INamespaceOperations operations, string namespaceName, ServiceBusSharedAccessAuthorizationRule rule)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).CreateAuthorizationRuleAsync(namespaceName, rule);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The create namespace authorization rule operation creates an
/// authorization rule for a namespace
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='rule'>
/// Required. The shared access authorization rule.
/// </param>
/// <returns>
/// A response to a request for a particular authorization rule.
/// </returns>
public static Task<ServiceBusAuthorizationRuleResponse> CreateAuthorizationRuleAsync(this INamespaceOperations operations, string namespaceName, ServiceBusSharedAccessAuthorizationRule rule)
{
return operations.CreateAuthorizationRuleAsync(namespaceName, rule, CancellationToken.None);
}
/// <summary>
/// Creates a new service namespace. Once created, this namespace's
/// resource manifest is immutable. This operation is idempotent.
/// (see http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='namespaceEntity'>
/// Required. The service bus namespace.
/// </param>
/// <returns>
/// The response to a request for a particular namespace.
/// </returns>
public static ServiceBusNamespaceResponse CreateNamespace(this INamespaceOperations operations, string namespaceName, ServiceBusNamespaceCreateParameters namespaceEntity)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).CreateNamespaceAsync(namespaceName, namespaceEntity);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new service namespace. Once created, this namespace's
/// resource manifest is immutable. This operation is idempotent.
/// (see http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='namespaceEntity'>
/// Required. The service bus namespace.
/// </param>
/// <returns>
/// The response to a request for a particular namespace.
/// </returns>
public static Task<ServiceBusNamespaceResponse> CreateNamespaceAsync(this INamespaceOperations operations, string namespaceName, ServiceBusNamespaceCreateParameters namespaceEntity)
{
return operations.CreateNamespaceAsync(namespaceName, namespaceEntity, CancellationToken.None);
}
/// <summary>
/// Deletes an existing namespace. This operation also removes all
/// associated entities including queues, topics, relay points, and
/// messages stored under the namespace. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse Delete(this INamespaceOperations operations, string namespaceName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).DeleteAsync(namespaceName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an existing namespace. This operation also removes all
/// associated entities including queues, topics, relay points, and
/// messages stored under the namespace. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> DeleteAsync(this INamespaceOperations operations, string namespaceName)
{
return operations.DeleteAsync(namespaceName, CancellationToken.None);
}
/// <summary>
/// The delete namespace authorization rule operation deletes an
/// authorization rule for a namespace
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='ruleName'>
/// Required. The rule name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse DeleteAuthorizationRule(this INamespaceOperations operations, string namespaceName, string ruleName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).DeleteAuthorizationRuleAsync(namespaceName, ruleName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The delete namespace authorization rule operation deletes an
/// authorization rule for a namespace
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='ruleName'>
/// Required. The rule name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> DeleteAuthorizationRuleAsync(this INamespaceOperations operations, string namespaceName, string ruleName)
{
return operations.DeleteAuthorizationRuleAsync(namespaceName, ruleName, CancellationToken.None);
}
/// <summary>
/// Returns the description for the specified namespace. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn140232.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <returns>
/// The response to a request for a particular namespace.
/// </returns>
public static ServiceBusNamespaceResponse Get(this INamespaceOperations operations, string namespaceName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).GetAsync(namespaceName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns the description for the specified namespace. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn140232.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <returns>
/// The response to a request for a particular namespace.
/// </returns>
public static Task<ServiceBusNamespaceResponse> GetAsync(this INamespaceOperations operations, string namespaceName)
{
return operations.GetAsync(namespaceName, CancellationToken.None);
}
/// <summary>
/// The get authorization rule operation gets an authorization rule for
/// a namespace by name.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace to get the authorization rule for.
/// </param>
/// <param name='entityName'>
/// Required. The entity name to get the authorization rule for.
/// </param>
/// <returns>
/// A response to a request for a particular authorization rule.
/// </returns>
public static ServiceBusAuthorizationRuleResponse GetAuthorizationRule(this INamespaceOperations operations, string namespaceName, string entityName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).GetAuthorizationRuleAsync(namespaceName, entityName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The get authorization rule operation gets an authorization rule for
/// a namespace by name.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace to get the authorization rule for.
/// </param>
/// <param name='entityName'>
/// Required. The entity name to get the authorization rule for.
/// </param>
/// <returns>
/// A response to a request for a particular authorization rule.
/// </returns>
public static Task<ServiceBusAuthorizationRuleResponse> GetAuthorizationRuleAsync(this INamespaceOperations operations, string namespaceName, string entityName)
{
return operations.GetAuthorizationRuleAsync(namespaceName, entityName, CancellationToken.None);
}
/// <summary>
/// The namespace description is an XML AtomPub document that defines
/// the desired semantics for a service namespace. The namespace
/// description contains the following properties. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <returns>
/// A response to a request for a list of namespaces.
/// </returns>
public static ServiceBusNamespaceDescriptionResponse GetNamespaceDescription(this INamespaceOperations operations, string namespaceName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).GetNamespaceDescriptionAsync(namespaceName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The namespace description is an XML AtomPub document that defines
/// the desired semantics for a service namespace. The namespace
/// description contains the following properties. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <returns>
/// A response to a request for a list of namespaces.
/// </returns>
public static Task<ServiceBusNamespaceDescriptionResponse> GetNamespaceDescriptionAsync(this INamespaceOperations operations, string namespaceName)
{
return operations.GetNamespaceDescriptionAsync(namespaceName, CancellationToken.None);
}
/// <summary>
/// Lists the available namespaces. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn140232.asp
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <returns>
/// The response to the request for a listing of namespaces.
/// </returns>
public static ServiceBusNamespacesResponse List(this INamespaceOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).ListAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the available namespaces. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn140232.asp
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <returns>
/// The response to the request for a listing of namespaces.
/// </returns>
public static Task<ServiceBusNamespacesResponse> ListAsync(this INamespaceOperations operations)
{
return operations.ListAsync(CancellationToken.None);
}
/// <summary>
/// The get authorization rules operation gets the authorization rules
/// for a namespace.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace to get the authorization rule for.
/// </param>
/// <returns>
/// A response to a request for a list of authorization rules.
/// </returns>
public static ServiceBusAuthorizationRulesResponse ListAuthorizationRules(this INamespaceOperations operations, string namespaceName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).ListAuthorizationRulesAsync(namespaceName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The get authorization rules operation gets the authorization rules
/// for a namespace.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace to get the authorization rule for.
/// </param>
/// <returns>
/// A response to a request for a list of authorization rules.
/// </returns>
public static Task<ServiceBusAuthorizationRulesResponse> ListAuthorizationRulesAsync(this INamespaceOperations operations, string namespaceName)
{
return operations.ListAuthorizationRulesAsync(namespaceName, CancellationToken.None);
}
/// <summary>
/// The update authorization rule operation updates an authorization
/// rule for a namespace.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='rule'>
/// Optional. Updated access authorization rule.
/// </param>
/// <returns>
/// A response to a request for a particular authorization rule.
/// </returns>
public static ServiceBusAuthorizationRuleResponse UpdateAuthorizationRule(this INamespaceOperations operations, string namespaceName, ServiceBusSharedAccessAuthorizationRule rule)
{
return Task.Factory.StartNew((object s) =>
{
return ((INamespaceOperations)s).UpdateAuthorizationRuleAsync(namespaceName, rule);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The update authorization rule operation updates an authorization
/// rule for a namespace.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INamespaceOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='rule'>
/// Optional. Updated access authorization rule.
/// </param>
/// <returns>
/// A response to a request for a particular authorization rule.
/// </returns>
public static Task<ServiceBusAuthorizationRuleResponse> UpdateAuthorizationRuleAsync(this INamespaceOperations operations, string namespaceName, ServiceBusSharedAccessAuthorizationRule rule)
{
return operations.UpdateAuthorizationRuleAsync(namespaceName, rule, CancellationToken.None);
}
}
}
| |
// 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 is where we group together all the runtime export calls.
//
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using Internal.Runtime;
using Internal.Runtime.CompilerServices;
namespace System.Runtime
{
internal static class RuntimeExports
{
//
// internal calls for allocation
//
[RuntimeExport("RhNewObject")]
public static unsafe object RhNewObject(EETypePtr pEEType)
{
EEType* ptrEEType = (EEType*)pEEType.ToPointer();
// This is structured in a funny way because at the present state of things in CoreRT, the Debug.Assert
// below will call into the assert defined in the class library (and not the MRT version of it). The one
// in the class library is not low level enough to be callable when GC statics are not initialized yet.
// Feel free to restructure once that's not a problem.
#if DEBUG
bool isValid = !ptrEEType->IsGenericTypeDefinition &&
!ptrEEType->IsInterface &&
!ptrEEType->IsArray &&
!ptrEEType->IsString &&
!ptrEEType->IsByRefLike;
if (!isValid)
Debug.Assert(false);
#endif
#if FEATURE_64BIT_ALIGNMENT
if (ptrEEType->RequiresAlign8)
{
if (ptrEEType->IsValueType)
return InternalCalls.RhpNewFastMisalign(ptrEEType);
if (ptrEEType->IsFinalizable)
return InternalCalls.RhpNewFinalizableAlign8(ptrEEType);
return InternalCalls.RhpNewFastAlign8(ptrEEType);
}
else
#endif // FEATURE_64BIT_ALIGNMENT
{
if (ptrEEType->IsFinalizable)
return InternalCalls.RhpNewFinalizable(ptrEEType);
return InternalCalls.RhpNewFast(ptrEEType);
}
}
[RuntimeExport("RhNewArray")]
public static unsafe object RhNewArray(EETypePtr pEEType, int length)
{
EEType* ptrEEType = (EEType*)pEEType.ToPointer();
Debug.Assert(ptrEEType->IsArray || ptrEEType->IsString);
#if FEATURE_64BIT_ALIGNMENT
if (ptrEEType->RequiresAlign8)
{
return InternalCalls.RhpNewArrayAlign8(ptrEEType, length);
}
else
#endif // FEATURE_64BIT_ALIGNMENT
{
return InternalCalls.RhpNewArray(ptrEEType, length);
}
}
[RuntimeExport("RhBox")]
public static unsafe object RhBox(EETypePtr pEEType, ref byte data)
{
EEType* ptrEEType = (EEType*)pEEType.ToPointer();
int dataOffset = 0;
object result;
// If we're boxing a Nullable<T> then either box the underlying T or return null (if the
// nullable's value is empty).
if (ptrEEType->IsNullable)
{
// The boolean which indicates whether the value is null comes first in the Nullable struct.
if (data == 0)
return null;
// Switch type we're going to box to the Nullable<T> target type and advance the data pointer
// to the value embedded within the nullable.
dataOffset = ptrEEType->NullableValueOffset;
ptrEEType = ptrEEType->NullableType;
}
#if FEATURE_64BIT_ALIGNMENT
if (ptrEEType->RequiresAlign8)
{
result = InternalCalls.RhpNewFastMisalign(ptrEEType);
}
else
#endif // FEATURE_64BIT_ALIGNMENT
{
result = InternalCalls.RhpNewFast(ptrEEType);
}
InternalCalls.RhpBox(result, ref Unsafe.Add(ref data, dataOffset));
return result;
}
[RuntimeExport("RhBoxAny")]
public static unsafe object RhBoxAny(ref byte data, EETypePtr pEEType)
{
EEType* ptrEEType = (EEType*)pEEType.ToPointer();
if (ptrEEType->IsValueType)
{
return RhBox(pEEType, ref data);
}
else
{
return Unsafe.As<byte, Object>(ref data);
}
}
private static unsafe bool UnboxAnyTypeCompare(EEType* pEEType, EEType* ptrUnboxToEEType)
{
if (TypeCast.AreTypesEquivalentInternal(pEEType, ptrUnboxToEEType))
return true;
if (pEEType->CorElementType == ptrUnboxToEEType->CorElementType)
{
// Enum's and primitive types should pass the UnboxAny exception cases
// if they have an exactly matching cor element type.
switch (ptrUnboxToEEType->CorElementType)
{
case CorElementType.ELEMENT_TYPE_I1:
case CorElementType.ELEMENT_TYPE_U1:
case CorElementType.ELEMENT_TYPE_I2:
case CorElementType.ELEMENT_TYPE_U2:
case CorElementType.ELEMENT_TYPE_I4:
case CorElementType.ELEMENT_TYPE_U4:
case CorElementType.ELEMENT_TYPE_I8:
case CorElementType.ELEMENT_TYPE_U8:
case CorElementType.ELEMENT_TYPE_I:
case CorElementType.ELEMENT_TYPE_U:
return true;
}
}
return false;
}
[RuntimeExport("RhUnboxAny")]
public static unsafe void RhUnboxAny(object o, ref byte data, EETypePtr pUnboxToEEType)
{
EEType* ptrUnboxToEEType = (EEType*)pUnboxToEEType.ToPointer();
if (ptrUnboxToEEType->IsValueType)
{
bool isValid = false;
if (ptrUnboxToEEType->IsNullable)
{
isValid = (o == null) || TypeCast.AreTypesEquivalentInternal(o.EEType, ptrUnboxToEEType->NullableType);
}
else
{
isValid = (o != null) && UnboxAnyTypeCompare(o.EEType, ptrUnboxToEEType);
}
if (!isValid)
{
// Throw the invalid cast exception defined by the classlib, using the input unbox EEType*
// to find the correct classlib.
ExceptionIDs exID = o == null ? ExceptionIDs.NullReference : ExceptionIDs.InvalidCast;
throw ptrUnboxToEEType->GetClasslibException(exID);
}
InternalCalls.RhUnbox(o, ref data, ptrUnboxToEEType);
}
else
{
if (o != null && (TypeCast.IsInstanceOf(o, ptrUnboxToEEType) == null))
{
throw ptrUnboxToEEType->GetClasslibException(ExceptionIDs.InvalidCast);
}
Unsafe.As<byte, Object>(ref data) = o;
}
}
//
// Unbox helpers with RyuJIT conventions
//
[RuntimeExport("RhUnbox2")]
public static unsafe ref byte RhUnbox2(EETypePtr pUnboxToEEType, Object obj)
{
EEType* ptrUnboxToEEType = (EEType*)pUnboxToEEType.ToPointer();
if ((obj == null) || !UnboxAnyTypeCompare(obj.EEType, ptrUnboxToEEType))
{
ExceptionIDs exID = obj == null ? ExceptionIDs.NullReference : ExceptionIDs.InvalidCast;
throw ptrUnboxToEEType->GetClasslibException(exID);
}
return ref obj.GetRawData();
}
[RuntimeExport("RhUnboxNullable")]
public static unsafe void RhUnboxNullable(ref byte data, EETypePtr pUnboxToEEType, Object obj)
{
EEType* ptrUnboxToEEType = (EEType*)pUnboxToEEType.ToPointer();
if ((obj != null) && !TypeCast.AreTypesEquivalentInternal(obj.EEType, ptrUnboxToEEType->NullableType))
{
throw ptrUnboxToEEType->GetClasslibException(ExceptionIDs.InvalidCast);
}
InternalCalls.RhUnbox(obj, ref data, ptrUnboxToEEType);
}
[RuntimeExport("RhArrayStoreCheckAny")]
public static unsafe void RhArrayStoreCheckAny(object array, ref byte data)
{
if (array == null)
{
return;
}
Debug.Assert(array.EEType->IsArray, "first argument must be an array");
EEType* arrayElemType = array.EEType->RelatedParameterType;
if (arrayElemType->IsValueType)
{
return;
}
TypeCast.CheckArrayStore(array, Unsafe.As<byte, Object>(ref data));
}
[RuntimeExport("RhBoxAndNullCheck")]
public static unsafe bool RhBoxAndNullCheck(ref byte data, EETypePtr pEEType)
{
EEType* ptrEEType = (EEType*)pEEType.ToPointer();
if (ptrEEType->IsValueType)
return true;
else
return Unsafe.As<byte, Object>(ref data) != null;
}
#pragma warning disable 169 // The field 'System.Runtime.RuntimeExports.Wrapper.o' is never used.
private class Wrapper
{
private Object _o;
}
#pragma warning restore 169
[RuntimeExport("RhAllocLocal")]
public static unsafe object RhAllocLocal(EETypePtr pEEType)
{
EEType* ptrEEType = (EEType*)pEEType.ToPointer();
if (ptrEEType->IsValueType)
{
#if FEATURE_64BIT_ALIGNMENT
if (ptrEEType->RequiresAlign8)
return InternalCalls.RhpNewFastMisalign(ptrEEType);
#endif
return InternalCalls.RhpNewFast(ptrEEType);
}
else
return new Wrapper();
}
// RhAllocLocal2 helper returns the pointer to the data region directly
// instead of relying on the code generator to offset the local by the
// size of a pointer to get the data region.
[RuntimeExport("RhAllocLocal2")]
public static unsafe ref byte RhAllocLocal2(EETypePtr pEEType)
{
EEType* ptrEEType = (EEType*)pEEType.ToPointer();
if (ptrEEType->IsValueType)
{
#if FEATURE_64BIT_ALIGNMENT
if (ptrEEType->RequiresAlign8)
return ref InternalCalls.RhpNewFastMisalign(ptrEEType).GetRawData();
#endif
return ref InternalCalls.RhpNewFast(ptrEEType).GetRawData();
}
else
return ref new Wrapper().GetRawData();
}
[RuntimeExport("RhMemberwiseClone")]
public static unsafe object RhMemberwiseClone(object src)
{
object objClone;
if (src.EEType->IsArray)
objClone = RhNewArray(new EETypePtr((IntPtr)src.EEType), Unsafe.As<Array>(src).Length);
else
objClone = RhNewObject(new EETypePtr((IntPtr)src.EEType));
InternalCalls.RhpCopyObjectContents(objClone, src);
return objClone;
}
[RuntimeExport("RhpReversePInvokeBadTransition")]
public static void RhpReversePInvokeBadTransition(IntPtr returnAddress)
{
EH.FailFastViaClasslib(
RhFailFastReason.IllegalNativeCallableEntry,
null,
returnAddress);
}
[RuntimeExport("RhGetCurrentThreadStackTrace")]
[MethodImpl(MethodImplOptions.NoInlining)] // Ensures that the RhGetCurrentThreadStackTrace frame is always present
public static unsafe int RhGetCurrentThreadStackTrace(IntPtr[] outputBuffer)
{
fixed (IntPtr* pOutputBuffer = outputBuffer)
return RhpGetCurrentThreadStackTrace(pOutputBuffer, (uint)((outputBuffer != null) ? outputBuffer.Length : 0));
}
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe int RhpGetCurrentThreadStackTrace(IntPtr* pOutputBuffer, uint outputBufferLength);
// Worker for RhGetCurrentThreadStackTrace. RhGetCurrentThreadStackTrace just allocates a transition
// frame that will be used to seed the stack trace and this method does all the real work.
//
// Input: outputBuffer may be null or non-null
// Return value: positive: number of entries written to outputBuffer
// negative: number of required entries in outputBuffer in case it's too small (or null)
// Output: outputBuffer is filled in with return address IPs, starting with placing the this
// method's return address into index 0
//
// NOTE: We don't want to allocate the array on behalf of the caller because we don't know which class
// library's objects the caller understands (we support multiple class libraries with multiple root
// System.Object types).
[NativeCallable(EntryPoint = "RhpCalculateStackTraceWorker", CallingConvention = CallingConvention.Cdecl)]
private static unsafe int RhpCalculateStackTraceWorker(IntPtr* pOutputBuffer, uint outputBufferLength)
{
uint nFrames = 0;
bool success = true;
StackFrameIterator frameIter = new StackFrameIterator();
bool isValid = frameIter.Init(null);
Debug.Assert(isValid, "Missing RhGetCurrentThreadStackTrace frame");
// Note that the while loop will skip RhGetCurrentThreadStackTrace frame
while (frameIter.Next())
{
if (nFrames < outputBufferLength)
pOutputBuffer[nFrames] = new IntPtr(frameIter.ControlPC);
else
success = false;
nFrames++;
}
return success ? (int)nFrames : -(int)nFrames;
}
// The GC conservative reporting descriptor is a special structure of data that the GC
// parses to determine whether there are specific regions of memory that it should not
// collect or move around.
// During garbage collection, the GC will inspect the data in this structure, and verify that:
// 1) _magic is set to the magic number (also hard coded on the GC side)
// 2) The reported region is valid (checks alignments, size, within bounds of the thread memory, etc...)
// 3) The ConservativelyReportedRegionDesc pointer must be reported by a frame which does not make a pinvoke transition.
// 4) The value of the _hash field is the computed hash of _regionPointerLow with _regionPointerHigh
// 5) The region must be IntPtr aligned, and have a size which is also IntPtr aligned
// If all conditions are satisfied, the region of memory starting at _regionPointerLow and ending at
// _regionPointerHigh will be conservatively reported.
// This can only be used to report memory regions on the current stack and the structure must itself
// be located on the stack.
public struct ConservativelyReportedRegionDesc
{
internal const ulong MagicNumber64 = 0x87DF7A104F09E0A9UL;
internal const uint MagicNumber32 = 0x4F09E0A9;
internal UIntPtr _magic;
internal UIntPtr _regionPointerLow;
internal UIntPtr _regionPointerHigh;
internal UIntPtr _hash;
}
[RuntimeExport("RhInitializeConservativeReportingRegion")]
public static unsafe void RhInitializeConservativeReportingRegion(ConservativelyReportedRegionDesc* regionDesc, void* bufferBegin, int cbBuffer)
{
Debug.Assert((((int)bufferBegin) & (sizeof(IntPtr) - 1)) == 0, "Buffer not IntPtr aligned");
Debug.Assert((cbBuffer & (sizeof(IntPtr) - 1)) == 0, "Size of buffer not IntPtr aligned");
UIntPtr regionPointerLow = (UIntPtr)bufferBegin;
UIntPtr regionPointerHigh = (UIntPtr)(((byte*)bufferBegin) + cbBuffer);
// Setup pointers to start and end of region
regionDesc->_regionPointerLow = regionPointerLow;
regionDesc->_regionPointerHigh = regionPointerHigh;
// Activate the region for processing
#if BIT64
ulong hash = ConservativelyReportedRegionDesc.MagicNumber64;
hash = ((hash << 13) ^ hash) ^ (ulong)regionPointerLow;
hash = ((hash << 13) ^ hash) ^ (ulong)regionPointerHigh;
regionDesc->_hash = new UIntPtr(hash);
regionDesc->_magic = new UIntPtr(ConservativelyReportedRegionDesc.MagicNumber64);
#else
uint hash = ConservativelyReportedRegionDesc.MagicNumber32;
hash = ((hash << 13) ^ hash) ^ (uint)regionPointerLow;
hash = ((hash << 13) ^ hash) ^ (uint)regionPointerHigh;
regionDesc->_hash = new UIntPtr(hash);
regionDesc->_magic = new UIntPtr(ConservativelyReportedRegionDesc.MagicNumber32);
#endif
}
// Disable conservative reporting
[RuntimeExport("RhDisableConservativeReportingRegion")]
public static unsafe void RhDisableConservativeReportingRegion(ConservativelyReportedRegionDesc* regionDesc)
{
regionDesc->_magic = default(UIntPtr);
}
[RuntimeExport("RhCreateThunksHeap")]
public static object RhCreateThunksHeap(IntPtr commonStubAddress)
{
return ThunksHeap.CreateThunksHeap(commonStubAddress);
}
[RuntimeExport("RhAllocateThunk")]
public static IntPtr RhAllocateThunk(object thunksHeap)
{
return ((ThunksHeap)thunksHeap).AllocateThunk();
}
[RuntimeExport("RhFreeThunk")]
public static void RhFreeThunk(object thunksHeap, IntPtr thunkAddress)
{
((ThunksHeap)thunksHeap).FreeThunk(thunkAddress);
}
[RuntimeExport("RhSetThunkData")]
public static void RhSetThunkData(object thunksHeap, IntPtr thunkAddress, IntPtr context, IntPtr target)
{
((ThunksHeap)thunksHeap).SetThunkData(thunkAddress, context, target);
}
[RuntimeExport("RhTryGetThunkData")]
public static bool RhTryGetThunkData(object thunksHeap, IntPtr thunkAddress, out IntPtr context, out IntPtr target)
{
return ((ThunksHeap)thunksHeap).TryGetThunkData(thunkAddress, out context, out target);
}
[RuntimeExport("RhGetThunkSize")]
public static int RhGetThunkSize()
{
return InternalCalls.RhpGetThunkSize();
}
}
}
| |
// Copyright (C) 2015 Google, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Reflection;
using GoogleMobileAds.Api;
using UnityEngine;
namespace GoogleMobileAds.Common
{
public class DummyClient : IBannerClient, IInterstitialClient, IRewardBasedVideoAdClient,
IAdLoaderClient, INativeExpressAdClient, IMobileAdsClient
{
public DummyClient()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
// Disable warnings for unused dummy ad events.
#pragma warning disable 67
public event EventHandler<EventArgs> OnAdLoaded;
public event EventHandler<AdFailedToLoadEventArgs> OnAdFailedToLoad;
public event EventHandler<EventArgs> OnAdOpening;
public event EventHandler<EventArgs> OnAdStarted;
public event EventHandler<EventArgs> OnAdClosed;
public event EventHandler<Reward> OnAdRewarded;
public event EventHandler<EventArgs> OnAdLeavingApplication;
public event EventHandler<CustomNativeEventArgs> OnCustomNativeTemplateAdLoaded;
#pragma warning restore 67
public string UserId
{
get
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
return "UserId";
}
set
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
}
public void Initialize(string appId)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void SetApplicationMuted(bool muted)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void SetApplicationVolume(float volume)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void CreateBannerView(string adUnitId, AdSize adSize, AdPosition position)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void CreateBannerView(string adUnitId, AdSize adSize, int positionX, int positionY)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void LoadAd(AdRequest request)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void ShowBannerView()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void HideBannerView()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void DestroyBannerView()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void CreateInterstitialAd(string adUnitId)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public bool IsLoaded()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
return true;
}
public void ShowInterstitial()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void DestroyInterstitial()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void CreateRewardBasedVideoAd()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void SetUserId(string userId)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void LoadAd(AdRequest request, string adUnitId)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void DestroyRewardBasedVideoAd()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void ShowRewardBasedVideoAd()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void CreateAdLoader(AdLoader.Builder builder)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void Load(AdRequest request)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void CreateNativeExpressAdView(string adUnitId, AdSize adSize, AdPosition position)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void CreateNativeExpressAdView(string adUnitId, AdSize adSize, int positionX, int positionY)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void SetAdSize(AdSize adSize)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void ShowNativeExpressAdView()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void HideNativeExpressAdView()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void DestroyNativeExpressAdView()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public string MediationAdapterClassName()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
return null;
}
}
}
| |
// 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.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !netstandard
using Internal.Runtime.CompilerServices;
#endif
namespace System.Buffers.Text
{
public static partial class Base64
{
/// <summary>
/// Decode the span of UTF-8 encoded text represented as base 64 into binary data.
/// If the input is not a multiple of 4, it will decode as much as it can, to the closest multiple of 4.
///
/// <param name="utf8">The input span which contains UTF-8 encoded text in base 64 that needs to be decoded.</param>
/// <param name="bytes">The output span which contains the result of the operation, i.e. the decoded binary data.</param>
/// <param name="consumed">The number of input bytes consumed during the operation. This can be used to slice the input for subsequent calls, if necessary.</param>
/// <param name="written">The number of bytes written into the output span. This can be used to slice the output for subsequent calls, if necessary.</param>
/// <param name="isFinalBlock">True (default) when the input span contains the entire data to decode.
/// Set to false only if it is known that the input span contains partial data with more data to follow.</param>
/// <returns>It returns the OperationStatus enum values:
/// - Done - on successful processing of the entire input span
/// - DestinationTooSmall - if there is not enough space in the output span to fit the decoded input
/// - NeedMoreData - only if isFinalBlock is false and the input is not a multiple of 4, otherwise the partial input would be considered as InvalidData
/// - InvalidData - if the input contains bytes outside of the expected base 64 range, or if it contains invalid/more than two padding characters,
/// or if the input is incomplete (i.e. not a multiple of 4) and isFinalBlock is true.</returns>
/// </summary>
public static OperationStatus DecodeFromUtf8(ReadOnlySpan<byte> utf8, Span<byte> bytes, out int consumed, out int written, bool isFinalBlock = true)
{
ref byte srcBytes = ref MemoryMarshal.GetReference(utf8);
ref byte destBytes = ref MemoryMarshal.GetReference(bytes);
int srcLength = utf8.Length & ~0x3; // only decode input up to the closest multiple of 4.
int destLength = bytes.Length;
int sourceIndex = 0;
int destIndex = 0;
if (utf8.Length == 0)
goto DoneExit;
ref sbyte decodingMap = ref s_decodingMap[0];
// Last bytes could have padding characters, so process them separately and treat them as valid only if isFinalBlock is true
// if isFinalBlock is false, padding characters are considered invalid
int skipLastChunk = isFinalBlock ? 4 : 0;
int maxSrcLength = 0;
if (destLength >= GetMaxDecodedFromUtf8Length(srcLength))
{
maxSrcLength = srcLength - skipLastChunk;
}
else
{
// This should never overflow since destLength here is less than int.MaxValue / 4 * 3 (i.e. 1610612733)
// Therefore, (destLength / 3) * 4 will always be less than 2147483641
maxSrcLength = (destLength / 3) * 4;
}
while (sourceIndex < maxSrcLength)
{
int result = Decode(ref Unsafe.Add(ref srcBytes, sourceIndex), ref decodingMap);
if (result < 0)
goto InvalidExit;
WriteThreeLowOrderBytes(ref Unsafe.Add(ref destBytes, destIndex), result);
destIndex += 3;
sourceIndex += 4;
}
if (maxSrcLength != srcLength - skipLastChunk)
goto DestinationSmallExit;
// If input is less than 4 bytes, srcLength == sourceIndex == 0
// If input is not a multiple of 4, sourceIndex == srcLength != 0
if (sourceIndex == srcLength)
{
if (isFinalBlock)
goto InvalidExit;
goto NeedMoreExit;
}
// if isFinalBlock is false, we will never reach this point
int i0 = Unsafe.Add(ref srcBytes, srcLength - 4);
int i1 = Unsafe.Add(ref srcBytes, srcLength - 3);
int i2 = Unsafe.Add(ref srcBytes, srcLength - 2);
int i3 = Unsafe.Add(ref srcBytes, srcLength - 1);
i0 = Unsafe.Add(ref decodingMap, i0);
i1 = Unsafe.Add(ref decodingMap, i1);
i0 <<= 18;
i1 <<= 12;
i0 |= i1;
if (i3 != EncodingPad)
{
i2 = Unsafe.Add(ref decodingMap, i2);
i3 = Unsafe.Add(ref decodingMap, i3);
i2 <<= 6;
i0 |= i3;
i0 |= i2;
if (i0 < 0)
goto InvalidExit;
if (destIndex > destLength - 3)
goto DestinationSmallExit;
WriteThreeLowOrderBytes(ref Unsafe.Add(ref destBytes, destIndex), i0);
destIndex += 3;
}
else if (i2 != EncodingPad)
{
i2 = Unsafe.Add(ref decodingMap, i2);
i2 <<= 6;
i0 |= i2;
if (i0 < 0)
goto InvalidExit;
if (destIndex > destLength - 2)
goto DestinationSmallExit;
Unsafe.Add(ref destBytes, destIndex) = (byte)(i0 >> 16);
Unsafe.Add(ref destBytes, destIndex + 1) = (byte)(i0 >> 8);
destIndex += 2;
}
else
{
if (i0 < 0)
goto InvalidExit;
if (destIndex > destLength - 1)
goto DestinationSmallExit;
Unsafe.Add(ref destBytes, destIndex) = (byte)(i0 >> 16);
destIndex += 1;
}
sourceIndex += 4;
if (srcLength != utf8.Length)
goto InvalidExit;
DoneExit:
consumed = sourceIndex;
written = destIndex;
return OperationStatus.Done;
DestinationSmallExit:
if (srcLength != utf8.Length && isFinalBlock)
goto InvalidExit; // if input is not a multiple of 4, and there is no more data, return invalid data instead
consumed = sourceIndex;
written = destIndex;
return OperationStatus.DestinationTooSmall;
NeedMoreExit:
consumed = sourceIndex;
written = destIndex;
return OperationStatus.NeedMoreData;
InvalidExit:
consumed = sourceIndex;
written = destIndex;
return OperationStatus.InvalidData;
}
/// <summary>
/// Returns the maximum length (in bytes) of the result if you were to deocde base 64 encoded text within a byte span of size "length".
/// </summary>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="length"/> is less than 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int GetMaxDecodedFromUtf8Length(int length)
{
if (length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length);
return (length >> 2) * 3;
}
/// <summary>
/// Decode the span of UTF-8 encoded text in base 64 (in-place) into binary data.
/// The decoded binary output is smaller than the text data contained in the input (the operation deflates the data).
/// If the input is not a multiple of 4, it will not decode any.
///
/// <param name="buffer">The input span which contains the base 64 text data that needs to be decoded.</param>
/// <param name="written">The number of bytes written into the buffer.</param>
/// <returns>It returns the OperationStatus enum values:
/// - Done - on successful processing of the entire input span
/// - InvalidData - if the input contains bytes outside of the expected base 64 range, or if it contains invalid/more than two padding characters,
/// or if the input is incomplete (i.e. not a multiple of 4).
/// It does not return DestinationTooSmall since that is not possible for base 64 decoding.
/// It does not return NeedMoreData since this method tramples the data in the buffer and
/// hence can only be called once with all the data in the buffer.</returns>
/// </summary>
public static OperationStatus DecodeFromUtf8InPlace(Span<byte> buffer, out int written)
{
int bufferLength = buffer.Length;
int sourceIndex = 0;
int destIndex = 0;
// only decode input if it is a multiple of 4
if (bufferLength != ((bufferLength >> 2) * 4))
goto InvalidExit;
if (bufferLength == 0)
goto DoneExit;
ref byte bufferBytes = ref MemoryMarshal.GetReference(buffer);
ref sbyte decodingMap = ref s_decodingMap[0];
while (sourceIndex < bufferLength - 4)
{
int result = Decode(ref Unsafe.Add(ref bufferBytes, sourceIndex), ref decodingMap);
if (result < 0)
goto InvalidExit;
WriteThreeLowOrderBytes(ref Unsafe.Add(ref bufferBytes, destIndex), result);
destIndex += 3;
sourceIndex += 4;
}
int i0 = Unsafe.Add(ref bufferBytes, bufferLength - 4);
int i1 = Unsafe.Add(ref bufferBytes, bufferLength - 3);
int i2 = Unsafe.Add(ref bufferBytes, bufferLength - 2);
int i3 = Unsafe.Add(ref bufferBytes, bufferLength - 1);
i0 = Unsafe.Add(ref decodingMap, i0);
i1 = Unsafe.Add(ref decodingMap, i1);
i0 <<= 18;
i1 <<= 12;
i0 |= i1;
if (i3 != EncodingPad)
{
i2 = Unsafe.Add(ref decodingMap, i2);
i3 = Unsafe.Add(ref decodingMap, i3);
i2 <<= 6;
i0 |= i3;
i0 |= i2;
if (i0 < 0)
goto InvalidExit;
WriteThreeLowOrderBytes(ref Unsafe.Add(ref bufferBytes, destIndex), i0);
destIndex += 3;
}
else if (i2 != EncodingPad)
{
i2 = Unsafe.Add(ref decodingMap, i2);
i2 <<= 6;
i0 |= i2;
if (i0 < 0)
goto InvalidExit;
Unsafe.Add(ref bufferBytes, destIndex) = (byte)(i0 >> 16);
Unsafe.Add(ref bufferBytes, destIndex + 1) = (byte)(i0 >> 8);
destIndex += 2;
}
else
{
if (i0 < 0)
goto InvalidExit;
Unsafe.Add(ref bufferBytes, destIndex) = (byte)(i0 >> 16);
destIndex += 1;
}
DoneExit:
written = destIndex;
return OperationStatus.Done;
InvalidExit:
written = destIndex;
return OperationStatus.InvalidData;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int Decode(ref byte encodedBytes, ref sbyte decodingMap)
{
int i0 = encodedBytes;
int i1 = Unsafe.Add(ref encodedBytes, 1);
int i2 = Unsafe.Add(ref encodedBytes, 2);
int i3 = Unsafe.Add(ref encodedBytes, 3);
i0 = Unsafe.Add(ref decodingMap, i0);
i1 = Unsafe.Add(ref decodingMap, i1);
i2 = Unsafe.Add(ref decodingMap, i2);
i3 = Unsafe.Add(ref decodingMap, i3);
i0 <<= 18;
i1 <<= 12;
i2 <<= 6;
i0 |= i3;
i1 |= i2;
i0 |= i1;
return i0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void WriteThreeLowOrderBytes(ref byte destination, int value)
{
destination = (byte)(value >> 16);
Unsafe.Add(ref destination, 1) = (byte)(value >> 8);
Unsafe.Add(ref destination, 2) = (byte)value;
}
// Pre-computing this table using a custom string(s_characters) and GenerateDecodingMapAndVerify (found in tests)
private static readonly sbyte[] s_decodingMap = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, //62 is placed at index 43 (for +), 63 at index 47 (for /)
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, //52-61 are placed at index 48-57 (for 0-9), 64 at index 61 (for =)
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, //0-25 are placed at index 65-90 (for A-Z)
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, //26-51 are placed at index 97-122 (for a-z)
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // Bytes over 122 ('z') are invalid and cannot be decoded
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // Hence, padding the map with 255, which indicates invalid input
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
};
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology.Forms
{
/// <summary>
/// FeatureSizeRangeControl.
/// </summary>
[DefaultEvent("SizeRangeChanged")]
public partial class FeatureSizeRangeControl : UserControl
{
#region Fields
private readonly DetailedLineSymbolDialog _lineDialog;
private readonly DetailedPointSymbolDialog _pointDialog;
private bool _ignore;
private IFeatureScheme _scheme;
private FeatureSizeRange _sizeRange;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="FeatureSizeRangeControl"/> class.
/// </summary>
public FeatureSizeRangeControl()
{
InitializeComponent();
_pointDialog = new DetailedPointSymbolDialog();
_pointDialog.ChangesApplied += PointDialogChangesApplied;
_lineDialog = new DetailedLineSymbolDialog();
_lineDialog.ChangesApplied += LineDialogChangesApplied;
}
#endregion
#region Events
/// <summary>
/// Occurs when either the sizes or the template has changed.
/// </summary>
public event EventHandler<SizeRangeEventArgs> SizeRangeChanged;
#endregion
#region Properties
/// <summary>
/// Gets or sets the point scheme to work with.
/// </summary>
public IFeatureScheme Scheme
{
get
{
return _scheme;
}
set
{
_scheme = value;
IPointScheme ps = _scheme as IPointScheme;
if (ps?.Categories.Count > 0)
{
_sizeRange.Symbolizer = ps.Categories[0].Symbolizer;
}
ILineScheme ls = _scheme as ILineScheme;
if (ls?.Categories.Count > 0)
{
_sizeRange.Symbolizer = ls.Categories[0].Symbolizer;
}
UpdateControls();
}
}
/// <summary>
/// Gets or sets the point Size Range, which controls the symbolizer,
/// as well as allowing the creation of a dynamically sized version
/// of the symbolizer.
/// </summary>
public FeatureSizeRange SizeRange
{
get
{
return _sizeRange;
}
set
{
_sizeRange = value;
UpdateControls();
}
}
#endregion
#region Methods
/// <summary>
/// Initializes this point size range control.
/// </summary>
/// <param name="args">The SizeRangeEventArgs.</param>
public void Initialize(SizeRangeEventArgs args)
{
if (_sizeRange == null) return;
_sizeRange.Start = args.StartSize;
_sizeRange.End = args.EndSize;
_sizeRange.Symbolizer = args.Template;
_sizeRange.UseSizeRange = args.UseSizeRange;
IPointSymbolizer ps = args.Template as IPointSymbolizer;
if (ps != null)
{
psvStart.Visible = true;
psvEnd.Visible = true;
lsvStart.Visible = false;
lsvEnd.Visible = false;
}
ILineSymbolizer ls = args.Template as ILineSymbolizer;
if (ls != null)
{
lsvStart.Visible = true;
lsvEnd.Visible = true;
psvStart.Visible = false;
psvEnd.Visible = false;
}
}
/// <summary>
/// Handles the inter-connectivity of the various controls and updates them all to match the latest value.
/// </summary>
public void UpdateControls()
{
if (_ignore) return;
_ignore = true;
if (_sizeRange == null)
{
_ignore = false;
return;
}
chkSizeRange.Checked = _sizeRange.UseSizeRange;
trkStart.Value = (int)_sizeRange.Start;
trkEnd.Value = (int)_sizeRange.End;
IPointSymbolizer ps = _sizeRange.Symbolizer as IPointSymbolizer;
if (ps != null)
{
Color color = ps.GetFillColor();
if (_scheme != null && _scheme.EditorSettings.UseColorRange)
{
color = _scheme.EditorSettings.StartColor;
}
if (chkSizeRange.Checked)
{
psvStart.Symbolizer = _sizeRange.GetSymbolizer(_sizeRange.Start, color) as IPointSymbolizer;
}
else
{
IPointSymbolizer sm = ps.Copy();
sm.SetFillColor(color);
psvStart.Symbolizer = sm;
}
if (_scheme != null && _scheme.EditorSettings.UseColorRange)
{
color = _scheme.EditorSettings.EndColor;
}
if (chkSizeRange.Checked)
{
psvEnd.Symbolizer = _sizeRange.GetSymbolizer(_sizeRange.End, color) as IPointSymbolizer;
}
else
{
IPointSymbolizer sm = ps.Copy();
sm.SetFillColor(color);
psvEnd.Symbolizer = sm;
}
}
ILineSymbolizer ls = _sizeRange.Symbolizer as ILineSymbolizer;
if (ls != null)
{
Color color = ls.GetFillColor();
if (_scheme != null && _scheme.EditorSettings.UseColorRange)
{
color = _scheme.EditorSettings.StartColor;
}
if (chkSizeRange.Checked)
{
lsvStart.Symbolizer = _sizeRange.GetSymbolizer(_sizeRange.Start, color) as ILineSymbolizer;
}
else
{
ILineSymbolizer sm = ls.Copy();
sm.SetFillColor(color);
lsvStart.Symbolizer = sm;
}
if (_scheme != null && _scheme.EditorSettings.UseColorRange)
{
color = _scheme.EditorSettings.EndColor;
}
if (chkSizeRange.Checked)
{
lsvEnd.Symbolizer = _sizeRange.GetSymbolizer(_sizeRange.End, color) as ILineSymbolizer;
}
else
{
ILineSymbolizer sm = ls.Copy();
sm.SetFillColor(color);
lsvEnd.Symbolizer = sm;
}
}
nudStart.Value = (decimal)_sizeRange.Start;
nudEnd.Value = (decimal)_sizeRange.End;
_ignore = false;
OnSizeRangeChanged();
}
/// <summary>
/// Fires the SizeRangeChanged event args.
/// </summary>
protected virtual void OnSizeRangeChanged()
{
SizeRangeChanged?.Invoke(this, new SizeRangeEventArgs(_sizeRange));
}
private void LineDialogChangesApplied(object sender, EventArgs e)
{
if (_sizeRange == null) return;
_sizeRange.Symbolizer = _lineDialog.Symbolizer;
UpdateControls();
}
private void PointDialogChangesApplied(object sender, EventArgs e)
{
if (_sizeRange == null) return;
_sizeRange.Symbolizer = _pointDialog.Symbolizer;
UpdateControls();
}
private void BtnEditClick(object sender, EventArgs e)
{
if (_sizeRange == null) return;
IPointSymbolizer ps = _sizeRange.Symbolizer as IPointSymbolizer;
if (ps != null)
{
_pointDialog.Symbolizer = ps;
_pointDialog.ShowDialog(this);
}
ILineSymbolizer ls = _sizeRange.Symbolizer as ILineSymbolizer;
if (ls != null)
{
_lineDialog.Symbolizer = ls;
_lineDialog.ShowDialog(this);
}
}
private void ChkSizeRangeCheckedChanged(object sender, EventArgs e)
{
if (_sizeRange == null) return;
_sizeRange.UseSizeRange = chkSizeRange.Checked;
UpdateControls();
}
private void NudEndValueChanged(object sender, EventArgs e)
{
if (_sizeRange == null) return;
_sizeRange.End = (int)nudEnd.Value;
UpdateControls();
}
private void NudStartValueChanged(object sender, EventArgs e)
{
if (_sizeRange == null) return;
_sizeRange.Start = (int)nudStart.Value;
UpdateControls();
}
private void TrkEndScroll(object sender, EventArgs e)
{
if (_sizeRange == null) return;
_sizeRange.End = trkEnd.Value;
UpdateControls();
}
private void TrkStartScroll(object sender, EventArgs e)
{
if (_sizeRange == null) return;
_sizeRange.Start = trkStart.Value;
UpdateControls();
}
#endregion
}
}
| |
using System;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
namespace Org.BouncyCastle.Crypto.Modes
{
/**
* implements the GOST 28147 OFB counter mode (GCTR).
*/
public class GOfbBlockCipher
: IBlockCipher
{
private byte[] IV;
private byte[] ofbV;
private byte[] ofbOutV;
private readonly int blockSize;
private readonly IBlockCipher cipher;
bool firstStep = true;
int N3;
int N4;
const int C1 = 16843012; //00000001000000010000000100000100
const int C2 = 16843009; //00000001000000010000000100000001
/**
* Basic constructor.
*
* @param cipher the block cipher to be used as the basis of the
* counter mode (must have a 64 bit block size).
*/
public GOfbBlockCipher(
IBlockCipher cipher)
{
this.cipher = cipher;
this.blockSize = cipher.GetBlockSize();
if (blockSize != 8)
{
throw new ArgumentException("GCTR only for 64 bit block ciphers");
}
this.IV = new byte[cipher.GetBlockSize()];
this.ofbV = new byte[cipher.GetBlockSize()];
this.ofbOutV = new byte[cipher.GetBlockSize()];
}
/**
* return the underlying block cipher that we are wrapping.
*
* @return the underlying block cipher that we are wrapping.
*/
public IBlockCipher GetUnderlyingCipher()
{
return cipher;
}
/**
* Initialise the cipher and, possibly, the initialisation vector (IV).
* If an IV isn't passed as part of the parameter, the IV will be all zeros.
* An IV which is too short is handled in FIPS compliant fashion.
*
* @param encrypting if true the cipher is initialised for
* encryption, if false for decryption.
* @param parameters the key and other data required by the cipher.
* @exception ArgumentException if the parameters argument is inappropriate.
*/
public void Init(
bool forEncryption, //ignored by this CTR mode
ICipherParameters parameters)
{
firstStep = true;
N3 = 0;
N4 = 0;
if (parameters is ParametersWithIV)
{
ParametersWithIV ivParam = (ParametersWithIV)parameters;
byte[] iv = ivParam.GetIV();
if (iv.Length < IV.Length)
{
// prepend the supplied IV with zeros (per FIPS PUB 81)
Array.Copy(iv, 0, IV, IV.Length - iv.Length, iv.Length);
for (int i = 0; i < IV.Length - iv.Length; i++)
{
IV[i] = 0;
}
}
else
{
Array.Copy(iv, 0, IV, 0, IV.Length);
}
parameters = ivParam.Parameters;
}
Reset();
cipher.Init(true, parameters);
}
/**
* return the algorithm name and mode.
*
* @return the name of the underlying algorithm followed by "/GCTR"
* and the block size in bits
*/
public string AlgorithmName
{
get { return cipher.AlgorithmName + "/GCTR"; }
}
public bool IsPartialBlockOkay
{
get { return true; }
}
/**
* return the block size we are operating at (in bytes).
*
* @return the block size we are operating at (in bytes).
*/
public int GetBlockSize()
{
return blockSize;
}
/**
* Process one block of input from the array in and write it to
* the out array.
*
* @param in the array containing the input data.
* @param inOff offset into the in array the data starts at.
* @param out the array the output data will be copied into.
* @param outOff the offset into the out array the output will start at.
* @exception DataLengthException if there isn't enough data in in, or
* space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
* @return the number of bytes processed and produced.
*/
public int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
if ((inOff + blockSize) > input.Length)
{
throw new DataLengthException("input buffer too short");
}
if ((outOff + blockSize) > output.Length)
{
throw new DataLengthException("output buffer too short");
}
if (firstStep)
{
firstStep = false;
cipher.ProcessBlock(ofbV, 0, ofbOutV, 0);
N3 = bytesToint(ofbOutV, 0);
N4 = bytesToint(ofbOutV, 4);
}
N3 += C2;
N4 += C1;
intTobytes(N3, ofbV, 0);
intTobytes(N4, ofbV, 4);
cipher.ProcessBlock(ofbV, 0, ofbOutV, 0);
//
// XOR the ofbV with the plaintext producing the cipher text (and
// the next input block).
//
for (int i = 0; i < blockSize; i++)
{
output[outOff + i] = (byte)(ofbOutV[i] ^ input[inOff + i]);
}
//
// change over the input block.
//
Array.Copy(ofbV, blockSize, ofbV, 0, ofbV.Length - blockSize);
Array.Copy(ofbOutV, 0, ofbV, ofbV.Length - blockSize, blockSize);
return blockSize;
}
/**
* reset the feedback vector back to the IV and reset the underlying
* cipher.
*/
public void Reset()
{
Array.Copy(IV, 0, ofbV, 0, IV.Length);
cipher.Reset();
}
//array of bytes to type int
private int bytesToint(
byte[] inBytes,
int inOff)
{
return (int)((inBytes[inOff + 3] << 24) & 0xff000000) + ((inBytes[inOff + 2] << 16) & 0xff0000) +
((inBytes[inOff + 1] << 8) & 0xff00) + (inBytes[inOff] & 0xff);
}
//int to array of bytes
private void intTobytes(
int num,
byte[] outBytes,
int outOff)
{
outBytes[outOff + 3] = (byte)(num >> 24);
outBytes[outOff + 2] = (byte)(num >> 16);
outBytes[outOff + 1] = (byte)(num >> 8);
outBytes[outOff] = (byte)num;
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// 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 System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.Properties;
using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models;
using Newtonsoft.Json;
namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery
{
/// <summary>
/// Creates Azure Site Recovery Recovery Plan object.
/// </summary>
[Cmdlet(
VerbsData.Update,
"AzureRmRecoveryServicesAsrRecoveryPlan",
DefaultParameterSetName = ASRParameterSets.ByRPObject,
SupportsShouldProcess = true)]
[Alias("Update-ASRRecoveryPlan")]
[OutputType(typeof(ASRJob))]
public class UpdateAzureRmRecoveryServicesAsrRecoveryPlan : SiteRecoveryCmdletBase
{
/// <summary>
/// Gets or sets Name of the Recovery Plan.
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.ByRPObject,
Mandatory = true,
ValueFromPipeline = true)]
[Alias("RecoveryPlan")]
public ASRRecoveryPlan InputObject { get; set; }
/// <summary>
/// Gets or sets RP JSON FilePath.
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.ByRPFile,
Mandatory = true)]
public string Path { get; set; }
/// <summary>
/// ProcessRecord of the command.
/// </summary>
public override void ExecuteSiteRecoveryCmdlet()
{
base.ExecuteSiteRecoveryCmdlet();
if (this.ShouldProcess(
"Recovery plan",
VerbsData.Update))
{
switch (this.ParameterSetName)
{
case ASRParameterSets.ByRPObject:
this.UpdateRecoveryPlan(this.InputObject);
break;
case ASRParameterSets.ByRPFile:
if (!File.Exists(this.Path))
{
throw new FileNotFoundException(
string.Format(
Resources.FileNotFound,
this.Path));
;
}
var filePath = this.Path;
RecoveryPlan recoveryPlan = null;
using (var file = new StreamReader(filePath))
{
recoveryPlan = JsonConvert.DeserializeObject<RecoveryPlan>(
file.ReadToEnd(),
new RecoveryPlanActionDetailsConverter());
}
this.UpdateRecoveryPlan(recoveryPlan);
break;
}
}
}
/// <summary>
/// Update Recovery Plan: By powerShell Recovery Plan object
/// </summary>
private void UpdateRecoveryPlan(
ASRRecoveryPlan asrRecoveryPlan)
{
var updateRecoveryPlanInputProperties =
new UpdateRecoveryPlanInputProperties { Groups = new List<RecoveryPlanGroup>() };
foreach (var asrRecoveryPlanGroup in asrRecoveryPlan.Groups)
{
var recoveryPlanGroup = new RecoveryPlanGroup
{
GroupType = (RecoveryPlanGroupType)Enum.Parse(
typeof(RecoveryPlanGroupType),
asrRecoveryPlanGroup.GroupType),
// Initialize ReplicationProtectedItems with empty List if asrRecoveryPlanGroup.ReplicationProtectedItems is null
// otherwise assign respective values
ReplicationProtectedItems =
asrRecoveryPlanGroup.ReplicationProtectedItems == null
? new List<RecoveryPlanProtectedItem>() : asrRecoveryPlanGroup
.ReplicationProtectedItems.Select(
item =>
{
var newItem = new RecoveryPlanProtectedItem(item.Id);
string VmId = null;
if (item.Properties.ProviderSpecificDetails.GetType() ==
typeof(HyperVReplicaAzureReplicationDetails))
{
VmId = ((HyperVReplicaAzureReplicationDetails)item
.Properties.ProviderSpecificDetails).VmId;
}
else if (item.Properties.ProviderSpecificDetails
.GetType() ==
typeof(HyperVReplicaReplicationDetails))
{
VmId = ((HyperVReplicaReplicationDetails)item.Properties
.ProviderSpecificDetails).VmId;
}
else if (item.Properties.ProviderSpecificDetails
.GetType() ==
typeof(HyperVReplicaBlueReplicationDetails))
{
VmId = ((HyperVReplicaBlueReplicationDetails)item
.Properties.ProviderSpecificDetails).VmId;
}
else if (item.Properties.ProviderSpecificDetails
.GetType() ==
typeof(InMageAzureV2ReplicationDetails))
{
VmId = ((InMageAzureV2ReplicationDetails)item
.Properties.ProviderSpecificDetails).VmId;
}
else if (item.Properties.ProviderSpecificDetails
.GetType() ==
typeof(InMageReplicationDetails))
{
VmId = ((InMageReplicationDetails)item
.Properties.ProviderSpecificDetails).VmId;
}
newItem.VirtualMachineId = VmId;
return newItem;
})
.ToList(),
StartGroupActions = asrRecoveryPlanGroup.StartGroupActions,
EndGroupActions = asrRecoveryPlanGroup.EndGroupActions
};
updateRecoveryPlanInputProperties.Groups.Add(recoveryPlanGroup);
}
var updateRecoveryPlanInput =
new UpdateRecoveryPlanInput { Properties = updateRecoveryPlanInputProperties };
this.UpdateRecoveryPlan(
asrRecoveryPlan.Name,
updateRecoveryPlanInput);
}
/// <summary>
/// Update Recovery Plan: By Service object
/// </summary>
private void UpdateRecoveryPlan(
RecoveryPlan recoveryPlan)
{
var updateRecoveryPlanInputProperties =
new UpdateRecoveryPlanInputProperties { Groups = recoveryPlan.Properties.Groups };
var updateRecoveryPlanInput =
new UpdateRecoveryPlanInput { Properties = updateRecoveryPlanInputProperties };
this.UpdateRecoveryPlan(
recoveryPlan.Name,
updateRecoveryPlanInput);
}
/// <summary>
/// Update Replication Plan: Utility call
/// </summary>
private void UpdateRecoveryPlan(
string recoveryPlanName,
UpdateRecoveryPlanInput updateRecoveryPlanInput)
{
var response = this.RecoveryServicesClient.UpdateAzureSiteRecoveryRecoveryPlan(
recoveryPlanName,
updateRecoveryPlanInput);
var jobResponse = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails(
PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location));
this.WriteObject(new ASRJob(jobResponse));
}
}
}
| |
namespace TimeRecorderStatistics
{
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.Win32;
using TimeRecorderStatistics.Properties;
public class MainViewModel : Observable
{
private DateTime firstDayOfWeek;
private bool perMachine;
private bool renderSelectedOnly;
private int totalTime;
private int selectedTime;
public MainViewModel(Window w)
{
this.PreviousWeekCommand = new DelegateCommand(x => this.FirstDayOfWeek = this.FirstDayOfWeek.AddDays(-7));
this.NextWeekCommand = new DelegateCommand(x => this.FirstDayOfWeek = this.FirstDayOfWeek.AddDays(7));
this.CreateReportCommand = new DelegateCommand(x => this.CreateReport());
this.ExitCommand = new DelegateCommand(x => w.Close());
this.ClearCategoriesCommand = new DelegateCommand(
x =>
{
foreach (var c in this.Categories)
{
c.IsChecked = false;
}
});
this.Week = new ObservableCollection<Statistics>();
this.Header = Statistics.RenderHeader();
this.Machines = new ObservableCollection<CheckableItem>();
this.Categories = new ObservableCollection<CheckableItem>();
TimeRecorder.TimeRecorder.InitializeFolders(Settings.Default.DatabaseRootFolder);
var folders = TimeRecorder.TimeRecorder.RootFolder;
foreach (var folder in folders.Split(';'))
{
foreach (var dir in Directory.GetDirectories(folder))
{
this.Machines.Add(new CheckableItem(this.MachineChanged) { Header = Path.GetFileName(dir) });
}
}
this.Categories.Add(new CheckableItem(this.CategoryChanged) { Header = "Unknown" });
foreach (var cat in TimeRecorder.TimeRecorder.LoadCategories())
{
this.Categories.Add(new CheckableItem(this.CategoryChanged) { Header = Path.GetFileName(cat) });
}
var today = DateTime.Now.Date;
this.FirstDayOfWeek = today.FirstDayOfWeek(CultureInfo.CurrentCulture);
}
public string RootFolders
{
get
{
return Settings.Default.DatabaseRootFolder;
}
set
{
Settings.Default.DatabaseRootFolder = value;
Settings.Default.Save();
}
}
public DelegateCommand ExitCommand { get; set; }
public bool PerMachine
{
get
{
return this.perMachine;
}
set
{
this.perMachine = value;
this.Refresh();
}
}
public bool RenderSelectedOnly
{
get
{
return this.renderSelectedOnly;
}
set
{
this.renderSelectedOnly = value;
this.Refresh();
}
}
public ObservableCollection<Statistics> Week { get; private set; }
public ObservableCollection<CheckableItem> Machines { get; private set; }
public ObservableCollection<CheckableItem> Categories { get; private set; }
public ICommand ClearCategoriesCommand { get; private set; }
public ICommand PreviousWeekCommand { get; private set; }
public ICommand NextWeekCommand { get; private set; }
public ICommand CreateReportCommand { get; private set; }
public ImageSource Header { get; private set; }
public DateTime FirstDayOfWeek
{
get
{
return this.firstDayOfWeek;
}
set
{
this.firstDayOfWeek = value;
this.Refresh();
}
}
public string TimeInfo
{
get
{
if (this.selectedTime == this.totalTime || this.selectedTime == 0)
{
return Statistics.ToTimeString(this.totalTime);
}
return string.Format(
"{0} / {1} ({2:0.0} %)",
Statistics.ToTimeString(this.selectedTime),
Statistics.ToTimeString(this.totalTime),
100.0 * this.selectedTime / this.totalTime);
}
}
private void Refresh()
{
this.totalTime = 0;
this.selectedTime = 0;
this.Week.Clear();
for (int i = 0; i < 7; i++)
{
this.Week.Add(this.Load(this.FirstDayOfWeek.AddDays(i)));
}
this.RaisePropertyChanged("TimeInfo");
}
private void CategoryChanged(CheckableItem category)
{
this.Refresh();
}
private void MachineChanged(CheckableItem machine)
{
this.Refresh();
}
private Statistics Load(DateTime date)
{
var categories = this.Categories.Where(c => c.IsChecked).Select(c => c.Header).ToList();
var s = new Statistics(date, categories)
{
RenderPerMachine = this.PerMachine,
RenderSelectedOnly = this.RenderSelectedOnly
};
foreach (var m in this.Machines.Where(m => m.IsChecked))
{
s.Add(m.Header);
}
this.totalTime += s.TotalTime;
this.selectedTime += s.SelectedTime;
return s;
}
private void CreateReport()
{
var dialog = new SaveFileDialog
{
Filter = "Report files (*.txt)|*.txt",
FileName = "Report.txt",
DefaultExt = ".txt"
};
if (!dialog.ShowDialog().Value)
{
return;
}
var rootFolder = TimeRecorder.TimeRecorder.RootFolder;
var categories = this.Categories.Where(c => c.IsChecked).Select(c => c.Header).ToList();
var report = new Report(categories, 8.5, 16.5);
// add logs for all machines
report.AddAll(rootFolder);
// export
report.Export(dialog.FileName);
// open the folder
Process.Start("Explorer.exe", Path.GetDirectoryName(dialog.FileName));
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Text;
using System.Globalization;
namespace System
{
// The class designed as to keep minimal the working set of Uri class.
// The idea is to stay with static helper methods and strings
internal static class IPv6AddressHelper
{
// fields
private const int NumberOfLabels = 8;
// Upper case hex, zero padded to 4 characters
private const string LegacyFormat = "{0:X4}:{1:X4}:{2:X4}:{3:X4}:{4:X4}:{5:X4}:{6:X4}:{7:X4}";
// Lower case hex, no leading zeros
private const string CanonicalNumberFormat = "{0:x}";
private const string EmbeddedIPv4Format = ":{0:d}.{1:d}.{2:d}.{3:d}";
private const char Separator = ':';
// methods
internal static string ParseCanonicalName(string str, int start, ref bool isLoopback, ref string scopeId)
{
unsafe
{
ushort* numbers = stackalloc ushort[NumberOfLabels];
// optimized zeroing of 8 shorts = 2 longs
((long*)numbers)[0] = 0L;
((long*)numbers)[1] = 0L;
isLoopback = Parse(str, numbers, start, ref scopeId);
return '[' + CreateCanonicalName(numbers) + ']';
}
}
internal unsafe static string CreateCanonicalName(ushort* numbers)
{
// RFC 5952 Sections 4 & 5 - Compressed, lower case, with possible embedded IPv4 addresses.
// Start to finish, inclusive. <-1, -1> for no compression
KeyValuePair<int, int> range = FindCompressionRange(numbers);
bool ipv4Embedded = ShouldHaveIpv4Embedded(numbers);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < NumberOfLabels; i++)
{
if (ipv4Embedded && i == (NumberOfLabels - 2))
{
// Write the remaining digits as an IPv4 address
builder.AppendFormat(CultureInfo.InvariantCulture, EmbeddedIPv4Format,
numbers[i] >> 8, numbers[i] & 0xFF, numbers[i + 1] >> 8, numbers[i + 1] & 0xFF);
break;
}
// Compression; 1::1, ::1, 1::
if (range.Key == i)
{ // Start compression, add :
builder.Append(Separator);
}
if (range.Key <= i && range.Value == (NumberOfLabels - 1))
{ // Remainder compressed; 1::
builder.Append(Separator);
break;
}
if (range.Key <= i && i <= range.Value)
{
continue; // Compressed
}
if (i != 0)
{
builder.Append(Separator);
}
builder.AppendFormat(CultureInfo.InvariantCulture, CanonicalNumberFormat, numbers[i]);
}
return builder.ToString();
}
// RFC 5952 Section 4.2.3
// Longest consecutive sequence of zero segments, minimum 2.
// On equal, first sequence wins.
// <-1, -1> for no compression.
private unsafe static KeyValuePair<int, int> FindCompressionRange(ushort* numbers)
{
int longestSequenceLength = 0;
int longestSequenceStart = -1;
int currentSequenceLength = 0;
for (int i = 0; i < NumberOfLabels; i++)
{
if (numbers[i] == 0)
{ // In a sequence
currentSequenceLength++;
if (currentSequenceLength > longestSequenceLength)
{
longestSequenceLength = currentSequenceLength;
longestSequenceStart = i - currentSequenceLength + 1;
}
}
else
{
currentSequenceLength = 0;
}
}
if (longestSequenceLength >= 2)
{
return new KeyValuePair<int, int>(longestSequenceStart,
longestSequenceStart + longestSequenceLength - 1);
}
return new KeyValuePair<int, int>(-1, -1); // No compression
}
// Returns true if the IPv6 address should be formated with an embedded IPv4 address:
// ::192.168.1.1
private unsafe static bool ShouldHaveIpv4Embedded(ushort* numbers)
{
// 0:0 : 0:0 : x:x : x.x.x.x
if (numbers[0] == 0 && numbers[1] == 0 && numbers[2] == 0 && numbers[3] == 0 && numbers[6] != 0)
{
// RFC 5952 Section 5 - 0:0 : 0:0 : 0:[0 | FFFF] : x.x.x.x
if (numbers[4] == 0 && (numbers[5] == 0 || numbers[5] == 0xFFFF))
{
return true;
}
// SIIT - 0:0 : 0:0 : FFFF:0 : x.x.x.x
else if (numbers[4] == 0xFFFF && numbers[5] == 0)
{
return true;
}
}
// ISATAP
if (numbers[4] == 0 && numbers[5] == 0x5EFE)
{
return true;
}
return false;
}
//
// InternalIsValid
//
// Determine whether a name is a valid IPv6 address. Rules are:
//
// * 8 groups of 16-bit hex numbers, separated by ':'
// * a *single* run of zeros can be compressed using the symbol '::'
// * an optional string of a ScopeID delimited by '%'
// * an optional (last) 1 or 2 character prefix length field delimited by '/'
// * the last 32 bits in an address can be represented as an IPv4 address
//
// Inputs:
// <argument> name
// Domain name field of a URI to check for pattern match with
// IPv6 address
// validateStrictAddress: if set to true, it expects strict ipv6 address. Otherwise it expects
// part of the string in ipv6 format.
//
// Outputs:
// Nothing
//
// Assumes:
// the correct name is terminated by ']' character
//
// Returns:
// true if <name> has IPv6 format/ipv6 address based on validateStrictAddress, else false
//
// Throws:
// Nothing
//
// Remarks: MUST NOT be used unless all input indexes are verified and trusted.
// start must be next to '[' position, or error is reported
unsafe private static bool InternalIsValid(char* name, int start, ref int end, bool validateStrictAddress)
{
int sequenceCount = 0;
int sequenceLength = 0;
bool haveCompressor = false;
bool haveIPv4Address = false;
bool havePrefix = false;
bool expectingNumber = true;
int lastSequence = 1;
int i;
for (i = start; i < end; ++i)
{
if (havePrefix ? (name[i] >= '0' && name[i] <= '9') : Uri.IsHexDigit(name[i]))
{
++sequenceLength;
expectingNumber = false;
}
else
{
if (sequenceLength > 4)
{
return false;
}
if (sequenceLength != 0)
{
++sequenceCount;
lastSequence = i - sequenceLength;
}
switch (name[i])
{
case '%':
while (true)
{
//accept anything in scopeID
if (++i == end)
{
// no closing ']', fail
return false;
}
if (name[i] == ']')
{
goto case ']';
}
else if (name[i] == '/')
{
goto case '/';
}
}
case ']':
start = i;
i = end;
//this will make i = end+1
continue;
case ':':
if ((i > 0) && (name[i - 1] == ':'))
{
if (haveCompressor)
{
//
// can only have one per IPv6 address
//
return false;
}
haveCompressor = true;
expectingNumber = false;
}
else
{
expectingNumber = true;
}
break;
case '/':
if (validateStrictAddress)
{
return false;
}
if ((sequenceCount == 0) || havePrefix)
{
return false;
}
havePrefix = true;
expectingNumber = true;
break;
case '.':
if (haveIPv4Address)
{
return false;
}
i = end;
if (!IPv4AddressHelper.IsValid(name, lastSequence, ref i, true, false, false))
{
return false;
}
// ipv4 address takes 2 slots in ipv6 address, one was just counted meeting the '.'
++sequenceCount;
haveIPv4Address = true;
--i; // it will be incremented back on the next loop
break;
default:
return false;
}
sequenceLength = 0;
}
}
//
// if the last token was a prefix, check number of digits
//
if (havePrefix && ((sequenceLength < 1) || (sequenceLength > 2)))
{
return false;
}
//
// these sequence counts are -1 because it is implied in end-of-sequence
//
int expectedSequenceCount = 8 + (havePrefix ? 1 : 0);
if (!expectingNumber && (sequenceLength <= 4) && (haveCompressor ? (sequenceCount < expectedSequenceCount) : (sequenceCount == expectedSequenceCount)))
{
if (i == end + 1)
{
// ']' was found
end = start + 1;
return true;
}
return false;
}
return false;
}
//
// IsValid
//
// Determine whether a name is a valid IPv6 address. Rules are:
//
// * 8 groups of 16-bit hex numbers, separated by ':'
// * a *single* run of zeros can be compressed using the symbol '::'
// * an optional string of a ScopeID delimited by '%'
// * an optional (last) 1 or 2 character prefix length field delimited by '/'
// * the last 32 bits in an address can be represented as an IPv4 address
//
// Inputs:
// <argument> name
// Domain name field of a URI to check for pattern match with
// IPv6 address
//
// Outputs:
// Nothing
//
// Assumes:
// the correct name is terminated by ']' character
//
// Returns:
// true if <name> has IPv6 format, else false
//
// Throws:
// Nothing
//
// Remarks: MUST NOT be used unless all input indexes are are verified and trusted.
// start must be next to '[' position, or error is reported
internal unsafe static bool IsValid(char* name, int start, ref int end)
{
return InternalIsValid(name, start, ref end, false);
}
//
// IsValidStrict
//
// Determine whether a name is a valid IPv6 address. Rules are:
//
// * 8 groups of 16-bit hex numbers, separated by ':'
// * a *single* run of zeros can be compressed using the symbol '::'
// * an optional string of a ScopeID delimited by '%'
// * the last 32 bits in an address can be represented as an IPv4 address
//
// Difference between IsValid() and IsValidStrict() is that IsValid() expects part of the string to
// be ipv6 address where as IsValidStrict() expects strict ipv6 address.
//
// Inputs:
// <argument> name
// IPv6 address in string format
//
// Outputs:
// Nothing
//
// Assumes:
// the correct name is terminated by ']' character
//
// Returns:
// true if <name> is IPv6 address, else false
//
// Throws:
// Nothing
//
// Remarks: MUST NOT be used unless all input indexes are verified and trusted.
// start must be next to '[' position, or error is reported
internal unsafe static bool IsValidStrict(char* name, int start, ref int end)
{
return InternalIsValid(name, start, ref end, true);
}
//
// Parse
//
// Convert this IPv6 address into a sequence of 8 16-bit numbers
//
// Inputs:
// <member> Name
// The validated IPv6 address
//
// Outputs:
// <member> numbers
// Array filled in with the numbers in the IPv6 groups
//
// <member> PrefixLength
// Set to the number after the prefix separator (/) if found
//
// Assumes:
// <Name> has been validated and contains only hex digits in groups of
// 16-bit numbers, the characters ':' and '/', and a possible IPv4
// address
//
// Returns:
// true if this is a loopback, false otherwise. There is no falure indication as the sting must be a valid one.
//
// Throws:
// Nothing
//
unsafe internal static bool Parse(string address, ushort* numbers, int start, ref string scopeId)
{
int number = 0;
int index = 0;
int compressorIndex = -1;
bool numberIsValid = true;
//This used to be a class instance member but have not been used so far
int PrefixLength = 0;
if (address[start] == '[')
{
++start;
}
for (int i = start; i < address.Length && address[i] != ']';)
{
switch (address[i])
{
case '%':
if (numberIsValid)
{
numbers[index++] = (ushort)number;
numberIsValid = false;
}
start = i;
for (++i; address[i] != ']' && address[i] != '/'; ++i)
{
;
}
scopeId = address.Substring(start, i - start);
// ignore prefix if any
for (; address[i] != ']'; ++i)
{
;
}
break;
case ':':
numbers[index++] = (ushort)number;
number = 0;
++i;
if (address[i] == ':')
{
compressorIndex = index;
++i;
}
else if ((compressorIndex < 0) && (index < 6))
{
//
// no point checking for IPv4 address if we don't
// have a compressor or we haven't seen 6 16-bit
// numbers yet
//
break;
}
//
// check to see if the upcoming number is really an IPv4
// address. If it is, convert it to 2 ushort numbers
//
for (int j = i; (address[j] != ']') &&
(address[j] != ':') &&
(address[j] != '%') &&
(address[j] != '/') &&
(j < i + 4); ++j)
{
if (address[j] == '.')
{
//
// we have an IPv4 address. Find the end of it:
// we know that since we have a valid IPv6
// address, the only things that will terminate
// the IPv4 address are the prefix delimiter '/'
// or the end-of-string (which we conveniently
// delimited with ']')
//
while ((address[j] != ']') && (address[j] != '/') && (address[j] != '%'))
{
++j;
}
number = IPv4AddressHelper.ParseHostNumber(address, i, j);
numbers[index++] = (ushort)(number >> 16);
numbers[index++] = (ushort)number;
i = j;
//
// set this to avoid adding another number to
// the array if there's a prefix
//
number = 0;
numberIsValid = false;
break;
}
}
break;
case '/':
if (numberIsValid)
{
numbers[index++] = (ushort)number;
numberIsValid = false;
}
//
// since we have a valid IPv6 address string, the prefix
// length is the last token in the string
//
for (++i; address[i] != ']'; ++i)
{
PrefixLength = PrefixLength * 10 + (address[i] - '0');
}
break;
default:
number = number * 16 + Uri.FromHex(address[i++]);
break;
}
}
//
// add number to the array if its not the prefix length or part of
// an IPv4 address that's already been handled
//
if (numberIsValid)
{
numbers[index++] = (ushort)number;
}
//
// if we had a compressor sequence ("::") then we need to expand the
// numbers array
//
if (compressorIndex > 0)
{
int toIndex = NumberOfLabels - 1;
int fromIndex = index - 1;
for (int i = index - compressorIndex; i > 0; --i)
{
numbers[toIndex--] = numbers[fromIndex];
numbers[fromIndex--] = 0;
}
}
//
// is the address loopback? Loopback is defined as one of:
//
// 0:0:0:0:0:0:0:1
// 0:0:0:0:0:0:127.0.0.1 == 0:0:0:0:0:0:7F00:0001
// 0:0:0:0:0:FFFF:127.0.0.1 == 0:0:0:0:0:FFFF:7F00:0001
//
return ((numbers[0] == 0)
&& (numbers[1] == 0)
&& (numbers[2] == 0)
&& (numbers[3] == 0)
&& (numbers[4] == 0))
&& (((numbers[5] == 0)
&& (numbers[6] == 0)
&& (numbers[7] == 1))
|| (((numbers[6] == 0x7F00)
&& (numbers[7] == 0x0001))
&& ((numbers[5] == 0)
|| (numbers[5] == 0xFFFF))));
}
}
}
| |
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using PlayFab;
using PlayFab.AuthenticationModels;
using PlayFab.MultiplayerModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
/////////////////////////////////////////
// NOTE: Before using this class you MUST set PlayFab.PlayFabSettings.TitleId and PlayFab.PlayFabSettings.DeveloperSecretKey
/////////////////////////////////////////
class PlayFabMultiplayerServerHelper
{
public static PlayFabMultiplayerServerHelper Singleton = null;
public PlayFabMultiplayerServerHelper()
{
Singleton = this;
}
/// <summary>
/// Authenticates with the PlayFab backend & obtains an entity token for the title.
/// </summary>
/// <returns>
/// Boolean representing whether the call was successful or not
/// </returns>
public async Task<bool> GetTitleEntityToken()
{
// Reset our entity token
m_EntityToken = String.Empty;
var key = new PlayFab.AuthenticationModels.EntityKey();
key.Id = PlayFab.PlayFabSettings.TitleId;
var tokenRequest = new GetEntityTokenRequest();
tokenRequest.Entity = key;
// Get an entity token from the PF backend using our title ID
PlayFabResult<GetEntityTokenResponse> taskResult = await PlayFab.PlayFabAuthenticationAPI.GetEntityTokenAsync(tokenRequest);
// Check the response for an error
bool hasError = CheckForError(taskResult);
if (!hasError)
{
m_EntityToken = taskResult.Result.EntityToken;
}
else
{
m_EntityToken = String.Empty;
}
return !hasError;
}
/// <summary>
/// Checks that the title is enabled (provisioned) for PlayFab Multiplayer Servers
/// </summary>
/// <returns>
/// Boolean representing whether the call was successful or not
/// </returns>
public async Task<bool> IsTitleProvisioned()
{
PlayFabResult<GetTitleEnabledForMultiplayerServersStatusResponse> taskResult = await PlayFab.PlayFabMultiplayerAPI.GetTitleEnabledForMultiplayerServersStatusAsync(null);
bool hasError = CheckForError(taskResult);
if (!hasError)
{
return taskResult.Result.Status == TitleMultiplayerServerEnabledStatus.Enabled;
}
return !hasError;
}
/// <summary>
/// Enables PlayFab Multiplayer for the title
/// </summary>
/// <returns>
/// Boolean representing whether the call was successful or not
/// </returns>
public async Task<bool> ProvisionTitle()
{
var taskResult = await PlayFab.PlayFabMultiplayerAPI.EnableMultiplayerServersForTitleAsync(null);
bool hasError = CheckForError(taskResult);
return !hasError;
}
/// <summary>
/// Helper function which checks fora PlayFabBaseResult for an error
/// </summary>
/// <returns>
/// Boolean representing whether an error was present or not
/// </returns>
private bool CheckForError(PlayFabBaseResult result)
{
if (result.Error != null)
{
return true;
}
return false;
}
/// <summary>
/// Retrieves a list of builds
/// </summary>
/// <returns>
/// A list container of build information
/// </returns>
public async Task<List<BuildSummary>> QueryBuilds()
{
if (IsAuthenticated())
{
var task = PlayFab.PlayFabMultiplayerAPI.ListBuildSummariesAsync(null);
var resp = await task;
return resp.Result.BuildSummaries;
}
return null;
}
/// <summary>
/// Retrieves a list of multiplayer servers
/// </summary>
/// <returns>
/// A list container of running multiplayer server information
/// </returns>
public async Task<List<MultiplayerServerSummary>> QueryMultiplayerServers(string buildID, AzureRegion region)
{
// We must be authenticated to make this call
if (IsAuthenticated())
{
ListMultiplayerServersRequest request = new ListMultiplayerServersRequest();
request.BuildId = buildID;
request.Region = region;
var task = PlayFab.PlayFabMultiplayerAPI.ListMultiplayerServersAsync(request);
var resp = await task;
return resp.Result.MultiplayerServerSummaries;
}
return null;
}
/// <summary>
/// Retrieves a list of virtual machines
/// </summary>
/// <returns>
/// A list container of running VMs
/// </returns>
public async Task<List<VirtualMachineSummary>> QueryVMs(string buildID, AzureRegion region)
{
// We must be authenticated to make this call
if (IsAuthenticated())
{
ListVirtualMachineSummariesRequest request = new ListVirtualMachineSummariesRequest();
request.BuildId = buildID;
request.Region = region;
var task = PlayFab.PlayFabMultiplayerAPI.ListVirtualMachineSummariesAsync(request);
var resp = await task;
return resp.Result.VirtualMachines;
}
return null;
}
/// <summary>
/// Requests a multiplayer server from the backend.
/// This will return an existing allocated server with the same session ID if one exists. Otherwise, a new server is allocated.
/// </summary>
/// <returns>
/// Details of the server
/// </returns>
public async Task<RequestMultiplayerServerResponse> RequestMultiplayerServer(string buildID, List<AzureRegion> regions, string sessionCookie, string sessionID)
{
// We must be authenticated to make this call
if (IsAuthenticated())
{
RequestMultiplayerServerRequest request = new RequestMultiplayerServerRequest();
request.BuildId = buildID;
request.PreferredRegions = regions;
request.SessionCookie = sessionCookie;
request.SessionId = sessionID;
var task = PlayFab.PlayFabMultiplayerAPI.RequestMultiplayerServerAsync(request);
var resp = await task;
bool hasError = CheckForError(resp);
if (!hasError)
{
return resp.Result;
}
else
{
throw new Exception(String.Format("Allocate failed with error: {0}", resp.Error.ErrorMessage));
}
}
return null;
}
/// <summary>
/// Requests the shutdown of a multiplayer server
/// </summary>
/// <returns>
/// Boolean representing whether the call was successful or not
/// </returns>
public async Task<bool> ShutdownMultiplayerServer(string buildID, AzureRegion region, string sessionID)
{
if (IsAuthenticated())
{
ShutdownMultiplayerServerRequest request = new ShutdownMultiplayerServerRequest();
request.BuildId = buildID;
request.Region = region;
request.SessionId = sessionID;
var task = PlayFab.PlayFabMultiplayerAPI.ShutdownMultiplayerServerAsync(request);
var resp = await task;
bool hasError = CheckForError(resp);
if (!hasError)
{
return true;
}
else
{
throw new Exception(String.Format("Deallocate failed with error: {0}", resp.Error.ErrorMessage));
}
}
return false;
}
/// <summary>
/// Retrieves the status of a multiplay server by session ID
/// </summary>
/// <returns>
/// Status of the server
/// </returns>
public async Task<GetMultiplayerServerDetailsResponse> GetMultiplayerServerStatus(string buildID, string sessionId)
{
if (IsAuthenticated())
{
GetMultiplayerServerDetailsRequest request = new GetMultiplayerServerDetailsRequest
{
BuildId = buildID,
SessionId = sessionId
};
var task = PlayFab.PlayFabMultiplayerAPI.GetMultiplayerServerDetailsAsync(request);
var resp = await task;
bool hasError = CheckForError(resp);
if (!hasError)
{
return resp.Result;
}
else
{
throw new Exception(String.Format("GetMultiplayerServerStatus failed with error: {0}", resp.Error.ErrorMessage));
}
}
return null;
}
// This class represents the information required to connect to a server via remote desktop
public class RDPInformation
{
public string Username;
public string Password;
public string Address;
public int Port;
}
/// <summary>
/// Creates a build
/// </summary>
/// <returns>
/// Boolean representing whether the call was successful or not
/// </returns>
public async Task<bool> CreateBuild(
string strName,
ContainerFlavor containerFlavor,
List<AssetReferenceParams> lstGameAssets,
List<GameCertificateReferenceParams> lstCertificates,
List<Port> lstPorts,
Dictionary<string, string> metaData,
List<BuildRegionParams> lstRegions,
int multiplayerServerCountPerVm,
string strStartGameCommand,
AzureVmSize VMSize
)
{
// Create a build with the requested specificaitons
CreateBuildWithManagedContainerRequest createRequest = new CreateBuildWithManagedContainerRequest()
{
BuildName = strName,
ContainerFlavor = containerFlavor,
GameAssetReferences = lstGameAssets,
GameCertificateReferences = lstCertificates,
Ports = lstPorts,
Metadata = metaData,
RegionConfigurations = lstRegions,
MultiplayerServerCountPerVm = multiplayerServerCountPerVm,
StartMultiplayerServerCommand = strStartGameCommand,
VmSize = VMSize
};
var createResp = await PlayFabMultiplayerAPI.CreateBuildWithManagedContainerAsync(createRequest);
bool hasError = CheckForError(createResp);
if (hasError)
{
throw new Exception(String.Format("Create Build failed with error: {0}", createResp.Error.ErrorMessage));
}
return !hasError;
}
/// <summary>
/// Uploads a certificate to be used with build creation
/// </summary>
/// <returns>
/// Awaitable void Task
/// </returns>
public async Task UploadCertificate(string certificateLocalPath, string certificateName, string certificatePassword)
{
string base64Certificate = Convert.ToBase64String(File.ReadAllBytes(certificateLocalPath));
Certificate newCert = new Certificate() { Base64EncodedValue = base64Certificate, Name = certificateName, Password = certificatePassword };
UploadCertificateRequest uploadCertRequest = new UploadCertificateRequest() { GameCertificate = newCert };
var uploadCertResponse = await PlayFab.PlayFabMultiplayerAPI.UploadCertificateAsync(uploadCertRequest);
bool hasError = CheckForError(uploadCertResponse);
if (hasError)
{
throw new Exception(String.Format("Upload Certificate failed with error: {0}", uploadCertResponse.Error.ErrorMessage));
}
}
/// <summary>
/// Uploads an asset (e.g. a server build, or art assets/other files to be deployed onto the docker container
/// </summary>
/// <returns>
/// String representing the deployed file name
/// </returns>
public async Task<string> UploadAsset(string assetLocalPath, Dictionary<string, string> metaData)
{
metaData.Add("OriginalFilePath", assetLocalPath);
// NOTE: We append a timestamp here to provide uniqueness. Duplicate asset keys are not allowed.
Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
string assetRemoteName = String.Format("0_{0}_{1}", unixTimestamp, System.IO.Path.GetFileName(assetLocalPath));
GetAssetUploadUrlRequest assetURLRequest = new GetAssetUploadUrlRequest
{
FileName = assetRemoteName,
};
var assetURLResponse = await PlayFab.PlayFabMultiplayerAPI.GetAssetUploadUrlAsync(assetURLRequest);
bool hasError = CheckForError(assetURLResponse);
if (!hasError)
{
// parse SAS token
string sasToken = assetURLResponse.Result.AssetUploadUrl;
sasToken = sasToken.Remove(sasToken.LastIndexOf("&api"));
string storageAccountName = sasToken.Substring(8, sasToken.IndexOf("blob") - 9);
sasToken = sasToken.Substring(sasToken.IndexOf("sv"));
// Azure storage auth using SAS token
StorageCredentials accountSAS = new StorageCredentials(sasToken);
// Use these credentials and the account name to create a Blob service client.
CloudStorageAccount accountWithSAS = new CloudStorageAccount(accountSAS, storageAccountName, endpointSuffix: null, useHttps: true);
// create and upload blob
CloudBlobClient blobClient = accountWithSAS.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("gameassets");
var blob = container.GetBlockBlobReference(assetRemoteName);
blob.Properties.ContentType = "application/zip";
await blob.UploadFromFileAsync(assetLocalPath);
return assetURLResponse.Result.FileName;
}
else
{
throw new Exception(String.Format("Upload Asset failed with error: {0}", assetURLResponse.Error.ErrorMessage));
}
}
/// <summary>
/// Retrieves a list of all available assets
/// </summary>
/// <returns>
/// List of assets and their details
/// </returns>
public async Task<List<AssetSummary>> GetAllAssets()
{
var task = await PlayFabMultiplayerAPI.ListAssetSummariesAsync(null);
return task.Result.AssetSummaries;
}
/// <summary>
/// Creates an account on a VM for RDP use
/// </summary>
/// <returns>
/// RDP connection information including ip, port and credentials
/// </returns>
public async Task<RDPInformation> CreateRDPCredentials(string buildID, AzureRegion region, string VMID)
{
// Create a random username, usernames must be unique
Random rng = new Random(Environment.TickCount);
string strUsername = "RDPUser_" + rng.Next().ToString();
DateTime expirationTime = DateTime.UtcNow.AddMinutes(60);
CreateRemoteUserRequest request = new CreateRemoteUserRequest()
{
BuildId = buildID,
Region = region,
ExpirationTime = expirationTime,
VmId = VMID,
Username = strUsername,
};
// Create the user on the VM and retrieve the password generated by the backend service
var resp = await PlayFab.PlayFabMultiplayerAPI.CreateRemoteUserAsync(request);
string strPassword = resp.Result.Password;
if (!CheckForError(resp))
{
GetRemoteLoginEndpointRequest endpointRequest = new GetRemoteLoginEndpointRequest()
{
BuildId = buildID,
Region = region,
VmId = VMID,
};
// Retrieve the RDP connection details for the VM
var endpointResp = await PlayFab.PlayFabMultiplayerAPI.GetRemoteLoginEndpointAsync(endpointRequest);
RDPInformation rdpInfo = new RDPInformation
{
Username = strUsername,
Password = strPassword,
Address = endpointResp.Result.IPV4Address,
Port = endpointResp.Result.Port,
};
return rdpInfo;
}
return null;
}
/// <summary>
/// Helper function to determine if the local device is authenticated
/// </summary>
/// <returns>
/// Boolean representing whether the local device is authenticated or not
/// </returns>
public bool IsAuthenticated()
{
return m_EntityToken != String.Empty;
}
// MEMBERS
private string m_EntityToken = String.Empty;
}
| |
using System;
using System.Linq.Expressions;
using StructureMap.Building.Interception;
using StructureMap.Graph;
using StructureMap.Pipeline;
namespace StructureMap.Configuration.DSL.Expressions
{
/// <summary>
/// Expression Builder that has grammars for defining policies at the
/// PluginType level. This expression is used for registering
/// open generic types
/// </summary>
public class GenericFamilyExpression
{
private readonly Type _pluginType;
private readonly Registry _registry;
public GenericFamilyExpression(Type pluginType, ILifecycle scope, Registry registry)
{
_pluginType = pluginType;
_registry = registry;
alterAndContinue(f => { });
if (scope != null)
{
alterAndContinue(family => family.SetLifecycleTo(scope));
}
}
private GenericFamilyExpression alterAndContinue(Action<PluginFamily> action)
{
_registry.alter = graph => {
var family = graph.FindExistingOrCreateFamily(_pluginType);
action(family);
};
return this;
}
/// <summary>
/// Use this configured Instance as is
/// </summary>
/// <param name="instance"></param>
public void Use(Instance instance)
{
alterAndContinue(family => family.SetDefault(instance));
}
/// <summary>
/// Convenience method that sets the default concrete type of the PluginType. The "concreteType"
/// can only accept types that do not have any primitive constructor arguments.
/// StructureMap has to know how to construct all of the constructor argument types.
/// </summary>
/// <param name="concreteType"></param>
/// <returns></returns>
public ConfiguredInstance Use(Type concreteType)
{
var instance = new ConfiguredInstance(concreteType);
Use(instance);
return instance;
}
/// <summary>
/// Specify the "on missing named instance" configuration for this
/// PluginType
/// </summary>
/// <param name="instance"></param>
/// <returns></returns>
public GenericFamilyExpression MissingNamedInstanceIs(Instance instance)
{
alterAndContinue(family => family.MissingInstance = instance);
return this;
}
/// <summary>
/// Register an Instance constructed by a Lambda Expression using IContext
/// </summary>
/// <param name="func"></param>
/// <returns></returns>
public LambdaInstance<object> Use(Expression<Func<IContext, object>> func)
{
var instance = new LambdaInstance<object>(func);
Use(instance);
return instance;
}
/// <summary>
/// Register an Instance constructed by a Func that uses IContex
/// </summary>
/// <param name="description">User friendly diagnostic description</param>
/// <param name="func"></param>
/// <returns></returns>
public LambdaInstance<object> Use(string description, Func<IContext, object> func)
{
var instance = new LambdaInstance<object>(description, func);
Use(instance);
return instance;
}
/// <summary>
/// Adds an additional Instance constructed by a Lambda Expression using IContext
/// </summary>
/// <param name="func"></param>
/// <returns></returns>
public LambdaInstance<object> Add(Expression<Func<IContext, object>> func)
{
var instance = new LambdaInstance<object>(func);
Add(instance);
return instance;
}
/// <summary>
/// Adds an additional Instance constructed by a Func using IContext
/// </summary>
/// <param name="description">User friendly description for diagnostic purposes</param>
/// <param name="func"></param>
/// <returns></returns>
public LambdaInstance<object> Add(string description, Func<IContext, object> func)
{
var instance = new LambdaInstance<object>(description, func);
Add(instance);
return instance;
}
/// <summary>
/// Shortcut to add a value by type
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public ObjectInstance Use(object value)
{
var instance = new ObjectInstance(value);
Use(instance);
return instance;
}
/// <summary>
/// Makes a previously registered Instance with the name 'instanceKey'
/// the default Instance for this PluginType
/// </summary>
/// <param name="instanceKey"></param>
/// <returns></returns>
public ReferencedInstance Use(string instanceKey)
{
var instance = new ReferencedInstance(instanceKey);
Use(instance);
return instance;
}
/// <summary>
/// Shortcut method to add an additional Instance to this Plugin Type
/// as just a Concrete Type. This will only work if the Concrete Type
/// has no primitive constructor or mandatory Setter arguments.
/// </summary>
/// <param name="concreteType"></param>
/// <returns></returns>
public ConfiguredInstance Add(Type concreteType)
{
var instance = new ConfiguredInstance(concreteType);
alterAndContinue(family => family.AddInstance(instance));
return instance;
}
/// <summary>
/// Adds an additional Instance against this PluginType
/// </summary>
/// <param name="instance"></param>
/// <returns></returns>
public GenericFamilyExpression Add(Instance instance)
{
return alterAndContinue(family => family.AddInstance(instance));
}
/// <summary>
/// Configure this type as the supplied value
/// </summary>
/// <returns></returns>
public ObjectInstance Add(object @object)
{
var instance = new ObjectInstance(@object);
Add(instance);
return instance;
}
/// <summary>
/// Assign a lifecycle to the PluginFamily
/// </summary>
/// <param name="lifecycle"></param>
/// <returns></returns>
public GenericFamilyExpression LifecycleIs(ILifecycle lifecycle)
{
return alterAndContinue(family => family.SetLifecycleTo(lifecycle));
}
/// <summary>
/// Convenience method to mark a PluginFamily as a Singleton
/// </summary>
/// <returns></returns>
public GenericFamilyExpression Singleton()
{
return LifecycleIs(Lifecycles.Singleton);
}
/// <summary>
/// Applies a decorator type to all Instances that return a type that can be cast to this PluginType
/// </summary>
/// <param name="decoratorType"></param>
/// <param name="filter"></param>
/// <returns></returns>
public ConfiguredInstance DecorateAllWith(Type decoratorType, Func<Instance, bool> filter = null)
{
var instance = new ConfiguredInstance(decoratorType);
var policy = new DecoratorPolicy(_pluginType, instance, filter);
_registry.alter = graph => graph.Policies.Interceptors.Add(policy);
return instance;
}
/// <summary>
/// Removes any and all previously registered instance from this
/// plugin type
/// </summary>
/// <returns></returns>
public GenericFamilyExpression ClearAll()
{
alterAndContinue(family => family.RemoveAll());
return this;
}
/// <summary>
/// A general purpose method to configure the underlying
/// PluginFamily for this type
/// </summary>
/// <param name="configure"></param>
public void Configure(Action<PluginFamily> configure)
{
alterAndContinue(configure);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Schema
{
using System.IO;
using System.Text;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Versioning;
#pragma warning disable 618
internal sealed class XdrValidator : BaseValidator
{
private const int STACK_INCREMENT = 10;
private HWStack _validationStack; // validaton contexts
private Hashtable _attPresence;
private XmlQualifiedName _name = XmlQualifiedName.Empty;
private XmlNamespaceManager _nsManager;
private bool _isProcessContents = false;
private Hashtable _IDs;
private IdRefNode _idRefListHead;
private Parser _inlineSchemaParser = null;
private const string x_schema = "x-schema:";
internal XdrValidator(BaseValidator validator) : base(validator)
{
Init();
}
internal XdrValidator(XmlValidatingReaderImpl reader, XmlSchemaCollection schemaCollection, IValidationEventHandling eventHandling) : base(reader, schemaCollection, eventHandling)
{
Init();
}
private void Init()
{
_nsManager = reader.NamespaceManager;
if (_nsManager == null)
{
_nsManager = new XmlNamespaceManager(NameTable);
_isProcessContents = true;
}
_validationStack = new HWStack(STACK_INCREMENT);
textValue = new StringBuilder();
_name = XmlQualifiedName.Empty;
_attPresence = new Hashtable();
Push(XmlQualifiedName.Empty);
schemaInfo = new SchemaInfo();
checkDatatype = false;
}
public override void Validate()
{
if (IsInlineSchemaStarted)
{
ProcessInlineSchema();
}
else
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
ValidateElement();
if (reader.IsEmptyElement)
{
goto case XmlNodeType.EndElement;
}
break;
case XmlNodeType.Whitespace:
ValidateWhitespace();
break;
case XmlNodeType.Text: // text inside a node
case XmlNodeType.CDATA: // <![CDATA[...]]>
case XmlNodeType.SignificantWhitespace:
ValidateText();
break;
case XmlNodeType.EndElement:
ValidateEndElement();
break;
}
}
}
private void ValidateElement()
{
elementName.Init(reader.LocalName, XmlSchemaDatatype.XdrCanonizeUri(reader.NamespaceURI, NameTable, SchemaNames));
ValidateChildElement();
if (SchemaNames.IsXDRRoot(elementName.Name, elementName.Namespace) && reader.Depth > 0)
{
_inlineSchemaParser = new Parser(SchemaType.XDR, NameTable, SchemaNames, EventHandler);
_inlineSchemaParser.StartParsing(reader, null);
_inlineSchemaParser.ParseReaderNode();
}
else
{
ProcessElement();
}
}
private void ValidateChildElement()
{
if (context.NeedValidateChildren)
{
int errorCode = 0;
context.ElementDecl.ContentValidator.ValidateElement(elementName, context, out errorCode);
if (errorCode < 0)
{
XmlSchemaValidator.ElementValidationError(elementName, context, EventHandler, reader, reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition, null);
}
}
}
private bool IsInlineSchemaStarted
{
get { return _inlineSchemaParser != null; }
}
private void ProcessInlineSchema()
{
if (!_inlineSchemaParser.ParseReaderNode())
{ // Done
_inlineSchemaParser.FinishParsing();
SchemaInfo xdrSchema = _inlineSchemaParser.XdrSchema;
if (xdrSchema != null && xdrSchema.ErrorCount == 0)
{
foreach (string inlineNS in xdrSchema.TargetNamespaces.Keys)
{
if (!this.schemaInfo.HasSchema(inlineNS))
{
schemaInfo.Add(xdrSchema, EventHandler);
SchemaCollection.Add(inlineNS, xdrSchema, null, false);
break;
}
}
}
_inlineSchemaParser = null;
}
}
private void ProcessElement()
{
Push(elementName);
if (_isProcessContents)
{
_nsManager.PopScope();
}
context.ElementDecl = ThoroughGetElementDecl();
if (context.ElementDecl != null)
{
ValidateStartElement();
ValidateEndStartElement();
context.NeedValidateChildren = true;
context.ElementDecl.ContentValidator.InitValidation(context);
}
}
private void ValidateEndElement()
{
if (_isProcessContents)
{
_nsManager.PopScope();
}
if (context.ElementDecl != null)
{
if (context.NeedValidateChildren)
{
if (!context.ElementDecl.ContentValidator.CompleteValidation(context))
{
XmlSchemaValidator.CompleteValidationError(context, EventHandler, reader, reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition, null);
}
}
if (checkDatatype)
{
string stringValue = !hasSibling ? textString : textValue.ToString(); // only for identity-constraint exception reporting
CheckValue(stringValue, null);
checkDatatype = false;
textValue.Length = 0; // cleanup
textString = string.Empty;
}
}
Pop();
}
// SxS: This method processes resource names read from the source document and does not expose
// any resources to the caller. It is fine to suppress the SxS warning.
private SchemaElementDecl ThoroughGetElementDecl()
{
if (reader.Depth == 0)
{
LoadSchema(string.Empty);
}
if (reader.MoveToFirstAttribute())
{
do
{
string objectNs = reader.NamespaceURI;
string objectName = reader.LocalName;
if (Ref.Equal(objectNs, SchemaNames.NsXmlNs))
{
LoadSchema(reader.Value);
if (_isProcessContents)
{
_nsManager.AddNamespace(reader.Prefix.Length == 0 ? string.Empty : reader.LocalName, reader.Value);
}
}
if (
Ref.Equal(objectNs, SchemaNames.QnDtDt.Namespace) &&
Ref.Equal(objectName, SchemaNames.QnDtDt.Name)
)
{
reader.SchemaTypeObject = XmlSchemaDatatype.FromXdrName(reader.Value);
}
} while (reader.MoveToNextAttribute());
reader.MoveToElement();
}
SchemaElementDecl elementDecl = schemaInfo.GetElementDecl(elementName);
if (elementDecl == null)
{
if (schemaInfo.TargetNamespaces.ContainsKey(context.Namespace))
{
SendValidationEvent(SR.Sch_UndeclaredElement, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
}
}
return elementDecl;
}
private void ValidateStartElement()
{
if (context.ElementDecl != null)
{
if (context.ElementDecl.SchemaType != null)
{
reader.SchemaTypeObject = context.ElementDecl.SchemaType;
}
else
{
reader.SchemaTypeObject = context.ElementDecl.Datatype;
}
if (reader.IsEmptyElement && !context.IsNill && context.ElementDecl.DefaultValueTyped != null)
{
reader.TypedValueObject = context.ElementDecl.DefaultValueTyped;
context.IsNill = true; // reusing IsNill
}
if (this.context.ElementDecl.HasRequiredAttribute)
{
_attPresence.Clear();
}
}
if (reader.MoveToFirstAttribute())
{
do
{
if ((object)reader.NamespaceURI == (object)SchemaNames.NsXmlNs)
{
continue;
}
try
{
reader.SchemaTypeObject = null;
SchemaAttDef attnDef = schemaInfo.GetAttributeXdr(context.ElementDecl, QualifiedName(reader.LocalName, reader.NamespaceURI));
if (attnDef != null)
{
if (context.ElementDecl != null && context.ElementDecl.HasRequiredAttribute)
{
_attPresence.Add(attnDef.Name, attnDef);
}
reader.SchemaTypeObject = (attnDef.SchemaType != null) ? (object)attnDef.SchemaType : (object)attnDef.Datatype;
if (attnDef.Datatype != null)
{
string attributeValue = reader.Value;
// need to check the contents of this attribute to make sure
// it is valid according to the specified attribute type.
CheckValue(attributeValue, attnDef);
}
}
}
catch (XmlSchemaException e)
{
e.SetSource(reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition);
SendValidationEvent(e);
}
} while (reader.MoveToNextAttribute());
reader.MoveToElement();
}
}
private void ValidateEndStartElement()
{
if (context.ElementDecl.HasDefaultAttribute)
{
for (int i = 0; i < context.ElementDecl.DefaultAttDefs.Count; ++i)
{
reader.AddDefaultAttribute((SchemaAttDef)context.ElementDecl.DefaultAttDefs[i]);
}
}
if (context.ElementDecl.HasRequiredAttribute)
{
try
{
context.ElementDecl.CheckAttributes(_attPresence, reader.StandAlone);
}
catch (XmlSchemaException e)
{
e.SetSource(reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition);
SendValidationEvent(e);
}
}
if (context.ElementDecl.Datatype != null)
{
checkDatatype = true;
hasSibling = false;
textString = string.Empty;
textValue.Length = 0;
}
}
private void LoadSchemaFromLocation(string uri)
{
// is x-schema
if (!XdrBuilder.IsXdrSchema(uri))
{
return;
}
string url = uri.Substring(x_schema.Length);
XmlReader reader = null;
SchemaInfo xdrSchema = null;
try
{
Uri ruri = this.XmlResolver.ResolveUri(BaseUri, url);
Stream stm = (Stream)this.XmlResolver.GetEntity(ruri, null, null);
reader = new XmlTextReader(ruri.ToString(), stm, NameTable);
((XmlTextReader)reader).XmlResolver = this.XmlResolver;
Parser parser = new Parser(SchemaType.XDR, NameTable, SchemaNames, EventHandler);
parser.XmlResolver = this.XmlResolver;
parser.Parse(reader, uri);
while (reader.Read()) ;// wellformness check
xdrSchema = parser.XdrSchema;
}
catch (XmlSchemaException e)
{
SendValidationEvent(SR.Sch_CannotLoadSchema, new string[] { uri, e.Message }, XmlSeverityType.Error);
}
catch (Exception e)
{
SendValidationEvent(SR.Sch_CannotLoadSchema, new string[] { uri, e.Message }, XmlSeverityType.Warning);
}
finally
{
if (reader != null)
{
reader.Close();
}
}
if (xdrSchema != null && xdrSchema.ErrorCount == 0)
{
schemaInfo.Add(xdrSchema, EventHandler);
SchemaCollection.Add(uri, xdrSchema, null, false);
}
}
private void LoadSchema(string uri)
{
if (this.schemaInfo.TargetNamespaces.ContainsKey(uri))
{
return;
}
if (this.XmlResolver == null)
{
return;
}
SchemaInfo schemaInfo = null;
if (SchemaCollection != null)
schemaInfo = SchemaCollection.GetSchemaInfo(uri);
if (schemaInfo != null)
{
if (schemaInfo.SchemaType != SchemaType.XDR)
{
throw new XmlException(SR.Xml_MultipleValidaitonTypes, string.Empty, this.PositionInfo.LineNumber, this.PositionInfo.LinePosition);
}
this.schemaInfo.Add(schemaInfo, EventHandler);
return;
}
LoadSchemaFromLocation(uri);
}
private bool HasSchema { get { return schemaInfo.SchemaType != SchemaType.None; } }
public override bool PreserveWhitespace
{
get { return context.ElementDecl != null ? context.ElementDecl.ContentValidator.PreserveWhitespace : false; }
}
private void ProcessTokenizedType(
XmlTokenizedType ttype,
string name
)
{
switch (ttype)
{
case XmlTokenizedType.ID:
if (FindId(name) != null)
{
SendValidationEvent(SR.Sch_DupId, name);
}
else
{
AddID(name, context.LocalName);
}
break;
case XmlTokenizedType.IDREF:
object p = FindId(name);
if (p == null)
{ // add it to linked list to check it later
_idRefListHead = new IdRefNode(_idRefListHead, name, this.PositionInfo.LineNumber, this.PositionInfo.LinePosition);
}
break;
case XmlTokenizedType.ENTITY:
ProcessEntity(schemaInfo, name, this, EventHandler, reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition);
break;
default:
break;
}
}
public override void CompleteValidation()
{
if (HasSchema)
{
CheckForwardRefs();
}
else
{
SendValidationEvent(new XmlSchemaException(SR.Xml_NoValidation, string.Empty), XmlSeverityType.Warning);
}
}
private void CheckValue(
string value,
SchemaAttDef attdef
)
{
try
{
reader.TypedValueObject = null;
bool isAttn = attdef != null;
XmlSchemaDatatype dtype = isAttn ? attdef.Datatype : context.ElementDecl.Datatype;
if (dtype == null)
{
return; // no reason to check
}
if (dtype.TokenizedType != XmlTokenizedType.CDATA)
{
value = value.Trim();
}
if (value.Length == 0)
{
return; // don't need to check
}
object typedValue = dtype.ParseValue(value, NameTable, _nsManager);
reader.TypedValueObject = typedValue;
// Check special types
XmlTokenizedType ttype = dtype.TokenizedType;
if (ttype == XmlTokenizedType.ENTITY || ttype == XmlTokenizedType.ID || ttype == XmlTokenizedType.IDREF)
{
if (dtype.Variety == XmlSchemaDatatypeVariety.List)
{
string[] ss = (string[])typedValue;
for (int i = 0; i < ss.Length; ++i)
{
ProcessTokenizedType(dtype.TokenizedType, ss[i]);
}
}
else
{
ProcessTokenizedType(dtype.TokenizedType, (string)typedValue);
}
}
SchemaDeclBase decl = isAttn ? (SchemaDeclBase)attdef : (SchemaDeclBase)context.ElementDecl;
if (decl.MaxLength != uint.MaxValue)
{
if (value.Length > decl.MaxLength)
{
SendValidationEvent(SR.Sch_MaxLengthConstraintFailed, value);
}
}
if (decl.MinLength != uint.MaxValue)
{
if (value.Length < decl.MinLength)
{
SendValidationEvent(SR.Sch_MinLengthConstraintFailed, value);
}
}
if (decl.Values != null && !decl.CheckEnumeration(typedValue))
{
if (dtype.TokenizedType == XmlTokenizedType.NOTATION)
{
SendValidationEvent(SR.Sch_NotationValue, typedValue.ToString());
}
else
{
SendValidationEvent(SR.Sch_EnumerationValue, typedValue.ToString());
}
}
if (!decl.CheckValue(typedValue))
{
if (isAttn)
{
SendValidationEvent(SR.Sch_FixedAttributeValue, attdef.Name.ToString());
}
else
{
SendValidationEvent(SR.Sch_FixedElementValue, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
}
}
}
catch (XmlSchemaException)
{
if (attdef != null)
{
SendValidationEvent(SR.Sch_AttributeValueDataType, attdef.Name.ToString());
}
else
{
SendValidationEvent(SR.Sch_ElementValueDataType, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
}
}
}
public static void CheckDefaultValue(
string value,
SchemaAttDef attdef,
SchemaInfo sinfo,
XmlNamespaceManager nsManager,
XmlNameTable NameTable,
object sender,
ValidationEventHandler eventhandler,
string baseUri,
int lineNo,
int linePos
)
{
try
{
XmlSchemaDatatype dtype = attdef.Datatype;
if (dtype == null)
{
return; // no reason to check
}
if (dtype.TokenizedType != XmlTokenizedType.CDATA)
{
value = value.Trim();
}
if (value.Length == 0)
{
return; // don't need to check
}
object typedValue = dtype.ParseValue(value, NameTable, nsManager);
// Check special types
XmlTokenizedType ttype = dtype.TokenizedType;
if (ttype == XmlTokenizedType.ENTITY)
{
if (dtype.Variety == XmlSchemaDatatypeVariety.List)
{
string[] ss = (string[])typedValue;
for (int i = 0; i < ss.Length; ++i)
{
ProcessEntity(sinfo, ss[i], sender, eventhandler, baseUri, lineNo, linePos);
}
}
else
{
ProcessEntity(sinfo, (string)typedValue, sender, eventhandler, baseUri, lineNo, linePos);
}
}
else if (ttype == XmlTokenizedType.ENUMERATION)
{
if (!attdef.CheckEnumeration(typedValue))
{
XmlSchemaException e = new XmlSchemaException(SR.Sch_EnumerationValue, typedValue.ToString(), baseUri, lineNo, linePos);
if (eventhandler != null)
{
eventhandler(sender, new ValidationEventArgs(e));
}
else
{
throw e;
}
}
}
attdef.DefaultValueTyped = typedValue;
}
#if DEBUG
catch (XmlSchemaException ex) {
Debug.WriteLineIf(DiagnosticsSwitches.XmlSchema.TraceError, ex.Message);
#else
catch
{
#endif
XmlSchemaException e = new XmlSchemaException(SR.Sch_AttributeDefaultDataType, attdef.Name.ToString(), baseUri, lineNo, linePos);
if (eventhandler != null)
{
eventhandler(sender, new ValidationEventArgs(e));
}
else
{
throw e;
}
}
}
internal void AddID(string name, object node)
{
// Note: It used to be true that we only called this if _fValidate was true,
// but due to the fact that you can now dynamically type somethign as an ID
// that is no longer true.
if (_IDs == null)
{
_IDs = new Hashtable();
}
_IDs.Add(name, node);
}
public override object FindId(string name)
{
return _IDs == null ? null : _IDs[name];
}
private void Push(XmlQualifiedName elementName)
{
context = (ValidationState)_validationStack.Push();
if (context == null)
{
context = new ValidationState();
_validationStack.AddToTop(context);
}
context.LocalName = elementName.Name;
context.Namespace = elementName.Namespace;
context.HasMatched = false;
context.IsNill = false;
context.NeedValidateChildren = false;
}
private void Pop()
{
if (_validationStack.Length > 1)
{
_validationStack.Pop();
context = (ValidationState)_validationStack.Peek();
}
}
private void CheckForwardRefs()
{
IdRefNode next = _idRefListHead;
while (next != null)
{
if (FindId(next.Id) == null)
{
SendValidationEvent(new XmlSchemaException(SR.Sch_UndeclaredId, next.Id, reader.BaseURI, next.LineNo, next.LinePos));
}
IdRefNode ptr = next.Next;
next.Next = null; // unhook each object so it is cleaned up by Garbage Collector
next = ptr;
}
// not needed any more.
_idRefListHead = null;
}
private XmlQualifiedName QualifiedName(string name, string ns)
{
return new XmlQualifiedName(name, XmlSchemaDatatype.XdrCanonizeUri(ns, NameTable, SchemaNames));
}
};
#pragma warning restore 618
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Communications;
using OpenSim.Services.Interfaces;
using OpenSim.Server.Base;
using OpenMetaverse;
namespace OpenSim.Services.Connectors
{
public class XInventoryServicesConnector : IInventoryService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_ServerURI = String.Empty;
private object m_Lock = new object();
public XInventoryServicesConnector()
{
}
public XInventoryServicesConnector(string serverURI)
{
m_ServerURI = serverURI.TrimEnd('/');
}
public XInventoryServicesConnector(IConfigSource source)
{
Initialise(source);
}
public virtual void Initialise(IConfigSource source)
{
IConfig assetConfig = source.Configs["InventoryService"];
if (assetConfig == null)
{
m_log.Error("[INVENTORY CONNECTOR]: InventoryService missing from OpenSim.ini");
throw new Exception("Inventory connector init error");
}
string serviceURI = assetConfig.GetString("InventoryServerURI",
String.Empty);
if (serviceURI == String.Empty)
{
m_log.Error("[INVENTORY CONNECTOR]: No Server URI named in section InventoryService");
throw new Exception("Inventory connector init error");
}
m_ServerURI = serviceURI;
}
private bool CheckReturn(Dictionary<string, object> ret)
{
if (ret == null)
return false;
if (ret.Count == 0)
return false;
if (ret.ContainsKey("RESULT"))
{
if (ret["RESULT"] is string)
{
bool result;
if (bool.TryParse((string)ret["RESULT"], out result))
return result;
return false;
}
}
return true;
}
public bool CreateUserInventory(UUID principalID)
{
Dictionary<string,object> ret = MakeRequest("CREATEUSERINVENTORY",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() }
});
return CheckReturn(ret);
}
public List<InventoryFolderBase> GetInventorySkeleton(UUID principalID)
{
Dictionary<string,object> ret = MakeRequest("GETINVENTORYSKELETON",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() }
});
if (!CheckReturn(ret))
return null;
Dictionary<string, object> folders = (Dictionary<string, object>)ret["FOLDERS"];
List<InventoryFolderBase> fldrs = new List<InventoryFolderBase>();
try
{
foreach (Object o in folders.Values)
fldrs.Add(BuildFolder((Dictionary<string, object>)o));
}
catch (Exception e)
{
m_log.Error("[XINVENTORY SERVICES CONNECTOR]: Exception unwrapping folder list: ", e);
}
return fldrs;
}
public InventoryFolderBase GetRootFolder(UUID principalID)
{
Dictionary<string,object> ret = MakeRequest("GETROOTFOLDER",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() }
});
if (!CheckReturn(ret))
return null;
return BuildFolder((Dictionary<string, object>)ret["folder"]);
}
public InventoryFolderBase GetFolderForType(UUID principalID, AssetType type)
{
Dictionary<string,object> ret = MakeRequest("GETFOLDERFORTYPE",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() },
{ "TYPE", ((int)type).ToString() }
});
if (!CheckReturn(ret))
return null;
return BuildFolder((Dictionary<string, object>)ret["folder"]);
}
public InventoryCollection GetFolderContent(UUID principalID, UUID folderID)
{
InventoryCollection inventory = new InventoryCollection();
inventory.Folders = new List<InventoryFolderBase>();
inventory.Items = new List<InventoryItemBase>();
inventory.UserID = principalID;
try
{
Dictionary<string,object> ret = MakeRequest("GETFOLDERCONTENT",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() },
{ "FOLDER", folderID.ToString() }
});
if (!CheckReturn(ret))
return null;
Dictionary<string,object> folders =
(Dictionary<string,object>)ret["FOLDERS"];
Dictionary<string,object> items =
(Dictionary<string,object>)ret["ITEMS"];
foreach (Object o in folders.Values) // getting the values directly, we don't care about the keys folder_i
inventory.Folders.Add(BuildFolder((Dictionary<string, object>)o));
foreach (Object o in items.Values) // getting the values directly, we don't care about the keys item_i
inventory.Items.Add(BuildItem((Dictionary<string, object>)o));
}
catch (Exception e)
{
m_log.WarnFormat("[XINVENTORY SERVICES CONNECTOR]: Exception in GetFolderContent: {0}", e.Message);
}
return inventory;
}
public List<InventoryItemBase> GetFolderItems(UUID principalID, UUID folderID)
{
Dictionary<string,object> ret = MakeRequest("GETFOLDERITEMS",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() },
{ "FOLDER", folderID.ToString() }
});
if (!CheckReturn(ret))
return null;
Dictionary<string, object> items = (Dictionary<string, object>)ret["ITEMS"];
List<InventoryItemBase> fitems = new List<InventoryItemBase>();
foreach (Object o in items.Values) // getting the values directly, we don't care about the keys item_i
fitems.Add(BuildItem((Dictionary<string, object>)o));
return fitems;
}
public bool AddFolder(InventoryFolderBase folder)
{
Dictionary<string,object> ret = MakeRequest("ADDFOLDER",
new Dictionary<string,object> {
{ "ParentID", folder.ParentID.ToString() },
{ "Type", folder.Type.ToString() },
{ "Version", folder.Version.ToString() },
{ "Name", folder.Name.ToString() },
{ "Owner", folder.Owner.ToString() },
{ "ID", folder.ID.ToString() }
});
return CheckReturn(ret);
}
public bool UpdateFolder(InventoryFolderBase folder)
{
Dictionary<string,object> ret = MakeRequest("UPDATEFOLDER",
new Dictionary<string,object> {
{ "ParentID", folder.ParentID.ToString() },
{ "Type", folder.Type.ToString() },
{ "Version", folder.Version.ToString() },
{ "Name", folder.Name.ToString() },
{ "Owner", folder.Owner.ToString() },
{ "ID", folder.ID.ToString() }
});
return CheckReturn(ret);
}
public bool MoveFolder(InventoryFolderBase folder)
{
Dictionary<string,object> ret = MakeRequest("MOVEFOLDER",
new Dictionary<string,object> {
{ "ParentID", folder.ParentID.ToString() },
{ "ID", folder.ID.ToString() },
{ "PRINCIPAL", folder.Owner.ToString() }
});
return CheckReturn(ret);
}
public bool DeleteFolders(UUID principalID, List<UUID> folderIDs)
{
List<string> slist = new List<string>();
foreach (UUID f in folderIDs)
slist.Add(f.ToString());
Dictionary<string,object> ret = MakeRequest("DELETEFOLDERS",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() },
{ "FOLDERS", slist }
});
return CheckReturn(ret);
}
public bool PurgeFolder(InventoryFolderBase folder)
{
Dictionary<string,object> ret = MakeRequest("PURGEFOLDER",
new Dictionary<string,object> {
{ "ID", folder.ID.ToString() }
});
return CheckReturn(ret);
}
public bool AddItem(InventoryItemBase item)
{
if (item.CreatorData == null)
item.CreatorData = String.Empty;
Dictionary<string,object> ret = MakeRequest("ADDITEM",
new Dictionary<string,object> {
{ "AssetID", item.AssetID.ToString() },
{ "AssetType", item.AssetType.ToString() },
{ "Name", item.Name.ToString() },
{ "Owner", item.Owner.ToString() },
{ "ID", item.ID.ToString() },
{ "InvType", item.InvType.ToString() },
{ "Folder", item.Folder.ToString() },
{ "CreatorId", item.CreatorId.ToString() },
{ "CreatorData", item.CreatorData.ToString() },
{ "Description", item.Description.ToString() },
{ "NextPermissions", item.NextPermissions.ToString() },
{ "CurrentPermissions", item.CurrentPermissions.ToString() },
{ "BasePermissions", item.BasePermissions.ToString() },
{ "EveryOnePermissions", item.EveryOnePermissions.ToString() },
{ "GroupPermissions", item.GroupPermissions.ToString() },
{ "GroupID", item.GroupID.ToString() },
{ "GroupOwned", item.GroupOwned.ToString() },
{ "SalePrice", item.SalePrice.ToString() },
{ "SaleType", item.SaleType.ToString() },
{ "Flags", item.Flags.ToString() },
{ "CreationDate", item.CreationDate.ToString() }
});
return CheckReturn(ret);
}
public bool UpdateItem(InventoryItemBase item)
{
if (item.CreatorData == null)
item.CreatorData = String.Empty;
Dictionary<string,object> ret = MakeRequest("UPDATEITEM",
new Dictionary<string,object> {
{ "AssetID", item.AssetID.ToString() },
{ "AssetType", item.AssetType.ToString() },
{ "Name", item.Name.ToString() },
{ "Owner", item.Owner.ToString() },
{ "ID", item.ID.ToString() },
{ "InvType", item.InvType.ToString() },
{ "Folder", item.Folder.ToString() },
{ "CreatorId", item.CreatorId.ToString() },
{ "CreatorData", item.CreatorData.ToString() },
{ "Description", item.Description.ToString() },
{ "NextPermissions", item.NextPermissions.ToString() },
{ "CurrentPermissions", item.CurrentPermissions.ToString() },
{ "BasePermissions", item.BasePermissions.ToString() },
{ "EveryOnePermissions", item.EveryOnePermissions.ToString() },
{ "GroupPermissions", item.GroupPermissions.ToString() },
{ "GroupID", item.GroupID.ToString() },
{ "GroupOwned", item.GroupOwned.ToString() },
{ "SalePrice", item.SalePrice.ToString() },
{ "SaleType", item.SaleType.ToString() },
{ "Flags", item.Flags.ToString() },
{ "CreationDate", item.CreationDate.ToString() }
});
return CheckReturn(ret);
}
public bool MoveItems(UUID principalID, List<InventoryItemBase> items)
{
List<string> idlist = new List<string>();
List<string> destlist = new List<string>();
foreach (InventoryItemBase item in items)
{
idlist.Add(item.ID.ToString());
destlist.Add(item.Folder.ToString());
}
Dictionary<string,object> ret = MakeRequest("MOVEITEMS",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() },
{ "IDLIST", idlist },
{ "DESTLIST", destlist }
});
return CheckReturn(ret);
}
public bool DeleteItems(UUID principalID, List<UUID> itemIDs)
{
List<string> slist = new List<string>();
foreach (UUID f in itemIDs)
slist.Add(f.ToString());
Dictionary<string,object> ret = MakeRequest("DELETEITEMS",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() },
{ "ITEMS", slist }
});
return CheckReturn(ret);
}
public InventoryItemBase GetItem(InventoryItemBase item)
{
try
{
Dictionary<string, object> ret = MakeRequest("GETITEM",
new Dictionary<string, object> {
{ "ID", item.ID.ToString() }
});
if (!CheckReturn(ret))
return null;
return BuildItem((Dictionary<string, object>)ret["item"]);
}
catch (Exception e)
{
m_log.Error("[XINVENTORY SERVICES CONNECTOR]: Exception in GetItem: ", e);
}
return null;
}
public InventoryFolderBase GetFolder(InventoryFolderBase folder)
{
try
{
Dictionary<string, object> ret = MakeRequest("GETFOLDER",
new Dictionary<string, object> {
{ "ID", folder.ID.ToString() }
});
if (!CheckReturn(ret))
return null;
return BuildFolder((Dictionary<string, object>)ret["folder"]);
}
catch (Exception e)
{
m_log.Error("[XINVENTORY SERVICES CONNECTOR]: Exception in GetFolder: ", e);
}
return null;
}
public List<InventoryItemBase> GetActiveGestures(UUID principalID)
{
Dictionary<string,object> ret = MakeRequest("GETACTIVEGESTURES",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() }
});
if (!CheckReturn(ret))
return null;
List<InventoryItemBase> items = new List<InventoryItemBase>();
foreach (Object o in ((Dictionary<string,object>)ret["ITEMS"]).Values)
items.Add(BuildItem((Dictionary<string, object>)o));
return items;
}
public bool HasInventoryForUser(UUID principalID)
{
return false;
}
// Helpers
//
private Dictionary<string,object> MakeRequest(string method,
Dictionary<string,object> sendData)
{
// Add "METHOD" as the first key in the dictionary. This ensures that it will be
// visible even when using partial logging ("debug http all 5").
Dictionary<string, object> temp = sendData;
sendData = new Dictionary<string,object>{ { "METHOD", method } };
foreach (KeyValuePair<string, object> kvp in temp)
sendData.Add(kvp.Key, kvp.Value);
string reply = string.Empty;
//lock (m_Lock)
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/xinventory",
ServerUtils.BuildQueryString(sendData));
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(
reply);
return replyData;
}
private InventoryFolderBase BuildFolder(Dictionary<string,object> data)
{
InventoryFolderBase folder = new InventoryFolderBase();
try
{
folder.ParentID = new UUID(data["ParentID"].ToString());
folder.Type = short.Parse(data["Type"].ToString());
folder.Version = ushort.Parse(data["Version"].ToString());
folder.Name = data["Name"].ToString();
folder.Owner = new UUID(data["Owner"].ToString());
folder.ID = new UUID(data["ID"].ToString());
}
catch (Exception e)
{
m_log.Error("[XINVENTORY SERVICES CONNECTOR]: Exception building folder: ", e);
}
return folder;
}
private InventoryItemBase BuildItem(Dictionary<string,object> data)
{
InventoryItemBase item = new InventoryItemBase();
try
{
item.AssetID = new UUID(data["AssetID"].ToString());
item.AssetType = int.Parse(data["AssetType"].ToString());
item.Name = data["Name"].ToString();
item.Owner = new UUID(data["Owner"].ToString());
item.ID = new UUID(data["ID"].ToString());
item.InvType = int.Parse(data["InvType"].ToString());
item.Folder = new UUID(data["Folder"].ToString());
item.CreatorId = data["CreatorId"].ToString();
if (data.ContainsKey("CreatorData"))
item.CreatorData = data["CreatorData"].ToString();
else
item.CreatorData = String.Empty;
item.Description = data["Description"].ToString();
item.NextPermissions = uint.Parse(data["NextPermissions"].ToString());
item.CurrentPermissions = uint.Parse(data["CurrentPermissions"].ToString());
item.BasePermissions = uint.Parse(data["BasePermissions"].ToString());
item.EveryOnePermissions = uint.Parse(data["EveryOnePermissions"].ToString());
item.GroupPermissions = uint.Parse(data["GroupPermissions"].ToString());
item.GroupID = new UUID(data["GroupID"].ToString());
item.GroupOwned = bool.Parse(data["GroupOwned"].ToString());
item.SalePrice = int.Parse(data["SalePrice"].ToString());
item.SaleType = byte.Parse(data["SaleType"].ToString());
item.Flags = uint.Parse(data["Flags"].ToString());
item.CreationDate = int.Parse(data["CreationDate"].ToString());
}
catch (Exception e)
{
m_log.Error("[XINVENTORY CONNECTOR]: Exception building item: ", e);
}
return item;
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// * Neither the name of Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
namespace Controls
{
partial class NumberPad
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component 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.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.btnPound = new System.Windows.Forms.Button();
this.btn0 = new System.Windows.Forms.Button();
this.btnStar = new System.Windows.Forms.Button();
this.btn9 = new System.Windows.Forms.Button();
this.btn8 = new System.Windows.Forms.Button();
this.btn7 = new System.Windows.Forms.Button();
this.btn6 = new System.Windows.Forms.Button();
this.btn5 = new System.Windows.Forms.Button();
this.btn4 = new System.Windows.Forms.Button();
this.btn3 = new System.Windows.Forms.Button();
this.btn2 = new System.Windows.Forms.Button();
this.btn1 = new System.Windows.Forms.Button();
this.tableLayoutPanel1.SuspendLayout();
this.SuspendLayout();
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 3;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33334F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33334F));
this.tableLayoutPanel1.Controls.Add(this.btnPound, 2, 3);
this.tableLayoutPanel1.Controls.Add(this.btn0, 1, 3);
this.tableLayoutPanel1.Controls.Add(this.btnStar, 0, 3);
this.tableLayoutPanel1.Controls.Add(this.btn9, 2, 2);
this.tableLayoutPanel1.Controls.Add(this.btn8, 1, 2);
this.tableLayoutPanel1.Controls.Add(this.btn7, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.btn6, 2, 1);
this.tableLayoutPanel1.Controls.Add(this.btn5, 1, 1);
this.tableLayoutPanel1.Controls.Add(this.btn4, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.btn3, 2, 0);
this.tableLayoutPanel1.Controls.Add(this.btn2, 1, 0);
this.tableLayoutPanel1.Controls.Add(this.btn1, 0, 0);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 4;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 25F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 25F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 25F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 25F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(466, 352);
this.tableLayoutPanel1.TabIndex = 0;
//
// btnPound
//
this.btnPound.Dock = System.Windows.Forms.DockStyle.Fill;
this.btnPound.Location = new System.Drawing.Point(313, 267);
this.btnPound.Name = "btnPound";
this.btnPound.Size = new System.Drawing.Size(150, 82);
this.btnPound.TabIndex = 12;
this.btnPound.Tag = "#";
this.btnPound.Text = "#";
this.btnPound.UseVisualStyleBackColor = true;
this.btnPound.Click += new System.EventHandler(this.btn_Click);
//
// btn0
//
this.btn0.Dock = System.Windows.Forms.DockStyle.Fill;
this.btn0.Location = new System.Drawing.Point(158, 267);
this.btn0.Name = "btn0";
this.btn0.Size = new System.Drawing.Size(149, 82);
this.btn0.TabIndex = 11;
this.btn0.Tag = "0";
this.btn0.Text = "0";
this.btn0.UseVisualStyleBackColor = true;
this.btn0.Click += new System.EventHandler(this.btn_Click);
//
// btnStar
//
this.btnStar.Dock = System.Windows.Forms.DockStyle.Fill;
this.btnStar.Location = new System.Drawing.Point(3, 267);
this.btnStar.Name = "btnStar";
this.btnStar.Size = new System.Drawing.Size(149, 82);
this.btnStar.TabIndex = 10;
this.btnStar.Tag = "*";
this.btnStar.Text = "*";
this.btnStar.UseVisualStyleBackColor = true;
this.btnStar.Click += new System.EventHandler(this.btn_Click);
//
// btn9
//
this.btn9.Dock = System.Windows.Forms.DockStyle.Fill;
this.btn9.Location = new System.Drawing.Point(313, 179);
this.btn9.Name = "btn9";
this.btn9.Size = new System.Drawing.Size(150, 82);
this.btn9.TabIndex = 9;
this.btn9.Tag = "9";
this.btn9.Text = "9";
this.btn9.UseVisualStyleBackColor = true;
this.btn9.Click += new System.EventHandler(this.btn_Click);
//
// btn8
//
this.btn8.Dock = System.Windows.Forms.DockStyle.Fill;
this.btn8.Location = new System.Drawing.Point(158, 179);
this.btn8.Name = "btn8";
this.btn8.Size = new System.Drawing.Size(149, 82);
this.btn8.TabIndex = 8;
this.btn8.Tag = "8";
this.btn8.Text = "8";
this.btn8.UseVisualStyleBackColor = true;
this.btn8.Click += new System.EventHandler(this.btn_Click);
//
// btn7
//
this.btn7.Dock = System.Windows.Forms.DockStyle.Fill;
this.btn7.Location = new System.Drawing.Point(3, 179);
this.btn7.Name = "btn7";
this.btn7.Size = new System.Drawing.Size(149, 82);
this.btn7.TabIndex = 7;
this.btn7.Tag = "7";
this.btn7.Text = "7";
this.btn7.UseVisualStyleBackColor = true;
this.btn7.Click += new System.EventHandler(this.btn_Click);
//
// btn6
//
this.btn6.Dock = System.Windows.Forms.DockStyle.Fill;
this.btn6.Location = new System.Drawing.Point(313, 91);
this.btn6.Name = "btn6";
this.btn6.Size = new System.Drawing.Size(150, 82);
this.btn6.TabIndex = 6;
this.btn6.Tag = "6";
this.btn6.Text = "6";
this.btn6.UseVisualStyleBackColor = true;
this.btn6.Click += new System.EventHandler(this.btn_Click);
//
// btn5
//
this.btn5.Dock = System.Windows.Forms.DockStyle.Fill;
this.btn5.Location = new System.Drawing.Point(158, 91);
this.btn5.Name = "btn5";
this.btn5.Size = new System.Drawing.Size(149, 82);
this.btn5.TabIndex = 5;
this.btn5.Tag = "5";
this.btn5.Text = "5";
this.btn5.UseVisualStyleBackColor = true;
this.btn5.Click += new System.EventHandler(this.btn_Click);
//
// btn4
//
this.btn4.Dock = System.Windows.Forms.DockStyle.Fill;
this.btn4.Location = new System.Drawing.Point(3, 91);
this.btn4.Name = "btn4";
this.btn4.Size = new System.Drawing.Size(149, 82);
this.btn4.TabIndex = 4;
this.btn4.Tag = "4";
this.btn4.Text = "4";
this.btn4.UseVisualStyleBackColor = true;
this.btn4.Click += new System.EventHandler(this.btn_Click);
//
// btn3
//
this.btn3.Dock = System.Windows.Forms.DockStyle.Fill;
this.btn3.Location = new System.Drawing.Point(313, 3);
this.btn3.Name = "btn3";
this.btn3.Size = new System.Drawing.Size(150, 82);
this.btn3.TabIndex = 3;
this.btn3.Tag = "3";
this.btn3.Text = "3";
this.btn3.UseVisualStyleBackColor = true;
this.btn3.Click += new System.EventHandler(this.btn_Click);
//
// btn2
//
this.btn2.Dock = System.Windows.Forms.DockStyle.Fill;
this.btn2.Location = new System.Drawing.Point(158, 3);
this.btn2.Name = "btn2";
this.btn2.Size = new System.Drawing.Size(149, 82);
this.btn2.TabIndex = 2;
this.btn2.Tag = "2";
this.btn2.Text = "2";
this.btn2.UseVisualStyleBackColor = true;
this.btn2.Click += new System.EventHandler(this.btn_Click);
//
// btn1
//
this.btn1.Dock = System.Windows.Forms.DockStyle.Fill;
this.btn1.Location = new System.Drawing.Point(3, 3);
this.btn1.Name = "btn1";
this.btn1.Size = new System.Drawing.Size(149, 82);
this.btn1.TabIndex = 0;
this.btn1.Tag = "1";
this.btn1.Text = "1";
this.btn1.UseVisualStyleBackColor = true;
this.btn1.Click += new System.EventHandler(this.btn_Click);
//
// NumberPad
//
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "NumberPad";
this.Size = new System.Drawing.Size(466, 352);
this.tableLayoutPanel1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Button btnPound;
private System.Windows.Forms.Button btn0;
private System.Windows.Forms.Button btnStar;
private System.Windows.Forms.Button btn9;
private System.Windows.Forms.Button btn8;
private System.Windows.Forms.Button btn7;
private System.Windows.Forms.Button btn6;
private System.Windows.Forms.Button btn5;
private System.Windows.Forms.Button btn4;
private System.Windows.Forms.Button btn3;
private System.Windows.Forms.Button btn2;
private System.Windows.Forms.Button btn1;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.