context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Xunit;
using Xunit.Sdk;
namespace System.Diagnostics
{
/// <summary>Base class used for all tests that need to spawn a remote process.</summary>
public abstract partial class RemoteExecutorTestBase : FileCleanupTestBase
{
/// <summary>A timeout (milliseconds) after which a wait on a remote operation should be considered a failure.</summary>
public const int FailWaitTimeoutMilliseconds = 60 * 1000;
/// <summary>The exit code returned when the test process exits successfully.</summary>
public const int SuccessExitCode = 42;
/// <summary>The name of the test console app.</summary>
protected static readonly string TestConsoleApp = Path.GetFullPath("RemoteExecutorConsoleApp.exe");
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Action method,
RemoteInvokeOptions options = null)
{
// There's no exit code to check
options = options ?? new RemoteInvokeOptions();
options.CheckExitCode = false;
return RemoteInvoke(GetMethodInfo(method), Array.Empty<string>(), options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Action<string> method,
string arg,
RemoteInvokeOptions options = null)
{
// There's no exit code to check
options = options ?? new RemoteInvokeOptions();
options.CheckExitCode = false;
return RemoteInvoke(GetMethodInfo(method), new[] { arg }, options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Action<string, string> method,
string arg1,
string arg2,
RemoteInvokeOptions options = null)
{
// There's no exit code to check
options = options ?? new RemoteInvokeOptions();
options.CheckExitCode = false;
return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2 }, options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Action<string, string, string> method,
string arg1,
string arg2,
string arg3,
RemoteInvokeOptions options = null)
{
// There's no exit code to check
options = options ?? new RemoteInvokeOptions();
options.CheckExitCode = false;
return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3 }, options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Action<string, string, string, string> method,
string arg1,
string arg2,
string arg3,
string arg4,
RemoteInvokeOptions options = null)
{
// There's no exit code to check
options = options ?? new RemoteInvokeOptions();
options.CheckExitCode = false;
return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3, arg4 }, options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Func<int> method,
RemoteInvokeOptions options = null)
{
return RemoteInvoke(GetMethodInfo(method), Array.Empty<string>(), options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Func<Task<int>> method,
RemoteInvokeOptions options = null)
{
return RemoteInvoke(GetMethodInfo(method), Array.Empty<string>(), options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="arg">The argument to pass to the method.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Func<string, Task<int>> method,
string arg,
RemoteInvokeOptions options = null)
{
return RemoteInvoke(GetMethodInfo(method), new[] { arg }, options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="arg1">The first argument to pass to the method.</param>
/// <param name="arg2">The second argument to pass to the method.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Func<string, string, Task<int>> method,
string arg1, string arg2,
RemoteInvokeOptions options = null)
{
return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2 }, options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="arg1">The first argument to pass to the method.</param>
/// <param name="arg2">The second argument to pass to the method.</param>
/// <param name="arg3">The third argument to pass to the method.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Func<string, string, string, Task<int>> method,
string arg1, string arg2, string arg3,
RemoteInvokeOptions options = null)
{
return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3 }, options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="arg">The argument to pass to the method.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Func<string, int> method,
string arg,
RemoteInvokeOptions options = null)
{
return RemoteInvoke(GetMethodInfo(method), new[] { arg }, options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="arg1">The first argument to pass to the method.</param>
/// <param name="arg2">The second argument to pass to the method.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Func<string, string, int> method,
string arg1, string arg2,
RemoteInvokeOptions options = null)
{
return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2 }, options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="arg1">The first argument to pass to the method.</param>
/// <param name="arg2">The second argument to pass to the method.</param>
/// <param name="arg3">The third argument to pass to the method.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Func<string, string, string, int> method,
string arg1, string arg2, string arg3,
RemoteInvokeOptions options = null)
{
return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3 }, options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="arg1">The first argument to pass to the method.</param>
/// <param name="arg2">The second argument to pass to the method.</param>
/// <param name="arg3">The third argument to pass to the method.</param>
/// <param name="arg4">The fourth argument to pass to the method.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Func<string, string, string, string, int> method,
string arg1, string arg2, string arg3, string arg4,
RemoteInvokeOptions options = null)
{
return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3, arg4 }, options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="arg1">The first argument to pass to the method.</param>
/// <param name="arg2">The second argument to pass to the method.</param>
/// <param name="arg3">The third argument to pass to the method.</param>
/// <param name="arg4">The fourth argument to pass to the method.</param>
/// <param name="arg5">The fifth argument to pass to the method.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Func<string, string, string, string, string, int> method,
string arg1, string arg2, string arg3, string arg4, string arg5,
RemoteInvokeOptions options = null)
{
return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3, arg4, arg5 }, options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments without performing any modifications to the arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="unparsedArg">The arguments to pass to the method.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvokeRaw(Delegate method, string unparsedArg,
RemoteInvokeOptions options = null)
{
return RemoteInvoke(GetMethodInfo(method), new[] { unparsedArg }, options, pasteArguments: false);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="args">The arguments to pass to the method.</param>
/// <param name="options">Options to use for the invocation.</param>
/// <param name="pasteArguments">true if this function should paste the arguments (e.g. surrounding with quotes); false if that responsibility is left up to the caller.</param>
private static RemoteInvokeHandle RemoteInvoke(MethodInfo method, string[] args, RemoteInvokeOptions options, bool pasteArguments = true)
{
options = options ?? new RemoteInvokeOptions();
// Verify the specified method returns an int (the exit code) or nothing,
// and that if it accepts any arguments, they're all strings.
Assert.True(method.ReturnType == typeof(void) || method.ReturnType == typeof(int) || method.ReturnType == typeof(Task<int>));
Assert.All(method.GetParameters(), pi => Assert.Equal(typeof(string), pi.ParameterType));
// And make sure it's in this assembly. This isn't critical, but it helps with deployment to know
// that the method to invoke is available because we're already running in this assembly.
Type t = method.DeclaringType;
Assembly a = t.GetTypeInfo().Assembly;
// Start the other process and return a wrapper for it to handle its lifetime and exit checking.
ProcessStartInfo psi = options.StartInfo;
psi.UseShellExecute = false;
if (!options.EnableProfiling)
{
// Profilers / code coverage tools doing coverage of the test process set environment
// variables to tell the targeted process what profiler to load. We don't want the child process
// to be profiled / have code coverage, so we remove these environment variables for that process
// before it's started.
psi.Environment.Remove("Cor_Profiler");
psi.Environment.Remove("Cor_Enable_Profiling");
psi.Environment.Remove("CoreClr_Profiler");
psi.Environment.Remove("CoreClr_Enable_Profiling");
}
// If we need the host (if it exists), use it, otherwise target the console app directly.
string metadataArgs = PasteArguments.Paste(new string[] { a.FullName, t.FullName, method.Name, options.ExceptionFile }, pasteFirstArgumentUsingArgV0Rules: false);
string passedArgs = pasteArguments ? PasteArguments.Paste(args, pasteFirstArgumentUsingArgV0Rules: false) : string.Join(" ", args);
string testConsoleAppArgs = ExtraParameter + " " + metadataArgs + " " + passedArgs;
// Uap console app is globally registered.
if (!File.Exists(HostRunner) && !PlatformDetection.IsUap)
throw new IOException($"{HostRunner} test app isn't present in the test runtime directory.");
if (options.RunAsSudo)
{
psi.FileName = "sudo";
psi.Arguments = HostRunner + " " + testConsoleAppArgs;
// Create exception file up front so there are no permission issue when RemoteInvokeHandle tries to delete it.
File.WriteAllText(options.ExceptionFile, "");
}
else
{
psi.FileName = HostRunner;
psi.Arguments = testConsoleAppArgs;
}
// Return the handle to the process, which may or not be started
return new RemoteInvokeHandle(options.Start ?
Process.Start(psi) :
new Process() { StartInfo = psi }, options,
a.FullName, t.FullName, method.Name
);
}
private static MethodInfo GetMethodInfo(Delegate d)
{
// RemoteInvoke doesn't support marshaling state on classes associated with
// the delegate supplied (often a display class of a lambda). If such fields
// are used, odd errors result, e.g. NullReferenceExceptions during the remote
// execution. Try to ward off the common cases by proactively failing early
// if it looks like such fields are needed.
if (d.Target != null)
{
// The only fields on the type should be compiler-defined (any fields of the compiler's own
// making generally include '<' and '>', as those are invalid in C# source). Note that this logic
// may need to be revised in the future as the compiler changes, as this relies on the specifics of
// actually how the compiler handles lifted fields for lambdas.
Type targetType = d.Target.GetType();
Assert.All(
targetType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fi => Assert.True(fi.Name.IndexOf('<') != -1, $"Field marshaling is not supported by {nameof(RemoteInvoke)}: {fi.Name}"));
}
return d.GetMethodInfo();
}
/// <summary>A cleanup handle to the Process created for the remote invocation.</summary>
public sealed class RemoteInvokeHandle : IDisposable
{
public RemoteInvokeHandle(Process process, RemoteInvokeOptions options, string assemblyName = null, string className = null, string methodName = null)
{
Process = process;
Options = options;
AssemblyName = assemblyName;
ClassName = className;
MethodName = methodName;
}
public int ExitCode
{
get
{
Process.WaitForExit();
return Process.ExitCode;
}
}
public Process Process { get; set; }
public RemoteInvokeOptions Options { get; private set; }
public string AssemblyName { get; private set; }
public string ClassName { get; private set; }
public string MethodName { get; private set; }
public void Dispose()
{
GC.SuppressFinalize(this); // before Dispose(true) in case the Dispose call throws
Dispose(disposing: true);
}
private void Dispose(bool disposing)
{
Assert.True(disposing, $"A test {AssemblyName}!{ClassName}.{MethodName} forgot to Dispose() the result of RemoteInvoke()");
if (Process != null)
{
// A bit unorthodox to do throwing operations in a Dispose, but by doing it here we avoid
// needing to do this in every derived test and keep each test much simpler.
try
{
Assert.True(Process.WaitForExit(Options.TimeOut),
$"Timed out after {Options.TimeOut}ms waiting for remote process {Process.Id}");
FileInfo exceptionFileInfo = new FileInfo(Options.ExceptionFile);
if (exceptionFileInfo.Exists && exceptionFileInfo.Length != 0)
{
throw new RemoteExecutionException(File.ReadAllText(Options.ExceptionFile));
}
if (Options.CheckExitCode)
{
int expected = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Options.ExpectedExitCode : unchecked((sbyte)Options.ExpectedExitCode);
int actual = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Process.ExitCode : unchecked((sbyte)Process.ExitCode);
Assert.True(expected == actual, $"Exit code was {Process.ExitCode} but it should have been {Options.ExpectedExitCode}");
}
}
finally
{
if (File.Exists(Options.ExceptionFile))
{
File.Delete(Options.ExceptionFile);
}
// Cleanup
try { Process.Kill(); }
catch { } // ignore all cleanup errors
Process.Dispose();
Process = null;
}
}
}
~RemoteInvokeHandle()
{
// Finalizer flags tests that omitted the explicit Dispose() call; they must have it, or they aren't
// waiting on the remote execution
Dispose(disposing: false);
}
private sealed class RemoteExecutionException : XunitException
{
internal RemoteExecutionException(string stackTrace) : base("Remote process failed with an unhandled exception.", stackTrace) { }
}
}
}
/// <summary>Options used with RemoteInvoke.</summary>
public sealed class RemoteInvokeOptions
{
private bool _runAsSudo;
public bool Start { get; set; } = true;
public ProcessStartInfo StartInfo { get; set; } = new ProcessStartInfo();
public bool EnableProfiling { get; set; } = true;
public bool CheckExitCode { get; set; } = true;
public int TimeOut {get; set; } = RemoteExecutorTestBase.FailWaitTimeoutMilliseconds;
public int ExpectedExitCode { get; set; } = RemoteExecutorTestBase.SuccessExitCode;
public string ExceptionFile { get; } = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
public bool RunAsSudo
{
get
{
return _runAsSudo;
}
set
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
throw new PlatformNotSupportedException();
}
_runAsSudo = value;
}
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Diagnostics;
namespace fyiReporting.RDL
{
/// <summary>
/// The PageTree object contains references to all the pages used within the Pdf.
/// All individual pages are referenced through the kids string
/// </summary>
internal class PdfPageTree:PdfBase
{
private string pageTree;
private string kids;
private int MaxPages;
internal PdfPageTree(PdfAnchor pa):base(pa)
{
kids="[ ";
MaxPages=0;
}
/// <summary>
/// Add a page to the Page Tree. ObjNum is the object number of the page to be added.
/// pageNum is the page number of the page.
/// </summary>
/// <param name="objNum"></param>
internal void AddPage(int objNum)
{
Debug.Assert(objNum >= 0 && objNum <= this.Current);
MaxPages++;
string refPage=objNum+" 0 R ";
kids=kids+refPage;
}
/// <summary>
/// returns the Page Tree Dictionary
/// </summary>
/// <returns></returns>
internal byte[] GetPageTree(long filePos,out int size)
{
pageTree=string.Format("\r\n{0} 0 obj<</Count {1}/Kids {2}]>> endobj\t",
this.objectNum,MaxPages,kids);
return this.GetUTF8Bytes(pageTree,filePos,out size);
}
}
/// <summary>
/// This class represents individual pages within the pdf.
/// The contents of the page belong to this class
/// </summary>
internal class PdfPage:PdfBase
{
private string page;
private string pageSize;
private string fontRef;
private string imageRef;
private string patternRef;
private string colorSpaceRef;
private string resourceDict,contents;
private string annotsDict;
internal PdfPage(PdfAnchor pa):base(pa)
{
resourceDict=null;
contents=null;
pageSize=null;
fontRef=null;
imageRef=null;
annotsDict=null;
colorSpaceRef=null;
patternRef=null;
}
/// <summary>
/// Create The Pdf page
/// </summary>
internal void CreatePage(int refParent,PdfPageSize pSize)
{
pageSize=string.Format("[0 0 {0} {1}]",pSize.xWidth,pSize.yHeight);
page=string.Format("\r\n{0} 0 obj<</Type /Page/Parent {1} 0 R/Rotate 0/MediaBox {2}/CropBox {2}",
this.objectNum,refParent,pageSize);
}
internal void AddHyperlink(float x, float y, float height, float width, string url)
{
if (annotsDict == null)
annotsDict = "\r/Annots [";
annotsDict += string.Format(@"<</Type /Annot /Subtype /Link /Rect [{0} {1} {2} {3}] /Border [0 0 0] /A <</S /URI /URI ({4})>>>>",
x, y, x+width, y-height, url);
}
internal void AddToolTip(float x, float y, float height, float width, string tooltip)
{
if (annotsDict == null)
annotsDict = "\r/Annots [";
annotsDict += string.Format(@"<</Type /Annot /Rect [{0} {1} {2} {3}] /Border [0 0 0] /IC [1.0 1.0 0.666656] /CA 0.00500488 /C [1.0 0.0 0.0] /Name/Comment /T(Value) /Contents({4}) /F 288 /Subtype/Square>>", /*/A <</S /URI /URI ({4})>>*/
x, y, x + width, y - height, tooltip);
}
/// <summary>
/// Add Pattern Resources to the pdf page
/// </summary>
internal void AddResource(PdfPattern patterns,int contentRef)
{
foreach (PdfPatternEntry pat in patterns.Patterns.Values)
{
patternRef+=string.Format("/{0} {1} 0 R",pat.pattern,pat.objectNum);
}
if(contentRef>0)
{
contents=string.Format("/Contents {0} 0 R",contentRef);
}
}
/// <summary>
/// Add Font Resources to the pdf page
/// </summary>
internal void AddResource(PdfFonts fonts,int contentRef)
{
foreach (PdfFontEntry font in fonts.Fonts.Values)
{
fontRef+=string.Format("/{0} {1} 0 R",font.font,font.objectNum);
}
if(contentRef>0)
{
contents=string.Format("/Contents {0} 0 R",contentRef);
}
}
internal void AddResource(PatternObj po,int contentRef)
{
colorSpaceRef=string.Format("/CS1 {0} 0 R",po.objectNum);
}
/// <summary>
/// Add Image Resources to the pdf page
/// </summary>
internal void AddResource(PdfImageEntry ie,int contentRef)
{
if (imageRef == null || imageRef.IndexOf("/"+ie.name) < 0) // only need it once per page
// imageRef+=string.Format("/XObject << /{0} {1} 0 R >>",ie.name,ie.objectNum);
imageRef+=string.Format("/{0} {1} 0 R ",ie.name,ie.objectNum);
if(contentRef>0)
{
contents=string.Format("/Contents {0} 0 R",contentRef);
}
}
/// <summary>
/// Get the Page Dictionary to be written to the file
/// </summary>
/// <returns></returns>
internal byte[] GetPageDict(long filePos,out int size)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
//will need to add pattern here
sb.AppendFormat("/Resources<<\r\n/Font<<{0}>>",fontRef);
if (patternRef != null)
sb.AppendFormat("\r\n/Pattern <<{0}>>",patternRef);
if (colorSpaceRef != null)
sb.AppendFormat("\r\n/ColorSpace <<{0}>>",colorSpaceRef);
sb.Append("\r\n/ProcSet[/PDF/Text");
if (imageRef == null)
sb.Append("]>>");
else
sb.AppendFormat("\r\n/ImageB]/XObject <<{0}>>>>",imageRef);
resourceDict = sb.ToString();
//if (imageRef == null)
// resourceDict=string.Format("/Resources<</Font<<{0}>>/ProcSet[/PDF/Text]>>",fontRef);
//else
// resourceDict=string.Format("/Resources<</Font<<{0}>>/ProcSet[/PDF/Text/ImageB]/XObject <<{1}>>>>",fontRef, imageRef);
if (annotsDict != null)
page += (annotsDict+"]\r");
page+=resourceDict+"\r\n"+contents+">>\r\nendobj\r\n";
return this.GetUTF8Bytes(page,filePos,out size);
}
}
/// <summary>
/// Specify the page size in 1/72 inches units.
/// </summary>
internal struct PdfPageSize
{
internal int xWidth;
internal int yHeight;
internal int leftMargin;
internal int rightMargin;
internal int topMargin;
internal int bottomMargin;
internal PdfPageSize(int width,int height)
{
xWidth=width;
yHeight=height;
leftMargin=0;
rightMargin=0;
topMargin=0;
bottomMargin=0;
}
internal void SetMargins(int L,int T,int R,int B)
{
leftMargin=L;
rightMargin=R;
topMargin=T;
bottomMargin=B;
}
}
}
| |
using System;
using System.ComponentModel;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security;
namespace Abc.Zerio.Interop
{
[SuppressUnmanagedCodeSecurity]
public unsafe class WinSock
{
[DllImport("WS2_32.dll", SetLastError = true, CharSet = CharSet.Ansi, BestFitMapping = true, ThrowOnUnmappableChar = true)]
internal static extern SocketError WSAStartup([In] short wVersionRequested, [Out] out WSAData lpWSAData);
[DllImport("WS2_32.dll", SetLastError = true)]
internal static extern int WSACleanup();
[DllImport("WS2_32.dll", SetLastError = true)]
internal static extern int WSAIoctl([In] IntPtr socket, [In] uint dwIoControlCode, [In] ref Guid lpvInBuffer, [In] uint cbInBuffer, [In, Out] ref RIO_EXTENSION_FUNCTION_TABLE lpvOutBuffer, [In] int cbOutBuffer, [Out] out uint lpcbBytesReturned, [In] IntPtr lpOverlapped, [In] IntPtr lpCompletionRoutine);
[DllImport("WS2_32.dll", SetLastError = true, EntryPoint = "WSAIoctl")]
internal static extern int WSAIoctl2([In] IntPtr socket, [In] uint dwIoControlCode, [In] ref Guid lpvInBuffer, [In] uint cbInBuffer, [In, Out] ref IntPtr lpvOutBuffer, [In] int cbOutBuffer, [Out] out uint lpcbBytesReturned, [In] IntPtr lpOverlapped, [In] IntPtr lpCompletionRoutine);
[DllImport("WS2_32.dll", SetLastError = true, EntryPoint = "WSAIoctl")]
internal static extern int WSAIoctlGeneral([In] IntPtr socket, [In] uint dwIoControlCode, [In] int* lpvInBuffer, [In] uint cbInBuffer, [In] int* lpvOutBuffer, [In] int cbOutBuffer, [Out] out uint lpcbBytesReturned, [In] IntPtr lpOverlapped, [In] IntPtr lpCompletionRoutine);
[DllImport("ws2_32.dll", EntryPoint = "WSAIoctl", SetLastError = true)]
internal static extern SocketError WSAIoctl_Blocking([In] IntPtr socketHandle, [In] int ioControlCode, [In] byte[] inBuffer, [In] int inBufferSize, [Out] byte[] outBuffer, [In] int outBufferSize, out int bytesTransferred, [In] IntPtr overlapped, [In] IntPtr completionRoutine);
[DllImport("WS2_32.dll", SetLastError = true, CharSet = CharSet.Ansi)]
internal static extern IntPtr WSASocket([In] AddressFamilies af, [In] SocketType type, [In] Protocol protocol, [In] IntPtr lpProtocolInfo, [In] int group, [In] SocketFlags dwFlags);
[DllImport("WS2_32.dll", SetLastError = true)]
internal static extern bool WSAGetOverlappedResult(IntPtr socket, [In] RioNativeOverlapped* lpOverlapped, out int lpcbTransfer, bool fWait, out int lpdwFlags);
[DllImport("WS2_32.dll", SetLastError = true)]
internal static extern IntPtr accept(IntPtr s, IntPtr addr, IntPtr addrlen);
[DllImport("WS2_32.dll", SetLastError = false)]
internal static extern int connect([In] IntPtr s, [In] ref SockaddrIn name, [In] int namelen);
[DllImport("WS2_32.dll", SetLastError = true, CharSet = CharSet.Ansi)]
internal static extern int bind(IntPtr s, ref SockaddrIn name, int namelen);
[DllImport("WS2_32.dll", SetLastError = true)]
internal static extern int listen(IntPtr s, int backlog);
[DllImport("WS2_32.dll", SetLastError = true)]
internal static extern int closesocket(IntPtr s);
[DllImport("WS2_32.dll", SetLastError = true)]
internal static extern int setsockopt(IntPtr s, int level, int optname, char* optval, int optlen);
[DllImport("WS2_32.dll", SetLastError = true)]
internal static extern int getsockopt(IntPtr s, int level, int optname, char* optval, int* optlen);
[DllImport("WS2_32.dll", SetLastError = true)]
internal static extern ushort htons([In] ushort hostshort);
[DllImport("WS2_32.dll", SetLastError = true)]
internal static extern ushort ntohs([In] ushort netshort);
[DllImport("WS2_32.dll", SetLastError = true)]
internal static extern ulong htonl([In] ulong hostshort);
[DllImport("WS2_32.dll", SetLastError = true)]
internal static extern SocketError getsockname([In] IntPtr s, [Out] byte* socketAddress, [In, Out] ref int socketAddressSize);
[DllImport("WS2_32.dll")]
internal static extern int WSAGetLastError();
public static class Extensions
{
internal static RIORegisterBufferFunc RegisterBuffer;
internal static RIOCreateCompletionQueueFunc CreateCompletionQueue;
internal static RIOCreateRequestQueueFunc CreateRequestQueue;
internal static RIOReceiveFunc Receive;
internal static RIOSendFunc Send;
internal static RIONotifyFunc Notify;
internal static RIOCloseCompletionQueueAction CloseCompletionQueue;
internal static RIODequeueCompletionFunc DequeueCompletion;
internal static RIODeregisterBufferAction DeregisterBuffer;
internal static RIOResizeCompletionQueueFunc ResizeCompletionQueue;
internal static RIOResizeRequestQueueFunc ResizeRequestQueue;
internal static AcceptExFunc AcceptEx;
internal static ConnectExFunc ConnectEx;
internal static DisconnectExFunc DisconnectEx;
[UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true), SuppressUnmanagedCodeSecurity]
internal delegate IntPtr RIORegisterBufferFunc([In] IntPtr DataBuffer, [In] uint DataLength);
[UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true), SuppressUnmanagedCodeSecurity]
internal delegate void RIODeregisterBufferAction([In] IntPtr BufferId);
[UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = false), SuppressUnmanagedCodeSecurity]
internal delegate bool RIOSendFunc([In] IntPtr SocketQueue, RIO_BUF* RioBuffer, [In] uint DataBufferCount, [In] RIO_SEND_FLAGS Flags, [In] long RequestCorrelation);
[UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = false), SuppressUnmanagedCodeSecurity]
internal delegate bool RIOReceiveFunc([In] IntPtr SocketQueue, RIO_BUF* RioBuffer, [In] uint DataBufferCount, [In] RIO_RECEIVE_FLAGS Flags, [In] long RequestCorrelation);
[UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true), SuppressUnmanagedCodeSecurity]
internal delegate CompletionQueueHandle RIOCreateCompletionQueueFunc([In] uint QueueSize, [In, Optional] RIO_NOTIFICATION_COMPLETION* NotificationCompletion);
[UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true), SuppressUnmanagedCodeSecurity]
internal delegate void RIOCloseCompletionQueueAction([In] IntPtr CQ);
[UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true), SuppressUnmanagedCodeSecurity]
internal delegate IntPtr RIOCreateRequestQueueFunc([In] IntPtr Socket, [In] uint MaxOutstandingReceive, [In] uint MaxReceiveDataBuffers, [In] uint MaxOutstandingSend, [In] uint MaxSendDataBuffers, [In] CompletionQueueHandle ReceiveCQ, [In] CompletionQueueHandle SendCQ, [In] int ConnectionCorrelation);
[UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = false), SuppressUnmanagedCodeSecurity]
internal delegate uint RIODequeueCompletionFunc([In] IntPtr CQ, [In] RIO_RESULT* ResultArray, [In] uint ResultArrayLength);
[UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = false), SuppressUnmanagedCodeSecurity]
internal delegate int RIONotifyFunc([In] IntPtr CQ);
[UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true), SuppressUnmanagedCodeSecurity]
internal delegate bool RIOResizeCompletionQueueFunc([In] IntPtr CQ, [In] uint QueueSize);
[UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true), SuppressUnmanagedCodeSecurity]
internal delegate bool RIOResizeRequestQueueFunc([In] IntPtr RQ, [In] uint MaxOutstandingReceive, [In] uint MaxOutstandingSend);
[UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = false), SuppressUnmanagedCodeSecurity]
internal delegate bool AcceptExFunc([In] IntPtr sListenSocket, [In] IntPtr sAcceptSocket, [In] IntPtr lpOutputBuffer, [In] int dwReceiveDataLength, [In] int dwLocalAddressLength, [In] int dwRemoteAddressLength, [Out] out int lpdwBytesReceived, [In] RioNativeOverlapped* lpOverlapped);
[UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = false), SuppressUnmanagedCodeSecurity]
internal delegate bool ConnectExFunc([In] IntPtr s, [In] SockaddrIn name, [In] int namelen, [In] IntPtr lpSendBuffer, [In] uint dwSendDataLength, [Out] out uint lpdwBytesSent, [In] RioNativeOverlapped* lpOverlapped);
[UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = false), SuppressUnmanagedCodeSecurity]
internal delegate bool DisconnectExFunc([In] IntPtr hSocket, [In] RioNativeOverlapped* lpOverlapped, [In] uint dwFlags, [In] uint reserved);
}
private static readonly object _lock = new object();
private static bool _initialized;
private static Exception _initializationException;
public static void EnsureIsInitialized()
{
if (!Environment.Is64BitProcess)
throw new InvalidOperationException("32 bit processes are not supported");
lock (_lock)
{
if (!_initialized)
{
Initialize();
_initialized = true;
}
}
if (_initializationException != null)
throw new InvalidOperationException("Unable to initialize WinSock", _initializationException);
}
private static void Initialize()
{
var version = new Version(2, 2);
WSAData data;
var result = WSAStartup((short)version.Raw, out data);
if (result != 0 && CaptureInitializationWsaError())
return;
var tempSocket = WSASocket(AddressFamilies.AF_INET, SocketType.SOCK_STREAM, Protocol.IPPROTO_TCP, IntPtr.Zero, 0, SocketFlags.WSA_FLAG_REGISTERED_IO | SocketFlags.WSA_FLAG_OVERLAPPED);
if (CaptureInitializationWsaError())
return;
uint dwBytes;
var acceptExId = new Guid("B5367DF1-CBAC-11CF-95CA-00805F48A192");
var acceptExptr = IntPtr.Zero;
var acceptExIoctlResult = WSAIoctl2(tempSocket, Consts.SIO_GET_EXTENSION_FUNCTION_POINTER, ref acceptExId, 16, ref acceptExptr, IntPtr.Size, out dwBytes, IntPtr.Zero, IntPtr.Zero);
if (acceptExIoctlResult != 0 && CaptureInitializationWsaError())
return;
Extensions.AcceptEx = Marshal.GetDelegateForFunctionPointer<Extensions.AcceptExFunc>(acceptExptr);
var connectExId = new Guid("25A207B9-DDF3-4660-8EE9-76E58C74063E");
var connectExptr = IntPtr.Zero;
var connectExIoctlResult = WSAIoctl2(tempSocket, Consts.SIO_GET_EXTENSION_FUNCTION_POINTER, ref connectExId, 16, ref connectExptr, IntPtr.Size, out dwBytes, IntPtr.Zero, IntPtr.Zero);
if (connectExIoctlResult != 0 && CaptureInitializationWsaError())
return;
Extensions.ConnectEx = Marshal.GetDelegateForFunctionPointer<Extensions.ConnectExFunc>(connectExptr);
var disconnectExId = new Guid("7FDA2E11-8630-436F-A031-F536A6EEC157");
var disconnectExptr = IntPtr.Zero;
var disconnectIoctlResult = WSAIoctl2(tempSocket, Consts.SIO_GET_EXTENSION_FUNCTION_POINTER, ref disconnectExId, 16, ref disconnectExptr, IntPtr.Size, out dwBytes, IntPtr.Zero, IntPtr.Zero);
if (disconnectIoctlResult != 0 && CaptureInitializationWsaError())
return;
Extensions.DisconnectEx = Marshal.GetDelegateForFunctionPointer<Extensions.DisconnectExFunc>(disconnectExptr);
var rio = new RIO_EXTENSION_FUNCTION_TABLE();
var rioFunctionsTableId = new Guid("8509e081-96dd-4005-b165-9e2ee8c79e3f");
var rioIoctlResult = WSAIoctl(tempSocket, Consts.SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER, ref rioFunctionsTableId, 16, ref rio, sizeof(RIO_EXTENSION_FUNCTION_TABLE), out dwBytes, IntPtr.Zero, IntPtr.Zero);
if (rioIoctlResult != 0 && CaptureInitializationWsaError())
return;
Extensions.RegisterBuffer = Marshal.GetDelegateForFunctionPointer<Extensions.RIORegisterBufferFunc>(rio.RIORegisterBuffer);
Extensions.CreateCompletionQueue = Marshal.GetDelegateForFunctionPointer<Extensions.RIOCreateCompletionQueueFunc>(rio.RIOCreateCompletionQueue);
Extensions.CreateRequestQueue = Marshal.GetDelegateForFunctionPointer<Extensions.RIOCreateRequestQueueFunc>(rio.RIOCreateRequestQueue);
Extensions.Notify = Marshal.GetDelegateForFunctionPointer<Extensions.RIONotifyFunc>(rio.RIONotify);
Extensions.DequeueCompletion = Marshal.GetDelegateForFunctionPointer<Extensions.RIODequeueCompletionFunc>(rio.RIODequeueCompletion);
Extensions.Receive = Marshal.GetDelegateForFunctionPointer<Extensions.RIOReceiveFunc>(rio.RIOReceive);
Extensions.Send = Marshal.GetDelegateForFunctionPointer<Extensions.RIOSendFunc>(rio.RIOSend);
Extensions.CloseCompletionQueue = Marshal.GetDelegateForFunctionPointer<Extensions.RIOCloseCompletionQueueAction>(rio.RIOCloseCompletionQueue);
Extensions.DeregisterBuffer = Marshal.GetDelegateForFunctionPointer<Extensions.RIODeregisterBufferAction>(rio.RIODeregisterBuffer);
Extensions.ResizeCompletionQueue = Marshal.GetDelegateForFunctionPointer<Extensions.RIOResizeCompletionQueueFunc>(rio.RIOResizeCompletionQueue);
Extensions.ResizeRequestQueue = Marshal.GetDelegateForFunctionPointer<Extensions.RIOResizeRequestQueueFunc>(rio.RIOResizeRequestQueue);
closesocket(tempSocket);
CaptureInitializationWsaError();
}
public static class Consts
{
public const int SOCKET_ERROR = -1;
public const int INVALID_SOCKET = -1;
public const int WSAEINTR = 10004;
public const int WSAENOTSOCK = 10038;
public const uint IOC_OUT = 0x40000000;
public const uint IOC_IN = 0x80000000;
public const uint IOC_INOUT = IOC_IN | IOC_OUT;
public const uint IOC_WS2 = 0x08000000;
public const uint SIO_GET_EXTENSION_FUNCTION_POINTER = IOC_INOUT | IOC_WS2 | 6;
public const uint SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER = IOC_INOUT | IOC_WS2 | 36;
public const uint SIO_LOOPBACK_FAST_PATH = IOC_IN | IOC_WS2 | 16;
public const int TCP_NODELAY = 0x0001;
public const int SO_REUSEADDR = 0x0004;
public const int IPPROTO_TCP = 6;
public const int SOL_SOCKET = 0xffff;
public const int SOMAXCONN = 0x7fffffff;
public const uint RIO_CORRUPT_CQ = 0xFFFFFFFF;
public static readonly IntPtr RIO_INVALID_BUFFERID = new IntPtr(-1);
}
internal static void ThrowLastWsaError()
{
var error = WSAGetLastError();
if (error != 0 && error != 997)
throw new Win32Exception(error);
}
private static bool CaptureInitializationWsaError()
{
var error = WSAGetLastError();
if (error != 0 && error != 997)
{
_initializationException = new Win32Exception(error);
return true;
}
return false;
}
}
}
| |
/*
* Copyright (c) 2011..., Sergei Grichine
* 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 Sergei Grichine nor the
* names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY Sergei Grichine ''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 Sergei Grichine 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.
*
* this is a X11 (BSD Revised) license - you do not have to publish your changes,
* although doing so, donating and contributing is always appreciated
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using W3C.Soap;
using Microsoft.Ccr.Core;
using Microsoft.Dss.Core.Attributes;
using Microsoft.Dss.ServiceModel.Dssp;
using Microsoft.Dss.Core.DsspHttp;
namespace TrackRoamer.Robotics.Services.TrackRoamerBrickPower
{
/// <summary>
/// TrackRoamer Power Brick Contract
/// </summary>
public sealed class Contract
{
/// The Unique Contract Identifier for the TrackRoamer Power Brick core service
public const String Identifier = "http://schemas.trackroamer.com/robotics/2009/04/trackroamerbrickpower.html";
}
/// <summary>
/// Track Roamer Bot Operations
/// </summary>
public class TrackRoamerBrickPowerOperations : PortSet<
DsspDefaultLookup,
DsspDefaultDrop,
Get,
Replace,
Subscribe,
//QueryConfig,
QueryWhiskers,
QueryMotorSpeed,
QueryMotorEncoderSpeed,
UpdateConfig,
UpdateMotorSpeed,
UpdateMotorEncoder,
UpdateMotorEncoderSpeed,
ResetMotorEncoder, // distances
SetOutputC,
UpdateWhiskers,
HttpGet,
HttpPost>
{
}
#region Data Contracts
[Description("The TrackRoamer Power Brick Power Controller (RoboteQ AX2850) Configuration State")]
[DataContract()]
public class TrackRoamerBrickPowerState
{
[Browsable(false)]
[DataMember]
public DateTime TimeStamp { get; set; }
/// <summary>
/// Is the PowerController unit currently connected.
/// </summary>
[DataMember]
[Description("Indicates that the Power Controller is connected.")]
[Browsable(false)]
public bool Connected { get; set; }
/// <summary>
/// Serial Port Configuration
/// </summary>
[DataMember(IsRequired = true)]
[Description("Specifies the serial port where the Power Controller is connected.")]
public PowerControllerConfig PowerControllerConfig { get; set; }
/// <summary>
/// PowerController measured values
/// </summary>
[DataMember(IsRequired = true)]
[Description("The TrackRoamer Power Brick Controller measured values.")]
public PowerControllerState PowerControllerState { get; set; }
[Browsable(false)]
[DataMember]
public bool Dropping { get; set; }
[Browsable(false)]
[DataMember]
public long FrameCounter { get; set; }
[Browsable(false)]
[DataMember]
public int FrameRate { get; set; }
[Browsable(false)]
[DataMember]
public long ErrorCounter { get; set; }
[Browsable(false)]
[DataMember]
public int ErrorRate { get; set; }
[Browsable(false)]
[DataMember]
public int ConnectAttempts { get; set; }
[Browsable(false)]
[DataMember]
public int? OutputC { get; set; } // 0 or 1
[Browsable(false)]
[DataMember]
public MotorSpeed MotorSpeed { get; set; }
[Browsable(false)]
[DataMember]
public Whiskers Whiskers { get; set; }
[Browsable(false)]
[DataMember]
public MotorEncoder MotorEncoder { get; set; }
[Browsable(false)]
[DataMember]
public MotorEncoderSpeed MotorEncoderSpeed { get; set; }
}
[Description("The whiskers sensors state")]
[DataContract]
public class Whiskers
{
/*
HardwareIdentifier coding:
1st digit 1=Left 2=Right
2d digit 0=Front 1=Rear
3d digit 1=Whisker 2=IRBumper 3=StepSensor
*/
[Browsable(false)]
[DataMember]
public DateTime Timestamp { get; set; }
[Browsable(false)]
[DataMember]
public bool? FrontWhiskerLeft { get; set; }
[Browsable(false)]
[DataMember]
public bool? FrontWhiskerRight { get; set; }
}
[Description("The current left and right motor speed settings")]
[DataContract]
public class MotorSpeed
{
[Browsable(false)]
[DataMember]
public DateTime Timestamp { get; set; }
[Browsable(false)]
[DataMember]
public double? LeftSpeed { get; set; }
[Browsable(false)]
[DataMember]
public double? RightSpeed { get; set; }
}
[Description("The current left or/and right motor encoder distance readings")]
[DataContract]
public class MotorEncoder
{
[Browsable(false)]
[DataMember]
public DateTime Timestamp { get; set; }
[Browsable(false)]
[DataMember]
public int? HardwareIdentifier { get; set; } // 1=Left, 2=Right matters on ResetMotorEncoder
[Browsable(false)]
[DataMember]
public double? LeftDistance { get; set; }
[Browsable(false)]
[DataMember]
public double? RightDistance { get; set; }
}
[Description("The current left or/and right motor encoder speed readings")]
[DataContract]
public class MotorEncoderSpeed
{
[Browsable(false)]
[DataMember]
public DateTime Timestamp { get; set; }
[Browsable(false)]
[DataMember]
public double? LeftSpeed { get; set; }
[Browsable(false)]
[DataMember]
public double? RightSpeed { get; set; }
}
/// <summary>
/// PowerController measured values
/// </summary>
[DataContract]
[DisplayName("(User) PowerController State")]
[Description("The TrackRoamer Power Brick Controller measured values")]
public class PowerControllerState
{
[DataMember]
[Description("Analog_Input_1")]
public double? Analog_Input_1 { get; set; }
[DataMember]
[Description("Analog_Input_2")]
public double? Analog_Input_2 { get; set; }
[DataMember]
[Description("Digital_Input_E")]
public double? Digital_Input_E { get; set; }
[DataMember]
[Description("Main_Battery_Voltage")]
public double? Main_Battery_Voltage { get; set; }
[DataMember]
[Description("Internal_Voltage")]
public double? Internal_Voltage { get; set; }
[DataMember]
[Description("Motor_Power_Left")]
public double? Motor_Power_Left { get; set; }
[DataMember]
[Description("Motor_Power_Right")]
public double? Motor_Power_Right { get; set; }
[DataMember]
[Description("Motor_Amps_Left")]
public double? Motor_Amps_Left { get; set; }
// note: Amps behave almost like integers, no precision here and low current will read as 0
[DataMember]
[Description("Motor_Amps_Right")]
public double? Motor_Amps_Right { get; set; }
[DataMember]
[Description("Heatsink_Temperature_Left")]
public double? Heatsink_Temperature_Left { get; set; }
[DataMember]
[Description("Heatsink_Temperature_Right")]
public double? Heatsink_Temperature_Right { get; set; }
}
/// <summary>
/// PowerController Serial Port Configuration
/// </summary>
[DataContract]
[DisplayName("(User) PowerController Configuration")]
[Description("The TrackRoamer Power Brick Controller Serial Port Configuration")]
public class PowerControllerConfig : ICloneable
{
/// <summary>
/// The Serial Comm Port
/// </summary>
[DataMember]
[Description("PowerController COM Port")]
public int CommPort { get; set; }
/// <summary>
/// The Serial Port Name or the File name containing PowerController readings
/// </summary>
[DataMember]
[Description("The Serial Port Name or the File name containing PowerController readings (Default blank)")]
public string PortName { get; set; }
/// <summary>
/// Baud Rate
/// </summary>
[DataMember]
[Description("PowerController Baud Rate")]
public int BaudRate { get; set; }
/// <summary>
/// Configuration Status
/// </summary>
[DataMember]
[Browsable(false)]
[Description("PowerController Configuration Status")]
public string ConfigurationStatus { get; set; }
[Description("Delay in milliseconds, sleep in the main loop of controller")]
[DataMember]
public int Delay { get; set; }
/// <summary>
/// Default Constructor
/// </summary>
public PowerControllerConfig()
{
this.BaudRate = 9600; // cannot be changed for AX2850
this.CommPort = 0;
this.PortName = string.Empty;
this.Delay = 17;
}
#region ICloneable implementation
public object Clone()
{
return new PowerControllerConfig()
{
BaudRate = this.BaudRate,
CommPort = this.CommPort,
PortName = this.PortName
};
}
#endregion // ICloneable implementation
}
#endregion
#region Operation Ports
[DisplayName("Get")]
[Description("Gets the TrackRoamer Power Brick's current state.")]
public class Get : Get<GetRequestType, PortSet<TrackRoamerBrickPowerState, Fault>>
{
}
//[DisplayName("GetConfiguration")]
//[Description("Gets the TrackRoamer Power Brick's current configuration.")]
//public class QueryConfig : Query<PowerControllerConfig, PortSet<PowerControllerConfig, Fault>>
//{
//}
[DisplayName("GetWhiskers")]
[Description("Gets the whiskers sensors' state.")]
public class QueryWhiskers : Query<Whiskers, PortSet<Whiskers, Fault>>
{
}
[DisplayName("GetMotorEncoder")]
[Description("Gets the motor encoder sensors' state - distances.")]
public class QueryMotorEncoder : Query<MotorEncoder, PortSet<MotorEncoder, Fault>>
{
}
[DisplayName("GetMotorEncoderSpeed")]
[Description("Gets the motor encoder sensors' state - speed.")]
public class QueryMotorEncoderSpeed : Query<MotorEncoderSpeed, PortSet<MotorEncoderSpeed, Fault>>
{
}
[DisplayName("GetMotorSpeed")]
[Description("Gets the motor speed.")]
public class QueryMotorSpeed : Query<MotorSpeed, PortSet<MotorSpeed, Fault>>
{
}
[DisplayName("UpdateConfiguration")]
[Description("Updates or indicates an update to the TrackRoamer Power Brick's configuration.")]
public class UpdateConfig : Update<PowerControllerConfig, PortSet<DefaultUpdateResponseType, Fault>>
{
}
[DisplayName("UpdateSpeed")]
[Description("Updates or indicates an update to motor speed.")]
public class UpdateMotorSpeed : Update<MotorSpeed, PortSet<DefaultUpdateResponseType, Fault>>
{
public UpdateMotorSpeed()
{
if (this.Body == null)
{
this.Body = new MotorSpeed();
}
}
public UpdateMotorSpeed(MotorSpeed motorSpeed)
{
this.Body = motorSpeed;
}
}
[DisplayName("SetOutputC")]
[Description("Sets Output C of the AX2850 to on or off")]
public class SetOutputC : Update<bool, PortSet<DefaultUpdateResponseType, Fault>>
{
}
[DisplayName("UpdateWhiskers")]
[Description("Updates or indicates an update to the whiskers sensors' state.")]
public class UpdateWhiskers : Update<Whiskers, PortSet<DefaultUpdateResponseType, Fault>>
{
}
[DisplayName("UpdateMotorEncoder")]
[Description("Updates or indicates an update to the motor encoders' state - distances.")]
public class UpdateMotorEncoder : Update<MotorEncoder, PortSet<DefaultUpdateResponseType, Fault>>
{
}
[DisplayName("UpdateMotorEncoderSpeed")]
[Description("Updates or indicates an update to the motor encoders' state - speeds.")]
public class UpdateMotorEncoderSpeed : Update<MotorEncoderSpeed, PortSet<DefaultUpdateResponseType, Fault>>
{
}
[DisplayName("ResetMotorEncoder")]
[Description("Resets the motor encoders' ticks (distances) to 0.")]
public class ResetMotorEncoder : Replace<MotorEncoder, PortSet<DefaultReplaceResponseType, Fault>>
{
}
[DisplayName("ChangeState")]
[Description("Changes or indicates a change to the TrackRoamer Power Brick's entire state.")]
public class Replace : Replace<TrackRoamerBrickPowerState, PortSet<DefaultReplaceResponseType, Fault>>
{
}
public class Subscribe : Subscribe<SubscribeRequestType, PortSet<SubscribeResponseType, Fault>>
{
}
/// <summary>
/// A PowerController Command
/// <remarks>Use with SendPowerControllerCommand()</remarks>
/// </summary>
[DataContract]
[Description("A PowerController Command")]
public class PowerControllerCommand
{
[DataMember]
public string Command { get; set; }
}
/// <summary>
/// standard subscribe request type
/// </summary>
[DataContract]
[Description("Standard Subscribe request")]
public class SubscribeRequest : SubscribeRequestType
{
/// <summary>
/// Which message types to subscribe to
/// </summary>
[DataMember]
public PowerControllerMessageType MessageTypes;
/// <summary>
/// Only subscribe to messages when IsValid is true
/// </summary>
[DataMember]
public bool ValidOnly;
}
/// <summary>
/// PowerController Message Type - bitwise OR for subscribing to selected types only
/// </summary>
[DataContract, Flags]
[Description("Identifies the UM6 message types bitmask for subscriptions.")]
public enum PowerControllerMessageType
{
/// <summary>
/// No-message mask
/// </summary>
None = 0,
/// <summary>
/// processed gyroscope data
/// </summary>
GYRO_PROC = 0x01,
/// <summary>
/// processed accelerometer data
/// </summary>
ACCEL_PROC = 0x02,
/// <summary>
/// processed magnitometer data
/// </summary>
MAG_PROC = 0x04,
/// <summary>
/// Euler angles (beware of 90 degrees singularity)
/// </summary>
EULER = 0x08,
/// <summary>
/// quaternion data (no singularities)
/// </summary>
QUAT = 0x10,
/// <summary>
/// Subscribe to all message types
/// </summary>
All = GYRO_PROC | ACCEL_PROC | MAG_PROC | EULER | QUAT // use "|" to combine all types here into a bitmask
}
#endregion
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Nullable.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections.Generic;
using Dot42;
using Dot42.Internal;
using Dot42.Internal.Generics;
using Java.Lang;
namespace System
{
public static class Nullable
{
public static int Compare<T>(T? n1, T? n2) where T : struct
{
if (n1.HasValue)
{
if (!n2.HasValue)
return 1;
return Comparer<T>.Default.Compare(n1.RawValue, n2.RawValue);
}
return n2.HasValue ? -1 : 0;
}
public static bool Equals<T>(T? n1, T? n2) where T : struct
{
if (n1.HasValue != n2.HasValue)
return false;
if (!n1.HasValue)
return true;
return EqualityComparer<T>.Default.Equals(n1.RawValue, n2.RawValue);
}
public static bool Equals(bool? n1, bool? n2)
{
return (n1.HasValue == n2.HasValue) && ((!n1.HasValue) || (n1.RawValue == n2.RawValue));
}
public static bool Equals(byte? n1, byte? n2)
{
return (n1.HasValue == n2.HasValue) && ((!n1.HasValue) || (n1.RawValue == n2.RawValue));
}
public static bool Equals(sbyte? n1, sbyte? n2)
{
return (n1.HasValue == n2.HasValue) && ((!n1.HasValue) || (n1.RawValue == n2.RawValue));
}
public static bool Equals(char? n1, char? n2)
{
return (n1.HasValue == n2.HasValue) && ((!n1.HasValue) || (n1.RawValue == n2.RawValue));
}
public static bool Equals(short? n1, short? n2)
{
return (n1.HasValue == n2.HasValue) && ((!n1.HasValue) || (n1.RawValue == n2.RawValue));
}
public static bool Equals(ushort? n1, ushort? n2)
{
return (n1.HasValue == n2.HasValue) && ((!n1.HasValue) || (n1.RawValue == n2.RawValue));
}
public static bool Equals(int? n1, int? n2)
{
return (n1.HasValue == n2.HasValue) && ((!n1.HasValue) || (n1.RawValue == n2.RawValue));
}
public static bool Equals(uint? n1, uint? n2)
{
return (n1.HasValue == n2.HasValue) && ((!n1.HasValue) || (n1.RawValue == n2.RawValue));
}
public static bool Equals(long? n1, long? n2)
{
return (n1.HasValue == n2.HasValue) && ((!n1.HasValue) || (n1.RawValue == n2.RawValue));
}
public static bool Equals(ulong? n1, ulong? n2)
{
return (n1.HasValue == n2.HasValue) && ((!n1.HasValue) || (n1.RawValue == n2.RawValue));
}
public static bool Equals(double? n1, double? n2)
{
return (n1.HasValue == n2.HasValue) && ((!n1.HasValue) || (n1.RawValue == n2.RawValue));
}
public static bool Equals(float? n1, float? n2)
{
return (n1.HasValue == n2.HasValue) && ((!n1.HasValue) || (n1.RawValue == n2.RawValue));
}
[Include, Inline]
internal static string ToStringChecked(object obj)
{
return ReferenceEquals(obj, null) ? string.Empty : obj.ToString();
}
public static Type GetUnderlyingType(Type nullableType)
{
return NullableReflection.GetUnderlyingType(nullableType);
}
}
[Serializable]
public struct Nullable<T> where T : struct
{
public Nullable(T value)
{
}
/// <summary>
/// Does the this struct have a valid value?
/// </summary>
public bool HasValue
{
[DexNative]
get { return false; }
}
/// <summary>
/// Gets the value of this object without throwing error if it has no value.
/// </summary>
internal T RawValue
{
[DexNative]
get { return default(T); }
}
/// <summary>
/// Gets the value.
/// </summary>
/// <exception cref="InvalidOperationException">When this struct has no value.</exception>
public T Value
{
[DexNative]
get { return default(T); }
}
[Include]
internal static T GetValue(object nullable, bool defaultOnNull)
{
if (ReferenceEquals(nullable, null))
{
if (defaultOnNull)
return default(T);
throw new InvalidOperationException("Nullable object must have a value.");
}
return (T)nullable;
}
[Include]
internal static T GetValueOrDefault(object nullable, T defaultOnNull)
{
return (ReferenceEquals(nullable, null))
? defaultOnNull
: (T)nullable;
}
public /*override*/ int GetHashCode()
{
return !HasValue ? 0 : RawValue.GetHashCode();
}
[DexNative]
public T GetValueOrDefault()
{
return HasValue ? RawValue : default(T);
}
[DexNative]
public T GetValueOrDefault(T defaultValue)
{
return HasValue ? RawValue : defaultValue;
}
// this is handled at the compiler level.
//public override string ToString()
//{
// return HasValue ? RawValue.ToString() : String.Empty;
//}
[DexNative]
public static implicit operator Nullable<T>(T value)
{
return new Nullable<T>(value);
}
public static explicit operator T(Nullable<T> value)
{
return value.Value;
}
}
}
| |
using System.Linq;
using System.Threading.Tasks;
using Content.Server.GameTicking.Events;
using Content.Server.Ghost;
using Content.Server.Maps;
using Content.Server.Mind;
using Content.Server.Players;
using Content.Server.Station;
using Content.Shared.Coordinates;
using Content.Shared.GameTicking;
using Content.Shared.Preferences;
using Content.Shared.Station;
using Prometheus;
using Robust.Server.Player;
using Robust.Shared.Map;
using Robust.Shared.Network;
using Robust.Shared.Player;
using Robust.Shared.Random;
using Robust.Shared.Utility;
namespace Content.Server.GameTicking
{
public sealed partial class GameTicker
{
private static readonly Counter RoundNumberMetric = Metrics.CreateCounter(
"ss14_round_number",
"Round number.");
private static readonly Gauge RoundLengthMetric = Metrics.CreateGauge(
"ss14_round_length",
"Round length in seconds.");
#if EXCEPTION_TOLERANCE
[ViewVariables]
private int _roundStartFailCount = 0;
#endif
[ViewVariables]
private TimeSpan _roundStartTimeSpan;
[ViewVariables]
private bool _startingRound;
[ViewVariables]
private GameRunLevel _runLevel;
[ViewVariables]
public GameRunLevel RunLevel
{
get => _runLevel;
private set
{
// Game admins can run `restartroundnow` while still in-lobby, which'd break things with this check.
// if (_runLevel == value) return;
var old = _runLevel;
_runLevel = value;
RaiseLocalEvent(new GameRunLevelChangedEvent(old, value));
}
}
[ViewVariables]
public int RoundId { get; private set; }
private void LoadMaps()
{
AddGamePresetRules();
DefaultMap = _mapManager.CreateMap();
_mapManager.AddUninitializedMap(DefaultMap);
var startTime = _gameTiming.RealTime;
var maps = new List<GameMapPrototype>() { _gameMapManager.GetSelectedMapChecked(true) };
// Let game rules dictate what maps we should load.
RaiseLocalEvent(new LoadingMapsEvent(maps));
foreach (var map in maps)
{
var toLoad = DefaultMap;
if (maps[0] != map)
{
// Create other maps for the others since we need to.
toLoad = _mapManager.CreateMap();
_mapManager.AddUninitializedMap(toLoad);
}
_mapLoader.LoadMap(toLoad, map.MapPath.ToString());
var grids = _mapManager.GetAllMapGrids(toLoad).ToList();
var dict = new Dictionary<string, StationId>();
StationId SetupInitialStation(IMapGrid grid, GameMapPrototype map)
{
var stationId = _stationSystem.InitialSetupStationGrid(grid.GridEntityId, map);
SetupGridStation(grid);
// ass!
_spawnPoint = grid.ToCoordinates();
return stationId;
}
// Iterate over all BecomesStation
for (var i = 0; i < grids.Count; i++)
{
var grid = grids[i];
// We still setup the grid
if (!TryComp<BecomesStationComponent>(grid.GridEntityId, out var becomesStation))
continue;
var stationId = SetupInitialStation(grid, map);
dict.Add(becomesStation.Id, stationId);
}
if (!dict.Any())
{
// Oh jeez, no stations got loaded.
// We'll just take the first grid and setup that, then.
var grid = grids[0];
var stationId = SetupInitialStation(grid, map);
dict.Add("Station", stationId);
}
// Iterate over all PartOfStation
for (var i = 0; i < grids.Count; i++)
{
var grid = grids[i];
if (!TryComp<PartOfStationComponent>(grid.GridEntityId, out var partOfStation))
continue;
SetupGridStation(grid);
if (dict.TryGetValue(partOfStation.Id, out var stationId))
{
_stationSystem.AddGridToStation(grid.GridEntityId, stationId);
}
else
{
_sawmill.Error($"Grid {grid.Index} ({grid.GridEntityId}) specified that it was part of station {partOfStation.Id} which does not exist");
}
}
}
var timeSpan = _gameTiming.RealTime - startTime;
_sawmill.Info($"Loaded maps in {timeSpan.TotalMilliseconds:N2}ms.");
}
private void SetupGridStation(IMapGrid grid)
{
var stationXform = EntityManager.GetComponent<TransformComponent>(grid.GridEntityId);
if (StationOffset)
{
// Apply a random offset to the station grid entity.
var x = _robustRandom.NextFloat(-MaxStationOffset, MaxStationOffset);
var y = _robustRandom.NextFloat(-MaxStationOffset, MaxStationOffset);
stationXform.LocalPosition = new Vector2(x, y);
}
if (StationRotation)
{
stationXform.LocalRotation = _robustRandom.NextFloat(MathF.Tau);
}
}
public void StartRound(bool force = false)
{
#if EXCEPTION_TOLERANCE
try
{
#endif
// If this game ticker is a dummy or the round is already being started, do nothing!
if (DummyTicker || _startingRound)
return;
_startingRound = true;
DebugTools.Assert(RunLevel == GameRunLevel.PreRoundLobby);
_sawmill.Info("Starting round!");
SendServerMessage(Loc.GetString("game-ticker-start-round"));
LoadMaps();
StartGamePresetRules();
RoundLengthMetric.Set(0);
var playerIds = _playersInLobby.Keys.Select(player => player.UserId.UserId).ToArray();
// TODO FIXME AAAAAAAAAAAAAAAAAAAH THIS IS BROKEN
// Task.Run as a terrible dirty workaround to avoid synchronization context deadlock from .Result here.
// This whole setup logic should be made asynchronous so we can properly wait on the DB AAAAAAAAAAAAAH
RoundId = Task.Run(async () => await _db.AddNewRound(playerIds)).Result;
var startingEvent = new RoundStartingEvent();
RaiseLocalEvent(startingEvent);
List<IPlayerSession> readyPlayers;
if (LobbyEnabled)
{
readyPlayers = _playersInLobby.Where(p => p.Value == LobbyPlayerStatus.Ready).Select(p => p.Key)
.ToList();
}
else
{
readyPlayers = _playersInLobby.Keys.ToList();
}
readyPlayers.RemoveAll(p =>
{
if (_roleBanManager.GetRoleBans(p.UserId) != null)
return false;
Logger.ErrorS("RoleBans", $"Role bans for player {p} {p.UserId} have not been loaded yet.");
return true;
});
// Get the profiles for each player for easier lookup.
var profiles = _prefsManager.GetSelectedProfilesForPlayers(
readyPlayers
.Select(p => p.UserId).ToList())
.ToDictionary(p => p.Key, p => (HumanoidCharacterProfile) p.Value);
foreach (var readyPlayer in readyPlayers)
{
if (!profiles.ContainsKey(readyPlayer.UserId))
{
profiles.Add(readyPlayer.UserId, HumanoidCharacterProfile.Random());
}
}
var origReadyPlayers = readyPlayers.ToArray();
if (!StartPreset(origReadyPlayers, force))
return;
// MapInitialize *before* spawning players, our codebase is too shit to do it afterwards...
_mapManager.DoMapInitialize(DefaultMap);
SpawnPlayers(readyPlayers, origReadyPlayers, profiles, force);
_roundStartDateTime = DateTime.UtcNow;
RunLevel = GameRunLevel.InRound;
_roundStartTimeSpan = _gameTiming.RealTime;
SendStatusToAll();
ReqWindowAttentionAll();
UpdateLateJoinStatus();
UpdateJobsAvailable();
#if EXCEPTION_TOLERANCE
}
catch (Exception e)
{
_roundStartFailCount++;
if (RoundStartFailShutdownCount > 0 && _roundStartFailCount >= RoundStartFailShutdownCount)
{
_sawmill.Fatal($"Failed to start a round {_roundStartFailCount} time(s) in a row... Shutting down!");
_runtimeLog.LogException(e, nameof(GameTicker));
_baseServer.Shutdown("Restarting server");
return;
}
_sawmill.Warning($"Exception caught while trying to start the round! Restarting round...");
_runtimeLog.LogException(e, nameof(GameTicker));
_startingRound = false;
RestartRound();
return;
}
// Round started successfully! Reset counter...
_roundStartFailCount = 0;
#endif
_startingRound = false;
}
private void RefreshLateJoinAllowed()
{
var refresh = new RefreshLateJoinAllowedEvent();
RaiseLocalEvent(refresh);
DisallowLateJoin = refresh.DisallowLateJoin;
}
public void EndRound(string text = "")
{
// If this game ticker is a dummy, do nothing!
if (DummyTicker)
return;
DebugTools.Assert(RunLevel == GameRunLevel.InRound);
_sawmill.Info("Ending round!");
RunLevel = GameRunLevel.PostRound;
//Tell every client the round has ended.
var gamemodeTitle = _preset != null ? Loc.GetString(_preset.ModeTitle) : string.Empty;
// Let things add text here.
var textEv = new RoundEndTextAppendEvent();
RaiseLocalEvent(textEv);
var roundEndText = $"{text}\n{textEv.Text}";
//Get the timespan of the round.
var roundDuration = RoundDuration();
//Generate a list of basic player info to display in the end round summary.
var listOfPlayerInfo = new List<RoundEndMessageEvent.RoundEndPlayerInfo>();
// Grab the great big book of all the Minds, we'll need them for this.
var allMinds = Get<MindTrackerSystem>().AllMinds;
foreach (var mind in allMinds)
{
if (mind != null)
{
// Some basics assuming things fail
var userId = mind.OriginalOwnerUserId;
var playerOOCName = userId.ToString();
var connected = false;
var observer = mind.AllRoles.Any(role => role is ObserverRole);
// Continuing
if (_playerManager.TryGetSessionById(userId, out var ply))
{
connected = true;
}
PlayerData? contentPlayerData = null;
if (_playerManager.TryGetPlayerData(userId, out var playerData))
{
contentPlayerData = playerData.ContentData();
}
// Finish
var antag = mind.AllRoles.Any(role => role.Antagonist);
var playerIcName = "Unknown";
if (mind.CharacterName != null)
playerIcName = mind.CharacterName;
else if (mind.CurrentEntity != null && TryName(mind.CurrentEntity.Value, out var icName))
playerIcName = icName;
var playerEndRoundInfo = new RoundEndMessageEvent.RoundEndPlayerInfo()
{
// Note that contentPlayerData?.Name sticks around after the player is disconnected.
// This is as opposed to ply?.Name which doesn't.
PlayerOOCName = contentPlayerData?.Name ?? "(IMPOSSIBLE: REGISTERED MIND WITH NO OWNER)",
// Character name takes precedence over current entity name
PlayerICName = playerIcName,
Role = antag
? mind.AllRoles.First(role => role.Antagonist).Name
: mind.AllRoles.FirstOrDefault()?.Name ?? Loc.GetString("game-ticker-unknown-role"),
Antag = antag,
Observer = observer,
Connected = connected
};
listOfPlayerInfo.Add(playerEndRoundInfo);
}
}
// This ordering mechanism isn't great (no ordering of minds) but functions
var listOfPlayerInfoFinal = listOfPlayerInfo.OrderBy(pi => pi.PlayerOOCName).ToArray();
_playersInGame.Clear();
RaiseNetworkEvent(new RoundEndMessageEvent(gamemodeTitle, roundEndText, roundDuration, listOfPlayerInfoFinal.Length, listOfPlayerInfoFinal));
}
public void RestartRound()
{
// If this game ticker is a dummy, do nothing!
if (DummyTicker)
return;
if (_updateOnRoundEnd)
{
_baseServer.Shutdown(Loc.GetString("game-ticker-shutdown-server-update"));
return;
}
_sawmill.Info("Restarting round!");
SendServerMessage(Loc.GetString("game-ticker-restart-round"));
RoundNumberMetric.Inc();
RunLevel = GameRunLevel.PreRoundLobby;
LobbySong = _robustRandom.Pick(_lobbyMusicCollection.PickFiles).ToString();
ResettingCleanup();
if (!LobbyEnabled)
{
StartRound();
}
else
{
if (_playerManager.PlayerCount == 0)
_roundStartCountdownHasNotStartedYetDueToNoPlayers = true;
else
_roundStartTime = _gameTiming.CurTime + LobbyDuration;
SendStatusToAll();
ReqWindowAttentionAll();
}
}
/// <summary>
/// Cleanup that has to run to clear up anything from the previous round.
/// Stuff like wiping the previous map clean.
/// </summary>
private void ResettingCleanup()
{
// Move everybody currently in the server to lobby.
foreach (var player in _playerManager.ServerSessions)
{
PlayerJoinLobby(player);
}
// Delete the minds of everybody.
// TODO: Maybe move this into a separate manager?
foreach (var unCastData in _playerManager.GetAllPlayerData())
{
unCastData.ContentData()?.WipeMind();
}
// Delete all entities.
foreach (var entity in EntityManager.GetEntities().ToArray())
{
#if EXCEPTION_TOLERANCE
try
{
#endif
// TODO: Maybe something less naive here?
// FIXME: Actually, definitely.
EntityManager.DeleteEntity(entity);
#if EXCEPTION_TOLERANCE
}
catch (Exception e)
{
_sawmill.Error($"Caught exception while trying to delete entity {ToPrettyString(entity)}, this might corrupt the game state...");
_runtimeLog.LogException(e, nameof(GameTicker));
continue;
}
#endif
}
_mapManager.Restart();
_roleBanManager.Restart();
// Clear up any game rules.
ClearGameRules();
_addedGameRules.Clear();
// Round restart cleanup event, so entity systems can reset.
var ev = new RoundRestartCleanupEvent();
RaiseLocalEvent(ev);
// So clients' entity systems can clean up too...
RaiseNetworkEvent(ev, Filter.Broadcast());
_spawnedPositions.Clear();
_manifest.Clear();
DisallowLateJoin = false;
}
public bool DelayStart(TimeSpan time)
{
if (_runLevel != GameRunLevel.PreRoundLobby)
{
return false;
}
_roundStartTime += time;
RaiseNetworkEvent(new TickerLobbyCountdownEvent(_roundStartTime, Paused));
_chatManager.DispatchServerAnnouncement(Loc.GetString("game-ticker-delay-start", ("seconds",time.TotalSeconds)));
return true;
}
private void UpdateRoundFlow(float frameTime)
{
if (RunLevel == GameRunLevel.InRound)
{
RoundLengthMetric.Inc(frameTime);
}
if (RunLevel != GameRunLevel.PreRoundLobby || Paused ||
_roundStartTime > _gameTiming.CurTime ||
_roundStartCountdownHasNotStartedYetDueToNoPlayers)
{
return;
}
StartRound();
}
public TimeSpan RoundDuration()
{
return _gameTiming.RealTime.Subtract(_roundStartTimeSpan);
}
}
public enum GameRunLevel
{
PreRoundLobby = 0,
InRound = 1,
PostRound = 2
}
public sealed class GameRunLevelChangedEvent
{
public GameRunLevel Old { get; }
public GameRunLevel New { get; }
public GameRunLevelChangedEvent(GameRunLevel old, GameRunLevel @new)
{
Old = old;
New = @new;
}
}
/// <summary>
/// Event raised before maps are loaded in pre-round setup.
/// Contains a list of game map prototypes to load; modify it if you want to load different maps,
/// for example as part of a game rule.
/// </summary>
public sealed class LoadingMapsEvent : EntityEventArgs
{
public List<GameMapPrototype> Maps;
public LoadingMapsEvent(List<GameMapPrototype> maps)
{
Maps = maps;
}
}
/// <summary>
/// Event raised to refresh the late join status.
/// If you want to disallow late joins, listen to this and call Disallow.
/// </summary>
public sealed class RefreshLateJoinAllowedEvent
{
public bool DisallowLateJoin { get; private set; } = false;
public void Disallow()
{
DisallowLateJoin = true;
}
}
/// <summary>
/// Attempt event raised on round start.
/// This can be listened to by GameRule systems to cancel round start if some condition is not met, like player count.
/// </summary>
public sealed class RoundStartAttemptEvent : CancellableEntityEventArgs
{
public IPlayerSession[] Players { get; }
public bool Forced { get; }
public RoundStartAttemptEvent(IPlayerSession[] players, bool forced)
{
Players = players;
Forced = forced;
}
}
/// <summary>
/// Event raised before readied up players are spawned and given jobs by the GameTicker.
/// You can use this to spawn people off-station, like in the case of nuke ops or wizard.
/// Remove the players you spawned from the PlayerPool and call <see cref="GameTicker.PlayerJoinGame"/> on them.
/// </summary>
public sealed class RulePlayerSpawningEvent
{
/// <summary>
/// Pool of players to be spawned.
/// If you want to handle a specific player being spawned, remove it from this list and do what you need.
/// </summary>
/// <remarks>If you spawn a player by yourself from this event, don't forget to call <see cref="GameTicker.PlayerJoinGame"/> on them.</remarks>
public List<IPlayerSession> PlayerPool { get; }
public IReadOnlyDictionary<NetUserId, HumanoidCharacterProfile> Profiles { get; }
public bool Forced { get; }
public RulePlayerSpawningEvent(List<IPlayerSession> playerPool, IReadOnlyDictionary<NetUserId, HumanoidCharacterProfile> profiles, bool forced)
{
PlayerPool = playerPool;
Profiles = profiles;
Forced = forced;
}
}
/// <summary>
/// Event raised after players were assigned jobs by the GameTicker.
/// You can give on-station people special roles by listening to this event.
/// </summary>
public sealed class RulePlayerJobsAssignedEvent
{
public IPlayerSession[] Players { get; }
public IReadOnlyDictionary<NetUserId, HumanoidCharacterProfile> Profiles { get; }
public bool Forced { get; }
public RulePlayerJobsAssignedEvent(IPlayerSession[] players, IReadOnlyDictionary<NetUserId, HumanoidCharacterProfile> profiles, bool forced)
{
Players = players;
Profiles = profiles;
Forced = forced;
}
}
/// <summary>
/// Event raised to allow subscribers to add text to the round end summary screen.
/// </summary>
public sealed class RoundEndTextAppendEvent
{
private bool _doNewLine;
/// <summary>
/// Text to display in the round end summary screen.
/// </summary>
public string Text { get; private set; } = string.Empty;
/// <summary>
/// Invoke this method to add text to the round end summary screen.
/// </summary>
/// <param name="text"></param>
public void AddLine(string text)
{
if (_doNewLine)
Text += "\n";
Text += text;
_doNewLine = true;
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Projection
// Description: The basic module for MapWindow version 6.0
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 8/17/2009 1:47:05 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// Name | Date | Comment
// --------------------|------------|------------------------------------------------------------
// Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace DotSpatial.Projections.Nad
{
/// <summary>
/// NadRecord is a single entry from an lla file
/// </summary>
[Serializable]
public class NadTable
{
/// <summary>
/// Converts degree values into radians
/// </summary>
protected const double DEG_TO_RAD = Math.PI / 180;
/// <summary>
/// I think this converts micro-seconds of arc to radians
/// </summary>
protected const double USecToRad = 4.848136811095359935899141023e-12;
/// <summary>
/// The delta lambda and delta phi for a single cell
/// </summary>
private PhiLam _cellSize;
/// <summary>
/// The set of conversion matrix coefficients for lambda
/// </summary>
private PhiLam[][] _cvs;
private long _dataOffset;
private bool _fileIsEmbedded;
private readonly bool _requiresDecompression;
private bool _filled;
private GridShiftTableFormat _format;
private string _gridFilePath;
/// <summary>
/// The lower left coordinate
/// </summary>
private PhiLam _lowerLeft;
private string _manifestResourceString;
/// <summary>
/// The character based id for this record
/// </summary>
private string _name;
/// <summary>
/// The total count of coordinates in the lambda direction
/// </summary>
private int _numLambdas;
/// <summary>
/// The total count of coordinates in the phi direction
/// </summary>
private int _numPhis;
private List<NadTable> _subGrids;
/// <summary>
/// Creates a blank nad Table
/// </summary>
public NadTable()
{
_subGrids = new List<NadTable>();
}
/// <summary>
/// This initializes a new table with the assumption that the offset is 0
/// </summary>
/// <param name="resourceLocation">The resource location</param>
public NadTable(string resourceLocation)
: this(resourceLocation, 0)
{
}
/// <summary>
/// This initializes a new table with the assumption that the offset is 0
/// </summary>
/// <param name="resourceLocation">The resource location</param>
/// <param name="embedded">Indicates if grid file is in embedded resource or external file</param>
public NadTable(string resourceLocation, bool embedded)
: this(resourceLocation, 0, embedded)
{
}
public NadTable(string resourceLocation, bool embedded, bool requiresDecompression)
: this(resourceLocation, 0, embedded, requiresDecompression)
{
}
/// <summary>
/// This initializes a new table with the assumption that the offset needs to be specified
/// because in gsb files, more than one table is listed, and this is a subtable.
/// </summary>
/// <param name="resourceLocation">The resource location</param>
/// <param name="offset">The offset marking the start of the header in the file</param>
public NadTable(string resourceLocation, long offset)
: this(resourceLocation, offset, true)
{
}
/// <summary>
/// This initializes a new table with the assumption that the offset needs to be specified
/// because in gsb files, more than one table is listed, and this is a subtable. This also allows
/// specifying if the grid file is included as an embedded resource.
/// </summary>
/// <param name="location">The resource (or file) location</param>
/// <param name="offset">The offset marking the start of the header in the file</param>
/// <param name="embedded">Indicates if embedded resource or external file</param>
/// <param name="requiresDecompression">Indicates if embedded resource requires decompression</param>
public NadTable(string location, long offset, bool embedded, bool requiresDecompression = false)
{
_subGrids = new List<NadTable>();
if (embedded)
{
_manifestResourceString = location;
}
else
{
_gridFilePath = location;
}
_fileIsEmbedded = embedded;
_requiresDecompression = requiresDecompression;
_dataOffset = offset;
}
/// <summary>
/// Given the resource setup, this causes the file to read the
/// </summary>
public virtual void ReadHeader()
{
// This code is implemented differently in subclasses
}
/// <summary>
///
/// </summary>
public virtual void FillData()
{
// THis code is implemented differently in subclasses
}
/// <summary>
/// This method parses the extension of a resource location or
/// path and creates the new NadTable type.
/// </summary>
public static NadTable FromSourceName(string location, bool embedded = true, bool requiresDecompression = false)
{
NadTable result = null;
string ext = Path.GetExtension(location).ToLower();
switch (ext)
{
case ".lla":
result = new LlaNadTable(location, embedded, requiresDecompression);
break;
case ".gsb":
result = new GsbNadTable(location, 0, embedded, requiresDecompression);
break;
case ".dat":
result = new DatNadTable(location, embedded, requiresDecompression);
break;
case ".los":
result = new LasLosNadTable(location, embedded, requiresDecompression);
break;
}
if (result != null) result.ReadHeader();
return result;
}
#region Methods
/// <summary>
/// Gets or sets the string name for this record
/// </summary>
public string Name
{
get { return _name; }
set { _name = value; }
}
/// <summary>
/// Gets or sets the lower left corner in radians
/// </summary>
public PhiLam LowerLeft
{
get { return _lowerLeft; }
set { _lowerLeft = value; }
}
/// <summary>
/// Gets or sets the angular cell size in radians
/// </summary>
public PhiLam CellSize
{
get { return _cellSize; }
set { _cellSize = value; }
}
/// <summary>
/// Gets or sets the integer count of phi coefficients
/// </summary>
public int NumPhis
{
get { return _numPhis; }
set { _numPhis = value; }
}
/// <summary>
/// Gets or sets the integer count of lambda coefficients
/// </summary>
public int NumLambdas
{
get { return _numLambdas; }
set { _numLambdas = value; }
}
/// <summary>
/// These represent smaller, higher resolution subgrids that should fall within the extents
/// of the larger grid. If this list exists, and there is a fit here, it should be used
/// in preference to the low-resolution main grid.
/// </summary>
public List<NadTable> SubGrids
{
get { return _subGrids; }
set { _subGrids = value; }
}
/// <summary>
/// Gets or sets the array of lambda coefficients organized
/// in a spatial Table (phi major)
/// </summary>
public PhiLam[][] Cvs
{
get { return _cvs; }
set { _cvs = value; }
}
/// <summary>
/// Gets or sets a boolean indicating whether or not the values have been filled.
/// </summary>
public bool Filled
{
get { return _filled; }
set { _filled = value; }
}
/// <summary>
/// Gets or sets the location this table should look for source data.
/// </summary>
public string ManifestResourceString
{
get { return _manifestResourceString; }
set { _manifestResourceString = value; }
}
/// <summary>
/// Gets or sets the long integer data offset where the stream should skip to to begin reading data
/// </summary>
public long DataOffset
{
get { return _dataOffset; }
set { _dataOffset = value; }
}
/// <summary>
/// Gets or sets the format being used.
/// </summary>
public GridShiftTableFormat Format
{
get { return _format; }
set { _format = value; }
}
/// <summary>
/// True if grid file is an embedded resource
/// </summary>
public bool FileIsEmbedded
{
get { return _fileIsEmbedded; }
set { _fileIsEmbedded = value; }
}
protected bool RequiresDecompression
{
get { return _requiresDecompression; }
}
/// <summary>
/// If FileIsEmbedded is false, this contains the full path to the grid file
/// </summary>
public string GridFilePath
{
get { return _gridFilePath; }
set { _gridFilePath = value; }
}
/// <summary>
/// Reads a double in BigEndian format (consistent with ntv1 and ntv2 formats.)
/// </summary>
/// <param name="br">The binary reader</param>
/// <returns>The double value parsed from the binary in big endian byte order.</returns>
protected static double ReadDouble(BinaryReader br)
{
byte[] temp = new byte[8];
br.Read(temp, 0, 8);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(temp);
}
double value = BitConverter.ToDouble(temp, 0);
return value;
}
/// <summary>
/// Gets the double value from the specified position in the byte array
/// Using BigEndian format.
/// </summary>
/// <param name="array"></param>
/// <param name="offset"></param>
/// <returns></returns>
protected virtual double GetDouble(byte[] array, int offset)
{
byte[] bValue = new byte[8];
Array.Copy(array, offset, bValue, 0, 8);
if (BitConverter.IsLittleEndian) Array.Reverse(bValue);
return BitConverter.ToDouble(bValue, 0);
}
/// <summary>
/// Get the stream to the grid
/// </summary>
/// <returns></returns>
protected Stream GetStream()
{
Assembly a = Assembly.GetExecutingAssembly();
Stream str = FileIsEmbedded
? (_requiresDecompression
? DeflateStreamReader.DecodeEmbeddedResource(_manifestResourceString)
: a.GetManifestResourceStream(_manifestResourceString))
: File.OpenRead(_gridFilePath);
return str;
}
#endregion
}
}
| |
// Code generated by a Template
using System;
using DNX.Helpers.Maths;
using DNX.Helpers.Validation;
using NUnit.Framework;
using Shouldly;
using Test.DNX.Helpers.Validation.TestsDataSource;
namespace Test.DNX.Helpers.Validation
{
[TestFixture]
public class GuardDoubleTests
{
[TestCaseSource(typeof(GuardDoubleTestsSource), "IsBetween_Default")]
public bool Guard_IsBetween_Default(double value, double min, double max, string messageText)
{
try
{
// Act
Guard.IsBetween(() => value, min, max);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
[TestCaseSource(typeof(GuardDoubleTestsSource), "IsBetween_BoundsType")]
public bool Guard_IsBetween_BoundsType(double value, double min, double max, IsBetweenBoundsType boundsType, string messageText)
{
try
{
// Act
Guard.IsBetween(() => value, min, max, boundsType);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
[TestCaseSource(typeof(GuardDoubleTestsSource), "IsBetween")]
public bool Guard_IsBetween(double value, double min, double max, bool allowEitherOrder, IsBetweenBoundsType boundsType, string messageText)
{
try
{
// Act
Guard.IsBetween(() => value, min, max, allowEitherOrder, boundsType);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
[TestCaseSource(typeof(GuardDoubleTestsSource), "IsGreaterThan")]
public bool Guard_IsGreaterThan_Expr(double value, double min, string messageText)
{
try
{
// Act
Guard.IsGreaterThan(() => value, min);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
[TestCaseSource(typeof(GuardDoubleTestsSource), "IsGreaterThan")]
public bool Guard_IsGreaterThan_Value(double actualValue, double min, string messageText)
{
try
{
// Act
double value = min;
Guard.IsGreaterThan(() => value, actualValue, min);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
[TestCaseSource(typeof(GuardDoubleTestsSource), "IsGreaterThanOrEqualTo")]
public bool Guard_IsGreaterThanOrEqualTo_Expr(double value, double min, string messageText)
{
try
{
// Act
Guard.IsGreaterThanOrEqualTo(() => value, min);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
[TestCaseSource(typeof(GuardDoubleTestsSource), "IsGreaterThanOrEqualTo")]
public bool Guard_IsGreaterThanOrEqualTo_Value(double actualValue, double min, string messageText)
{
try
{
// Act
double value = min;
Guard.IsGreaterThanOrEqualTo(() => value, actualValue, min);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
[TestCaseSource(typeof(GuardDoubleTestsSource), "IsLessThan")]
public bool Guard_IsLessThan_Expr(double value, double max, string messageText)
{
try
{
// Act
Guard.IsLessThan(() => value, max);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
[TestCaseSource(typeof(GuardDoubleTestsSource), "IsLessThan")]
public bool Guard_IsLessThan_Value(double actualValue, double max, string messageText)
{
try
{
// Act
double value = max;
Guard.IsLessThan(() => value, actualValue, max);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
[TestCaseSource(typeof(GuardDoubleTestsSource), "IsLessThanOrEqualTo")]
public bool Guard_IsLessThanOrEqualTo_Expr(double value, double max, string messageText)
{
try
{
// Act
Guard.IsLessThanOrEqualTo(() => value, max);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
[TestCaseSource(typeof(GuardDoubleTestsSource), "IsLessThanOrEqualTo")]
public bool Guard_IsLessThanOrEqualTo_Value(double actualValue, double max, string messageText)
{
try
{
// Act
double value = max;
Guard.IsLessThanOrEqualTo(() => value, actualValue, max);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using IronAHK.Rusty.Linux.X11;
using IronAHK.Rusty.Linux.X11.Events;
namespace IronAHK.Rusty.Linux
{
internal class KeyboardHook : Common.Keyboard.KeyboardHook
{
StringBuilder Dummy = new StringBuilder(); // Somehow needed to get strings from native X11
Dictionary<char, CachedKey> Cache;
Dictionary<XKeys, System.Windows.Forms.Keys> Mapping;
XConnectionSingleton XConn;
protected override void RegisterHook()
{
SetupMapping();
XConn = XConnectionSingleton.GetInstance();
XConn.OnEvent += HandleXEvent;
}
void HandleXEvent (XEvent Event)
{
if(Event.type == XEventName.KeyPress || Event.type == XEventName.KeyRelease)
KeyReceived(TranslateKey(Event), Event.type == XEventName.KeyPress);
}
protected override void DeregisterHook()
{
// TODO disposal
}
System.Windows.Forms.Keys TranslateKey(XEvent Event)
{
if(Mapping.ContainsKey(Event.KeyEvent.keycode))
return Mapping[Event.KeyEvent.keycode];
else return StringToWFKey(Event);
}
System.Windows.Forms.Keys StringToWFKey(XEvent Event)
{
Dummy.Remove(0, Dummy.Length);
Dummy.Append(" "); // HACK: Somehow necessary
Event.KeyEvent.state = 16; // Repair any shifting applied by control
if(Xlib.XLookupString(ref Event, Dummy, 10, IntPtr.Zero, IntPtr.Zero) != 0)
{
string Lookup = Dummy.ToString();
if(Dummy.Length == 1 && char.IsLetterOrDigit(Dummy[0]))
Lookup = Dummy[0].ToString().ToUpper();
if(string.IsNullOrEmpty(Lookup.Trim())) return System.Windows.Forms.Keys.None;
try
{
return (System.Windows.Forms.Keys) Enum.Parse(typeof(System.Windows.Forms.Keys), Lookup);
}
catch(ArgumentException)
{
// TODO
Console.Error.WriteLine("Warning, could not look up key: "+Lookup);
return System.Windows.Forms.Keys.None;
}
}
else return System.Windows.Forms.Keys.None;
}
#region Hotstrings
// Simulate a number of backspaces
protected override void Backspace (int length)
{
for(int i = 0; i < length; i++)
{
Xlib.XTestFakeKeyEvent(XConn.Handle, (uint)XKeys.BackSpace, true, 0);
Xlib.XTestFakeKeyEvent(XConn.Handle, (uint)XKeys.BackSpace, false, 0);
}
}
protected internal override void Send(string Sequence)
{
foreach(var C in Sequence)
{
CachedKey Key = LookupKeycode(C);
// If it is an upper case character, hold the shift key...
if(char.IsUpper(C) || Key.Shift)
Xlib.XTestFakeKeyEvent(XConn.Handle, (uint)XKeys.LeftShift, true, 0);
// Make sure the key is up before we press it again.
// If X thinks this key is still down, nothing will happen if we press it.
// Likewise, if X thinks that the key is up, this will do no harm.
Xlib.XTestFakeKeyEvent(XConn.Handle, Key.Sym, false, 0);
// Fake a key event. Note that some programs filter this kind of event.
Xlib.XTestFakeKeyEvent(XConn.Handle, Key.Sym, true, 0);
Xlib.XTestFakeKeyEvent(XConn.Handle, Key.Sym, false, 0);
// ...and release it later on
if(char.IsUpper(C) || Key.Shift)
Xlib.XTestFakeKeyEvent(XConn.Handle, (uint)XKeys.LeftShift, false, 0);
}
}
protected internal override void Send(System.Windows.Forms.Keys key)
{
var vk = (uint)key;
Xlib.XTestFakeKeyEvent(XConn.Handle, vk, true, 0);
Xlib.XTestFakeKeyEvent(XConn.Handle, vk, false, 0);
}
CachedKey LookupKeycode(char Code)
{
// If we have a cache value, return that
if(Cache.ContainsKey(Code))
return Cache[Code];
// First look up the KeySym (XK_* in X11/keysymdef.h)
uint KeySym = Xlib.XStringToKeysym(Code.ToString());
// Then look up the appropriate KeyCode
uint KeyCode = Xlib.XKeysymToKeycode(XConn.Handle, KeySym);
// Cache for later use
var Ret = new CachedKey(KeyCode, false);
Cache.Add(Code, Ret);
return Ret;
}
#endregion
private struct CachedKey
{
public uint Sym;
public bool Shift;
public CachedKey(uint Sym, bool Shift) {
this.Sym = Sym;
this.Shift = Shift;
}
public CachedKey(XKeys Sym, bool Shift)
: this((uint)Sym, Shift) {
}
}
public void SetupMapping() {
Mapping = new Dictionary<XKeys, System.Windows.Forms.Keys>();
Cache = new Dictionary<char, CachedKey>();
Mapping.Add(XKeys.LeftAlt, System.Windows.Forms.Keys.LMenu);
Mapping.Add(XKeys.RightAlt, System.Windows.Forms.Keys.RMenu);
Mapping.Add(XKeys.LeftControl, System.Windows.Forms.Keys.LControlKey);
Mapping.Add(XKeys.RightControl, System.Windows.Forms.Keys.RControlKey);
Mapping.Add(XKeys.LeftSuper, System.Windows.Forms.Keys.LWin);
Mapping.Add(XKeys.RightSuper, System.Windows.Forms.Keys.RWin);
Mapping.Add(XKeys.LeftShift, System.Windows.Forms.Keys.LShiftKey);
Mapping.Add(XKeys.RightShift, System.Windows.Forms.Keys.RShiftKey);
Mapping.Add(XKeys.F1, System.Windows.Forms.Keys.F1);
Mapping.Add(XKeys.F2, System.Windows.Forms.Keys.F2);
Mapping.Add(XKeys.F3, System.Windows.Forms.Keys.F3);
Mapping.Add(XKeys.F4, System.Windows.Forms.Keys.F4);
Mapping.Add(XKeys.F5, System.Windows.Forms.Keys.F5);
Mapping.Add(XKeys.F6, System.Windows.Forms.Keys.F6);
Mapping.Add(XKeys.F7, System.Windows.Forms.Keys.F7);
Mapping.Add(XKeys.F8, System.Windows.Forms.Keys.F8);
Mapping.Add(XKeys.F9, System.Windows.Forms.Keys.F9);
Mapping.Add(XKeys.F10, System.Windows.Forms.Keys.F10);
// Missing: F11 (Caught by WM)
Mapping.Add(XKeys.F12, System.Windows.Forms.Keys.F12);
Mapping.Add(XKeys.Escape, System.Windows.Forms.Keys.Escape);
Mapping.Add(XKeys.Tab, System.Windows.Forms.Keys.Tab);
Mapping.Add(XKeys.CapsLock, System.Windows.Forms.Keys.CapsLock);
Mapping.Add(XKeys.Tilde, System.Windows.Forms.Keys.Oemtilde);
Mapping.Add(XKeys.Backslash, System.Windows.Forms.Keys.OemBackslash);
Mapping.Add(XKeys.BackSpace, System.Windows.Forms.Keys.Back);
Mapping.Add(XKeys.ScrollLock, System.Windows.Forms.Keys.Scroll);
Mapping.Add(XKeys.Pause, System.Windows.Forms.Keys.Pause);
Mapping.Add(XKeys.Insert, System.Windows.Forms.Keys.Insert);
Mapping.Add(XKeys.Delete, System.Windows.Forms.Keys.Delete);
Mapping.Add(XKeys.Home, System.Windows.Forms.Keys.Home);
Mapping.Add(XKeys.End, System.Windows.Forms.Keys.End);
Mapping.Add(XKeys.PageUp, System.Windows.Forms.Keys.PageUp);
Mapping.Add(XKeys.PageDown, System.Windows.Forms.Keys.PageDown);
Mapping.Add(XKeys.NumLock, System.Windows.Forms.Keys.NumLock);
Mapping.Add(XKeys.SpaceBar, System.Windows.Forms.Keys.Space);
Mapping.Add(XKeys.Return, System.Windows.Forms.Keys.Return);
Mapping.Add(XKeys.Slash, System.Windows.Forms.Keys.OemQuestion);
Mapping.Add(XKeys.Dot, System.Windows.Forms.Keys.OemPeriod);
Mapping.Add(XKeys.Comma, System.Windows.Forms.Keys.Oemcomma);
Mapping.Add(XKeys.Semicolon, System.Windows.Forms.Keys.OemSemicolon);
Mapping.Add(XKeys.OpenSquareBracket, System.Windows.Forms.Keys.OemOpenBrackets);
Mapping.Add(XKeys.CloseSquareBracket, System.Windows.Forms.Keys.OemCloseBrackets);
Mapping.Add(XKeys.Up, System.Windows.Forms.Keys.Up);
Mapping.Add(XKeys.Down, System.Windows.Forms.Keys.Down);
Mapping.Add(XKeys.Right, System.Windows.Forms.Keys.Right);
Mapping.Add(XKeys.Left, System.Windows.Forms.Keys.Left);
// Not sure about these ....
Mapping.Add(XKeys.Dash, System.Windows.Forms.Keys.OemMinus);
Mapping.Add(XKeys.Equals, System.Windows.Forms.Keys.Oemplus);
// No windows equivalent?
Mapping.Add(XKeys.NumpadSlash, System.Windows.Forms.Keys.None);
Mapping.Add(XKeys.NumpadAsterisk, System.Windows.Forms.Keys.None);
Mapping.Add(XKeys.NumpadDot, System.Windows.Forms.Keys.None);
Mapping.Add(XKeys.NumpadEnter, System.Windows.Forms.Keys.None);
Mapping.Add(XKeys.NumpadPlus, System.Windows.Forms.Keys.None);
Mapping.Add(XKeys.NumpadMinus, System.Windows.Forms.Keys.None);
#region Cache
// Add keys to the cache that can not be looked up with XLookupKeysym
// HACK: I'm not sure these will work on other keyboard layouts.
Cache.Add('(', new CachedKey(XKeys.OpenParens, true));
Cache.Add(')', new CachedKey(XKeys.CloseParens, true));
Cache.Add('[', new CachedKey(XKeys.OpenSquareBracket, true));
Cache.Add(']', new CachedKey(XKeys.CloseSquareBracket, true));
Cache.Add('=', new CachedKey(XKeys.Equals, true));
Cache.Add('-', new CachedKey(XKeys.Dash, true));
Cache.Add('!', new CachedKey(XKeys.ExMark, true));
Cache.Add('@', new CachedKey(XKeys.At, true));
Cache.Add('#', new CachedKey(XKeys.Hash, true));
Cache.Add('$', new CachedKey(XKeys.Dollar, true));
Cache.Add('%', new CachedKey(XKeys.Percent, true));
Cache.Add('^', new CachedKey(XKeys.Circumflex, true));
Cache.Add('&', new CachedKey(XKeys.Ampersand, true));
Cache.Add('*', new CachedKey(XKeys.Asterisk, true));
Cache.Add(' ', new CachedKey(XKeys.SpaceBar, false));
#endregion
}
}
}
| |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
using Lucene.Net.Analysis;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Store;
using Lucene.Net.Support;
using Lucene.Net.Util;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Console = Lucene.Net.Support.SystemConsole;
namespace Lucene.Net.Documents
{
[TestFixture]
public class TestLazyDocument : LuceneTestCase
{
public readonly int NUM_DOCS = AtLeast(10);
public readonly string[] FIELDS = new string[]
{ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k" };
public readonly int NUM_VALUES = AtLeast(100);
public Directory dir = NewDirectory();
[OneTimeTearDown]
public override void AfterClass() // LUCENENET specific - changed from CreateIndex() to ensure calling order vs base class
{
if (null != dir)
{
try
{
dir.Dispose();
dir = null;
}
catch (Exception /*e*/) { /* NOOP */ }
}
base.AfterClass();
}
[OneTimeSetUp]
public override void BeforeClass() // LUCENENET specific - changed from CreateIndex() to ensure calling order vs base class
{
base.BeforeClass();
Analyzer analyzer = new MockAnalyzer(Random());
IndexWriter writer = new IndexWriter
(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer));
try
{
for (int docid = 0; docid < NUM_DOCS; docid++)
{
Document d = new Document();
d.Add(NewStringField("docid", "" + docid, Field.Store.YES));
d.Add(NewStringField("never_load", "fail", Field.Store.YES));
foreach (string f in FIELDS)
{
for (int val = 0; val < NUM_VALUES; val++)
{
d.Add(NewStringField(f, docid + "_" + f + "_" + val, Field.Store.YES));
}
}
d.Add(NewStringField("load_later", "yes", Field.Store.YES));
writer.AddDocument(d);
}
}
finally
{
writer.Dispose();
}
}
[Test]
public void TestLazy()
{
int id = Random().nextInt(NUM_DOCS);
IndexReader reader = DirectoryReader.Open(dir);
try
{
Query q = new TermQuery(new Term("docid", "" + id));
IndexSearcher searcher = NewSearcher(reader);
ScoreDoc[] hits = searcher.Search(q, 100).ScoreDocs;
assertEquals("Too many docs", 1, hits.Length);
LazyTestingStoredFieldVisitor visitor
= new LazyTestingStoredFieldVisitor(new LazyDocument(reader, hits[0].Doc),
FIELDS);
reader.Document(hits[0].Doc, visitor);
Document d = visitor.doc;
int numFieldValues = 0;
IDictionary<string, int> fieldValueCounts = new HashMap<string, int>();
// at this point, all FIELDS should be Lazy and unrealized
foreach (IIndexableField f in d)
{
numFieldValues++;
if (f.Name.equals("never_load"))
{
fail("never_load was loaded");
}
if (f.Name.equals("load_later"))
{
fail("load_later was loaded on first pass");
}
if (f.Name.equals("docid"))
{
assertFalse(f.Name, f is LazyDocument.LazyField);
}
else
{
int count = fieldValueCounts.ContainsKey(f.Name) ?
fieldValueCounts[f.Name] : 0;
count++;
fieldValueCounts.Put(f.Name, count);
assertTrue(f.Name + " is " + f.GetType(),
f is LazyDocument.LazyField);
LazyDocument.LazyField lf = (LazyDocument.LazyField)f;
assertFalse(f.Name + " is loaded", lf.HasBeenLoaded);
}
}
Console.WriteLine("numFieldValues == " + numFieldValues);
assertEquals("numFieldValues", 1 + (NUM_VALUES * FIELDS.Length),
numFieldValues);
foreach (string field in fieldValueCounts.Keys)
{
assertEquals("fieldName count: " + field,
NUM_VALUES, fieldValueCounts[field]);
}
// pick a single field name to load a single value
string fieldName = FIELDS[Random().nextInt(FIELDS.Length)];
IIndexableField[] fieldValues = d.GetFields(fieldName);
assertEquals("#vals in field: " + fieldName,
NUM_VALUES, fieldValues.Length);
int valNum = Random().nextInt(fieldValues.Length);
assertEquals(id + "_" + fieldName + "_" + valNum,
fieldValues[valNum].GetStringValue());
// now every value of fieldName should be loaded
foreach (IIndexableField f in d)
{
if (f.Name.equals("never_load"))
{
fail("never_load was loaded");
}
if (f.Name.equals("load_later"))
{
fail("load_later was loaded too soon");
}
if (f.Name.equals("docid"))
{
assertFalse(f.Name, f is LazyDocument.LazyField);
}
else
{
assertTrue(f.Name + " is " + f.GetType(),
f is LazyDocument.LazyField);
LazyDocument.LazyField lf = (LazyDocument.LazyField)f;
assertEquals(f.Name + " is loaded?",
lf.Name.equals(fieldName), lf.HasBeenLoaded);
}
}
// use the same LazyDoc to ask for one more lazy field
visitor = new LazyTestingStoredFieldVisitor(new LazyDocument(reader, hits[0].Doc),
"load_later");
reader.Document(hits[0].Doc, visitor);
d = visitor.doc;
// ensure we have all the values we expect now, and that
// adding one more lazy field didn't "unload" the existing LazyField's
// we already loaded.
foreach (IIndexableField f in d)
{
if (f.Name.equals("never_load"))
{
fail("never_load was loaded");
}
if (f.Name.equals("docid"))
{
assertFalse(f.Name, f is LazyDocument.LazyField);
}
else
{
assertTrue(f.Name + " is " + f.GetType(),
f is LazyDocument.LazyField);
LazyDocument.LazyField lf = (LazyDocument.LazyField)f;
assertEquals(f.Name + " is loaded?",
lf.Name.equals(fieldName), lf.HasBeenLoaded);
}
}
// even the underlying doc shouldn't have never_load
assertNull("never_load was loaded in wrapped doc",
visitor.lazyDoc.GetDocument().GetField("never_load"));
}
finally
{
reader.Dispose();
}
}
internal class LazyTestingStoredFieldVisitor : StoredFieldVisitor
{
public readonly Document doc = new Document();
public readonly LazyDocument lazyDoc;
public readonly ISet<string> lazyFieldNames;
internal LazyTestingStoredFieldVisitor(LazyDocument l, params string[] fields)
{
lazyDoc = l;
lazyFieldNames = new HashSet<string>(Arrays.AsList(fields));
}
public override Status NeedsField(FieldInfo fieldInfo)
{
if (fieldInfo.Name.equals("docid"))
{
return Status.YES;
}
else if (fieldInfo.Name.equals("never_load"))
{
return Status.NO;
}
else
{
if (lazyFieldNames.contains(fieldInfo.Name))
{
doc.Add(lazyDoc.GetField(fieldInfo));
}
}
return Status.NO;
}
public override void StringField(FieldInfo fieldInfo, string value)
{
FieldType ft = new FieldType(TextField.TYPE_STORED);
ft.StoreTermVectors = fieldInfo.HasVectors;
ft.IsIndexed = fieldInfo.IsIndexed;
ft.OmitNorms = fieldInfo.OmitsNorms;
ft.IndexOptions = fieldInfo.IndexOptions;
doc.Add(new Field(fieldInfo.Name, value, ft));
}
}
}
}
| |
#region Header
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Copyright (c) 2007-2008 James Nies and NArrange contributors.
* All rights reserved.
*
* This program and the accompanying materials are made available under
* the terms of the Common Public License v1.0 which accompanies this
* distribution.
*
* 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.
*
* 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.
*
*<author>James Nies</author>
*<contributor>Justin Dearing</contributor>
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#endregion Header
namespace NArrange.Core.Configuration
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Xml.Serialization;
/// <summary>
/// Code arranger configuration information.
/// </summary>
public class CodeConfiguration : ConfigurationElement
{
#region Fields
/// <summary>
/// Synchronization lock for the default configuration instance.
/// </summary>
private static readonly object _defaultLock = new object();
/// <summary>
/// Seriarializer for serializing and deserializing the configuration
/// to and from XML.
/// </summary>
private static readonly XmlSerializer _serializer;
/// <summary>
/// The default configuration instance.
/// </summary>
private static CodeConfiguration _default;
/// <summary>
/// Encoding configuration.
/// </summary>
private EncodingConfiguration _encoding;
/// <summary>
/// Formatting configuration.
/// </summary>
private FormattingConfiguration _formatting;
/// <summary>
/// Collection of source/project handler configurations.
/// </summary>
private HandlerConfigurationCollection _handlers;
#endregion Fields
#region Constructors
/// <summary>
/// Type initialization.
/// </summary>
static CodeConfiguration()
{
_serializer = new XmlSerializer(typeof(CodeConfiguration));
// Register handlers for invalid configuration elements
_serializer.UnknownAttribute += new XmlAttributeEventHandler(HandleUnknownAttribute);
_serializer.UnknownElement += new XmlElementEventHandler(HandleUnknownElement);
}
#endregion Constructors
#region Properties
/// <summary>
/// Gets the default configuration.
/// </summary>
public static CodeConfiguration Default
{
get
{
if (_default == null)
{
lock (_defaultLock)
{
if (_default == null)
{
// Load the default configuration from the embedded resource file.
using (Stream resourceStream =
typeof(CodeConfiguration).Assembly.GetManifestResourceStream(
typeof(CodeConfiguration).Assembly.GetName().Name + ".DefaultConfig.xml"))
{
_default = Load(resourceStream);
}
}
}
}
return _default;
}
}
/// <summary>
/// Gets or sets the closing comment configuration.
/// </summary>
[Description("The settings for closing comments (Obsolete - Use Formatting.ClosingComments instead).")]
[DisplayName("Closing comments (Obsolete)")]
[ReadOnly(true)]
[Browsable(false)]
public ClosingCommentConfiguration ClosingComments
{
get
{
return null;
}
set
{
Formatting.ClosingComments = value;
}
}
/// <summary>
/// Gets or sets the encoding configuration.
/// </summary>
[Description("The encoding settings used for reading and writing source code files.")]
[ReadOnly(true)]
public EncodingConfiguration Encoding
{
get
{
if (_encoding == null)
{
lock (this)
{
if (_encoding == null)
{
// Default encoding configuration
_encoding = new EncodingConfiguration();
}
}
}
return _encoding;
}
set
{
_encoding = value;
}
}
/// <summary>
/// Gets or sets the formatting configuration.
/// </summary>
[Description("Formatting settings.")]
[DisplayName("Formatting")]
[ReadOnly(true)]
public FormattingConfiguration Formatting
{
get
{
if (_formatting == null)
{
lock (this)
{
if (_formatting == null)
{
// Default style configuration
_formatting = new FormattingConfiguration();
}
}
}
return _formatting;
}
set
{
_formatting = value;
}
}
/// <summary>
/// Gets the collection of source code/project handlers.
/// </summary>
[XmlArrayItem(typeof(SourceHandlerConfiguration))]
[XmlArrayItem(typeof(ProjectHandlerConfiguration))]
[Description("The list of project/language handlers and their settings.")]
public HandlerConfigurationCollection Handlers
{
get
{
if (_handlers == null)
{
lock (this)
{
if (_handlers == null)
{
_handlers = new HandlerConfigurationCollection();
}
}
}
return _handlers;
}
}
/// <summary>
/// Gets or sets the regions configuration.
/// </summary>
[Description("The settings for all regions (Obsolete - Use Formatting.Regions instead).")]
[ReadOnly(true)]
[Browsable(false)]
public RegionFormatConfiguration Regions
{
get
{
return null;
}
set
{
Formatting.Regions = value;
}
}
/// <summary>
/// Gets or sets the tab configuration.
/// </summary>
[Description("The settings for indentation (Obsolete - Use Formatting.Tabs instead).")]
[ReadOnly(true)]
[Browsable(false)]
public TabConfiguration Tabs
{
get
{
return null;
}
set
{
Formatting.Tabs = value;
}
}
#endregion Properties
#region Methods
/// <summary>
/// Loads a configuration from the specified file.
/// </summary>
/// <param name="fileName">Configuration file name.</param>
/// <returns>The loaded code configuration if succesful, otherwise null.</returns>
public static CodeConfiguration Load(string fileName)
{
return Load(fileName, true);
}
/// <summary>
/// Loads a configuration from the specified file.
/// </summary>
/// <param name="fileName">Configuration file name.</param>
/// <param name="resolveReferences">Resolve element references.</param>
/// <returns>The code configuration if succesful, otherwise null.</returns>
public static CodeConfiguration Load(string fileName, bool resolveReferences)
{
using (FileStream fileStream = new FileStream(fileName, FileMode.Open))
{
return Load(fileStream, resolveReferences);
}
}
/// <summary>
/// Loads a configuration from a stream.
/// </summary>
/// <param name="stream">The stream to load the configuration from.</param>
/// <returns>The code configuration if succesful, otherwise null.</returns>
public static CodeConfiguration Load(Stream stream)
{
return Load(stream, true);
}
/// <summary>
/// Loads a configuration from a stream.
/// </summary>
/// <param name="stream">The sream to load the configuration from.</param>
/// <param name="resolveReferences">
/// Whether or not element references should be resolved.
/// </param>
/// <returns>The code configuration if succesful, otherwise null.</returns>
public static CodeConfiguration Load(Stream stream, bool resolveReferences)
{
CodeConfiguration configuration =
_serializer.Deserialize(stream) as CodeConfiguration;
if (resolveReferences)
{
configuration.ResolveReferences();
}
configuration.Upgrade();
return configuration;
}
/// <summary>
/// Override Clone so that we can force resolution of element references.
/// </summary>
/// <returns>
/// A new object that is a copy of this instance.
/// </returns>
public override object Clone()
{
CodeConfiguration clone = base.Clone() as CodeConfiguration;
clone.ResolveReferences();
return clone;
}
/// <summary>
/// Resolves any reference elements in the configuration.
/// </summary>
public void ResolveReferences()
{
Dictionary<string, ElementConfiguration> elementMap = new Dictionary<string, ElementConfiguration>();
List<ElementReferenceConfiguration> elementReferences = new List<ElementReferenceConfiguration>();
Action<ConfigurationElement> populateElementMap = delegate(ConfigurationElement element)
{
ElementConfiguration elementConfiguration = element as ElementConfiguration;
if (elementConfiguration != null && elementConfiguration.Id != null)
{
elementMap.Add(elementConfiguration.Id, elementConfiguration);
}
};
Action<ConfigurationElement> populateElementReferenceList = delegate(ConfigurationElement element)
{
ElementReferenceConfiguration elementReference = element as ElementReferenceConfiguration;
if (elementReference != null && elementReference.Id != null)
{
elementReferences.Add(elementReference);
}
};
Action<ConfigurationElement>[] actions = new Action<ConfigurationElement>[]
{
populateElementMap,
populateElementReferenceList
};
TreeProcess(this, actions);
// Resolve element references
foreach (ElementReferenceConfiguration reference in elementReferences)
{
ElementConfiguration referencedElement = null;
elementMap.TryGetValue(reference.Id, out referencedElement);
if (referencedElement != null)
{
reference.ReferencedElement = referencedElement;
}
else
{
throw new InvalidOperationException(
string.Format(
"Unable to resolve element reference for Id={0}.",
reference.Id));
}
}
}
/// <summary>
/// Saves the configuration to a file.
/// </summary>
/// <param name="fileName">Name of the file.</param>
public void Save(string fileName)
{
using (FileStream stream = new FileStream(fileName, FileMode.Create))
{
_serializer.Serialize(stream, this);
}
}
/// <summary>
/// Creates a clone of this instance.
/// </summary>
/// <returns>A clone of the instance.</returns>
protected override ConfigurationElement DoClone()
{
CodeConfiguration clone = new CodeConfiguration();
clone._encoding = Encoding.Clone() as EncodingConfiguration;
clone._formatting = Formatting.Clone() as FormattingConfiguration;
foreach (HandlerConfiguration handler in Handlers)
{
HandlerConfiguration handlerClone = handler.Clone() as HandlerConfiguration;
clone.Handlers.Add(handlerClone);
}
return clone;
}
/// <summary>
/// Handler for unknown attributes.
/// </summary>
/// <param name="sender">The sender/</param>
/// <param name="e">Event arguments.</param>
private static void HandleUnknownAttribute(object sender, XmlAttributeEventArgs e)
{
throw new InvalidOperationException(e.ToString() + " Unknown attribute " + e.Attr.Name);
}
/// <summary>
/// Handler for unknown elements.
/// </summary>
/// <param name="sender">The sender/</param>
/// <param name="e">Event arguments.</param>
private static void HandleUnknownElement(object sender, XmlElementEventArgs e)
{
throw new InvalidOperationException(e.ToString() + " Unknown element " + e.Element.Name);
}
/// <summary>
/// Recurses through the configuration tree and executes actions against
/// each configuration element.
/// </summary>
/// <param name="element">Element to process.</param>
/// <param name="actions">Actions to perform.</param>
private void TreeProcess(ConfigurationElement element, Action<ConfigurationElement>[] actions)
{
if (element != null)
{
foreach (ConfigurationElement childElement in element.Elements)
{
foreach (Action<ConfigurationElement> action in actions)
{
action(childElement);
}
TreeProcess(childElement, actions);
}
}
}
/// <summary>
/// Upgrades the configuration.
/// </summary>
private void Upgrade()
{
UpgradeProjectExtensions();
}
/// <summary>
/// Moves project extensions to the new format.
/// </summary>
private void UpgradeProjectExtensions()
{
// Migrate project handler configurations
string parserType = typeof(MSBuildProjectParser).FullName;
ProjectHandlerConfiguration projectHandlerConfiguration = null;
foreach (HandlerConfiguration handlerConfiguration in Handlers)
{
if (handlerConfiguration.HandlerType == HandlerType.Project)
{
ProjectHandlerConfiguration candidateConfiguration = handlerConfiguration as ProjectHandlerConfiguration;
if (candidateConfiguration.ParserType != null &&
candidateConfiguration.ParserType.ToUpperInvariant() == parserType.ToUpperInvariant())
{
projectHandlerConfiguration = candidateConfiguration;
break;
}
}
}
//
// Create the new project configuration if necessary
//
if (projectHandlerConfiguration == null)
{
projectHandlerConfiguration = new ProjectHandlerConfiguration();
projectHandlerConfiguration.ParserType = parserType;
Handlers.Insert(0, projectHandlerConfiguration);
}
foreach (HandlerConfiguration handlerConfiguration in Handlers)
{
if (handlerConfiguration.HandlerType == HandlerType.Source)
{
SourceHandlerConfiguration sourceHandlerConfiguration = handlerConfiguration as SourceHandlerConfiguration;
foreach (ExtensionConfiguration projectExtension in sourceHandlerConfiguration.ProjectExtensions)
{
bool upgraded = false;
foreach (ExtensionConfiguration upgradedExtension in projectHandlerConfiguration.ProjectExtensions)
{
if (string.Compare(upgradedExtension.Name, projectExtension.Name, true) == 0)
{
upgraded = true;
break;
}
}
if (!upgraded)
{
projectHandlerConfiguration.ProjectExtensions.Add(projectExtension);
}
}
sourceHandlerConfiguration.ProjectExtensions.Clear();
}
}
}
#endregion Methods
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Reflection;
using System.Web;
using bv.common.Core;
using System.IO;
using System.Linq;
using bv.common.Configuration;
using System.Windows.Forms;
namespace bv.common.Diagnostics
{
public class Dbg
{
//private static Regex s_DebugMethodFilterRegexp;
//private static bool s_DebugMethodFilterRegexpDefined;
private static int m_DefaultDetailLevel;
private Dbg()
{
// NOOP
}
private static readonly StandardOutput m_StandardOutput = new StandardOutput();
public static DebugFileOutput CreateDebugFileOutput(string fileName)
{
if (!Utils.IsEmpty(fileName))
{
DirectoryInfo dir;
if (HttpContext.Current != null)
{
dir = GetWebErrorDirectory();
}
else
dir = Directory.GetParent(Application.CommonAppDataPath);
string logfile = dir.FullName + "\\" + fileName;
if (IsValidOutputFile(logfile))
return new DebugFileOutput(logfile, false);
logfile = Utils.GetExecutingPath() + fileName;
if (IsValidOutputFile(logfile))
return new DebugFileOutput(logfile, false);
}
return null;
}
private static DirectoryInfo GetWebErrorDirectory()
{
string path = BaseSettings.ErrorLogPath;
if (!Path.IsPathRooted(path))
path = Path.Combine(Utils.GetExecutingPath(), path);
if (!String.IsNullOrEmpty(path))
{
if (!Directory.Exists(path))
{
try
{
Utils.ForceDirectories(path);
return new DirectoryInfo(path);
}
catch
{
return null;
}
}
return new DirectoryInfo(path);
}
return null;
}
private static IDebugOutput CreateDefaultOutputMethod()
{
// TODO: allow configurable output to log file
m_DefaultDetailLevel = BaseSettings.DebugDetailLevel;
if (!BaseSettings.DebugOutput)
{
return null;
}
if (!Utils.IsEmpty(BaseSettings.DebugLogFile))
{
var output = CreateDebugFileOutput(BaseSettings.DebugLogFile);
if (output != null)
return output;
}
return m_StandardOutput;
}
private static bool IsValidOutputFile(string fileName)
{
try
{
if (File.Exists(fileName))
{
FileAttributes attr = File.GetAttributes(fileName);
if ((attr & FileAttributes.ReadOnly) != 0)
{
attr = attr & (~FileAttributes.ReadOnly);
File.SetAttributes(fileName, attr);
}
FileStream fs = File.OpenWrite(fileName);
fs.Close();
}
else
{
FileStream fs = File.Create(fileName);
fs.Close();
}
return true;
}
catch (Exception)
{
return false;
}
}
private static string FormatDataRow(DataRow row)
{
var @out = (from DataColumn col in row.Table.Columns
select string.Format(":{0} <{1}>", col.ColumnName, FormatValue(row[col]))).ToList();
return string.Format("#<DataRow {0}>", Utils.Join(" ", @out));
}
public static string FormatValue(object value)
{
if (value == null)
{
return "*Nothing*";
}
if (value == DBNull.Value)
{
return "*DBNull*";
}
var row = value as DataRow;
if (row != null)
{
return FormatDataRow(row);
}
var view = value as DataRowView;
if (view != null)
{
return FormatDataRow(view.Row);
}
try
{
var ret = value.ToString();
if (ret.IsNormalized())
return ret;
return "*Non string value*";
}
catch
{
return "*Non string value*";
}
}
private static IDebugOutput m_OutputMethod;
public static IDebugOutput OutputMethod
{
get
{
if (!Config.IsInitialized)
Config.InitSettings();
if (!Config.IsInitialized)
return m_StandardOutput;
return m_OutputMethod ?? (m_OutputMethod = CreateDefaultOutputMethod());
//Dim result As IDebugOutput = Nothing
//If InitSlot() Then
// result = CType(Thread.GetData(s_OutputMethodSlot), IDebugOutput)
//Else
// result = CreateDefaultOutputMethod()
// Thread.SetData(s_OutputMethodSlot, result)
//End If
//Return result
}
set
{
m_OutputMethod = value;
//InitSlot()
//Thread.SetData(s_OutputMethodSlot, value)
}
}
private static void DoDbg(int detailLevel, string fmt, params object[] args)
{
if (OutputMethod != null)
{
var trace = new StackTrace(2, true);
string methodName = "*UNKNOWN*";
string declaringMethodName = "*UNKNOWN*";
if (trace.GetFrame(0) != null)
{
MethodBase method = trace.GetFrame(0).GetMethod();
if (method != null)
{
methodName = method.Name;
if (method.DeclaringType != null)
declaringMethodName = method.DeclaringType.Name;
}
}
if (ShouldIgnore(detailLevel))
{
return;
}
if (args == null || args.Length == 0)
{
OutputMethod.WriteLine(string.Format("{0} {1}.{2}(): {3}", DateTime.Now, declaringMethodName, methodName, fmt));
return;
}
var newArgs = new object[args.Length];
for (int i = 0; i <= args.Length - 1; i++)
{
newArgs[i] = FormatValue(args[i]);
}
OutputMethod.WriteLine(string.Format("{0} {1}.{2}(): {3}", DateTime.Now, declaringMethodName, methodName, string.Format(fmt, newArgs)));
}
}
public static void WriteLine(string fmt, params object[] args)
{
if (OutputMethod != null)
{
var newArgs = new object[args.Length];
for (int i = 0; i <= args.Length - 1; i++)
newArgs[i] = FormatValue(args[i]);
OutputMethod.WriteLine(args.Length == 0 ? fmt : string.Format(fmt, newArgs));
}
}
public static void Debug(string fmt, params object[] args)
{
DoDbg(0, fmt, args);
}
public static void ConditionalDebug(int detailLevel, string fmt, params object[] args)
{
DoDbg(detailLevel, fmt, args);
}
public static void ConditionalDebug(DebugDetalizationLevel detailLevel, string fmt, params object[] args)
{
DoDbg((int)detailLevel, fmt, args);
}
public static void Fail(string fmt, params object[] args)
{
string message = "Assertion failed: " + string.Format(fmt, args);
DoDbg(0, "{0}", message); // TODO: always print failure messages
if (Debugger.IsAttached)
{
Debugger.Break();
}
throw (new InternalErrorException(message));
}
public static void Assert(bool value, string fmt, params object[] args)
{
if (!value)
{
// we duplicate Fail here to make DoDbg work correctly
string message = "Assertion failed: " + string.Format(fmt, args);
DoDbg(0, "{0}", message);
if (Debugger.IsAttached)
{
Debugger.Break();
}
throw (new InternalErrorException(message));
}
}
public static void DbgAssert(bool value, string fmt, params object[] args)
{
if (!value)
{
// we duplicate Fail here to make DoDbg work correctly
string message = "Assertion failed: " + string.Format(fmt, args);
DoDbg(0, "{0}", message);
}
}
public static void DbgAssert(int detailLevel, bool value, string fmt, params object[] args)
{
if (!value)
{
// we duplicate Fail here to make DoDbg work correctly
string message = "Assertion failed: " + string.Format(fmt, args);
DoDbg(detailLevel, "{0}", message);
}
}
// TODO: probably System.Diagnostics.SymbolStore.* can be used to display extended error information
public static void Require(params object[] values)
{
for (int i = 0; i <= values.Length - 1; i++)
{
if (values[i] == null)
{
// we duplicate Fail here to make DoDbg work correctly
string message = string.Format("Require: value #{0} (starting from 1) is Nothing", i + 1);
DoDbg(0, "{0}", message);
if (Debugger.IsAttached)
{
Debugger.Break();
}
throw (new InternalErrorException(message));
}
}
}
private static bool ShouldIgnore(int detailLevel)
{
return detailLevel > m_DefaultDetailLevel;
}
public static void Trace(params object[] argValues)
{
#if TRACE
if (OutputMethod == null)
{
return;
}
var trace = new StackTrace(1, true);
MethodBase method = null;
string methodName = "*UNKNOWN*";
string declaringTypeName = "*UNKNOWN*";
if (trace.GetFrame(0) != null)
{
method = trace.GetFrame(0).GetMethod();
if (method != null)
{
methodName = method.Name;
if (method.DeclaringType != null)
declaringTypeName = method.DeclaringType.Name;
}
}
var argStrings = new List<string>();
if (argValues != null && argValues.Length != 0 && method != null)
{
ParameterInfo[] @params = method.GetParameters();
int numArgs = Math.Min(@params.Length, argValues.Length);
for (int i = 0; i <= numArgs - 1; i++)
{
string valString = FormatValue(argValues[i]);
argStrings.Add(string.Format("{0} = <{1}>", @params[i].Name, valString));
}
}
OutputMethod.WriteLine(string.Format("--> {0}.{1}({2})", declaringTypeName, methodName, Utils.Join(", ", argStrings)));
#endif
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.hide003.hide003
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class C
{
}
public class Base
{
public static int Status;
public void Method(C x)
{
Base.Status = 1;
}
}
public class Derived : Base
{
public new void Method(C x)
{
Base.Status = 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
C x = new C();
d.Method(x);
if (Base.Status == 2)
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload001.overload001
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static int Status;
public void Method(short x)
{
Base.Status = 1;
}
}
public class Derived : Base
{
public void Method(int x)
{
Base.Status = 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
short x = 3;
d.Method(x);
if (Base.Status == 2)
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload002.overload002
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static int Status;
public void Method(short x)
{
Base.Status = 1;
}
}
public class Derived : Base
{
public void Method(int x)
{
Base.Status = 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
int x = 3;
d.Method(x);
if (Base.Status == 2)
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload003.overload003
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Call methods with different accessibility level and selecting the right one.:)
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static int Status;
protected void Method(short x)
{
Base.Status = 1;
}
}
public class Derived : Base
{
public void Method(int x)
{
Base.Status = 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
int x = 3;
d.Method(x);
if (Base.Status == 2)
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload004.overload004
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Call methods with different accessibility level and selecting the right one.:)
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static int Status;
public void Method(int x)
{
Base.Status = 1;
}
}
public class Derived : Base
{
protected void Method(short x)
{
Base.Status = 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
short x = 3;
d.Method(x);
if (Base.Status == 1)
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload005.overload005
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Call methods with different accessibility level and selecting the right one.:)
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static int Status;
public void Method(int x)
{
Base.Status = 1;
}
}
public class Derived : Base
{
private void Method(short x)
{
Base.Status = 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
short x = 3;
d.Method(x);
if (Base.Status == 1)
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload006.overload006
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Call methods with different accessibility level and selecting the right one.:)
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static int Status;
internal void Method(short x)
{
Base.Status = 1;
}
}
public class Derived : Base
{
public void Method(int x)
{
Base.Status = 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
int x = 3;
d.Method(x);
if (Base.Status == 2)
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload007.overload007
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Call methods with different accessibility level and selecting the right one.:)
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static int Status;
protected internal void Method(short x)
{
Base.Status = 1;
}
}
public class Derived : Base
{
public void Method(int x)
{
Base.Status = 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
int x = 3;
d.Method(x);
if (Base.Status == 2)
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload008.overload008
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Select the best method to call.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static int Status;
public int Method(dynamic x)
{
Base.Status = 1;
return 1;
}
public void Method(short x)
{
Base.Status = 2;
}
}
public class Derived : Base
{
public void Method(int x)
{
Base.Status = 3;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
dynamic x = 3;
d.Method(x);
if (Base.Status == 3)
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload009.overload009
{
// <Title> Tests overload resolution</Title>
// <Description></Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public class B
{
public static int status = -1;
public void Foo(out int x)
{
status = 1;
x = 1;
}
}
public class A : B
{
public void Foo(ref int x)
{
status = 2;
}
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic a = new A();
int x;
// used to call 'ref', should call 'out'
a.Foo(out x);
return (1 == status) ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload010.overload010
{
// <Title> Tests overload resolution</Title>
// <Description>regression test </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public class B
{
public static int status = -1;
public void Foo(out int x)
{
status = 1;
x = 1;
}
}
public class A : B
{
public void Foo(ref int x)
{
status = 2;
}
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic a = new A();
int x;
// used to call 'ref', should call 'out'
a.Foo(out x);
return (1 == status) ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload011.overload011
{
//<Area></Area>
//<Title></Title>
//<Description>regression test</Description>
//<Related Bugs></Related Bugs>
//<Expects Status=success></Expects Status>
//<Code>
public class NO
{
public void Foo<T, U>(U u = default(U), T t2 = default(T))
{
System.Console.WriteLine(1);
}
public void Foo<T>(params T[] t)
{
Program.result = 0;
}
}
public class Program
{
public static int result;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic x = new NO();
x.Foo(3);
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload012.overload012
{
//<Area></Area>
//<Title></Title>
//<Description>regression test</Description>
//<Related Bugs></Related Bugs>
//<Expects Status=success></Expects Status>
//<Code>
public class NO
{
public void Foo<T>(T t = default(T))
{
}
}
public class Program
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new NO();
try
{
d.Foo();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
{
return 0;
}
catch (System.Exception)
{
return 1;
}
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.overload013.overload013
{
// <Area>dynamic</Area>
// <Title>ref parameter overloading</Title>
// <Description>
// binder generates bad expression tree in presence of ref overload
// </Description>
// <Related Bugs></Related Bugs>
//<Expects Status=success></Expects>
// <Code>
public class A
{
public static int x = 0;
public void Foo(ref string y)
{
x = 1;
}
}
public class C : A
{
public void Foo(string y)
{
}
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic x = new C();
string y = "";
x.Foo(ref y);
return (A.x == 1) ? 0 : 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr001.ovr001
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static int Status;
public virtual void Method(int x)
{
Base.Status = 1;
}
}
public class Derived : Base
{
public override void Method(int x)
{
Base.Status = 2;
}
public void Method(long l)
{
Base.Status = 3;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
int x = 3;
d.Method(x);
if (Base.Status == 3)
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr002.ovr002
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static int Status;
public virtual void Method(int x)
{
Base.Status = 1;
}
}
public class Derived : Base
{
public override void Method(int x)
{
Base.Status = 2;
}
public void Method(long l)
{
Base.Status = 3;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
short x = 3;
d.Method(x);
if (Base.Status == 3)
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr003.ovr003
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static int Status;
public virtual void Method(string x)
{
Base.Status = 1;
}
}
public class Derived : Base
{
public override void Method(string x)
{
Base.Status = 2;
}
public void Method(object o)
{
Base.Status = 3;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
string x = "3";
d.Method(x);
if (Base.Status == 3)
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr004.ovr004
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class C
{
}
public class D : C
{
}
public class Base
{
public static int Status;
public virtual void Method(D x)
{
Base.Status = 1;
}
}
public class Derived : Base
{
public override void Method(D x)
{
Base.Status = 2;
}
public void Method(C o)
{
Base.Status = 3;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
C x = new C();
d.Method(x);
if (Base.Status == 3)
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr005.ovr005
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class C
{
}
public class D : C
{
}
public class Base
{
public static int Status;
public virtual void Method(D x)
{
Base.Status = 1;
}
}
public class Derived : Base
{
public override void Method(D x)
{
Base.Status = 2;
}
public void Method(C o)
{
Base.Status = 3;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
D x = new D();
d.Method(x);
if (Base.Status == 3)
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr006.ovr006
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class C
{
}
public class D : C
{
}
public class Base
{
public static int Status;
public virtual void Method(D x)
{
Base.Status = 1;
}
}
public class Derived : Base
{
public override void Method(D x)
{
Base.Status = 2;
}
public void Method(C o)
{
Base.Status = 3;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
C x = new D();
d.Method(x);
if (Base.Status == 3)
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr007.ovr007
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class C
{
}
public class D : C
{
}
public class Base
{
public static int Status;
public virtual void Method(int x)
{
Base.Status = 1;
}
}
public class Derived : Base
{
public override void Method(int x)
{
Base.Status = 2;
}
public void Method(string o)
{
Base.Status = 3;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
int x = 3;
d.Method(x);
if (Base.Status == 2)
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr008.ovr008
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class C
{
}
public class Base
{
public static int Status;
public virtual void Method(int x)
{
Base.Status = 1;
}
}
public class Derived : Base
{
public override void Method(int x)
{
Base.Status = 2;
}
public void Method(C o)
{
Base.Status = 3;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
short x = 3;
d.Method(x);
if (Base.Status == 2)
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr009.ovr009
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public enum E
{
first,
second
}
public class Base
{
public static int Status;
public virtual void Method(string x)
{
Base.Status = 1;
}
}
public class Derived : Base
{
public override void Method(string x)
{
Base.Status = 2;
}
public void Method(E o)
{
Base.Status = 3;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
string x = "adfs";
d.Method(x);
if (Base.Status == 2)
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr010.ovr010
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class C
{
public static implicit operator int (C c)
{
return 0;
}
}
public class Base
{
public static int Status;
public virtual void Method(C x)
{
Base.Status = 1;
}
}
public class Derived : Base
{
public override void Method(C x)
{
Base.Status = 2;
}
public void Method(int o)
{
Base.Status = 3;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
C x = new C();
d.Method(x);
if (Base.Status == 3)
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr011.ovr011
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class C
{
public static implicit operator int (C c)
{
return 0;
}
}
public class Base
{
public static int Status;
public virtual void Method(C x)
{
Base.Status = 1;
}
}
public class Derived : Base
{
public override void Method(C x)
{
Base.Status = 2;
}
public void Method(long o)
{
Base.Status = 3;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
C x = new C(); //This should go to Base.Status = 3
d.Method(x);
if (Base.Status == 3)
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovr012.ovr012
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static int Status;
public virtual void Method(int x)
{
Base.Status = 1;
}
public virtual void Method(long y)
{
Base.Status = 2;
}
}
public class Derived : Base
{
public override void Method(long x)
{
Base.Status = 3;
}
}
public class FurtherDerived : Derived
{
public override void Method(int y)
{
Base.Status = 4;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new FurtherDerived();
int x = 3;
d.Method(x);
if (Base.Status == 4) //We should pick the second method
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovrdynamic001.ovrdynamic001
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class C
{
}
public class Base
{
public static int Status;
public virtual void Method(object x)
{
Base.Status = 1;
}
}
public class Derived : Base
{
public override void Method(dynamic x)
{
Base.Status = 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
C x = new C(); //This should go to Base.Status = 3
d.Method(x);
if (Base.Status == 2)
return 0;
else
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Methods.Twoclass2methods.ovrdynamic002.ovrdynamic002
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class C
{
}
public class Base
{
public static int Status;
public virtual void Method(dynamic x)
{
Base.Status = 1;
}
}
public class Derived : Base
{
public override void Method(object x)
{
Base.Status = 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
C x = new C(); //This should go to Base.Status = 3
d.Method(x);
if (Base.Status == 2)
return 0;
else
return 1;
}
}
// </Code>
}
| |
using System;
using System.IO;
namespace ICSharpCode.SharpZipLib.Zip
{
/// <summary>
/// Defines known values for the <see cref="HostSystemID"/> property.
/// </summary>
public enum HostSystemID
{
/// <summary>
/// Host system = MSDOS
/// </summary>
Msdos = 0,
/// <summary>
/// Host system = Amiga
/// </summary>
Amiga = 1,
/// <summary>
/// Host system = Open VMS
/// </summary>
OpenVms = 2,
/// <summary>
/// Host system = Unix
/// </summary>
Unix = 3,
/// <summary>
/// Host system = VMCms
/// </summary>
VMCms = 4,
/// <summary>
/// Host system = Atari ST
/// </summary>
AtariST = 5,
/// <summary>
/// Host system = OS2
/// </summary>
OS2 = 6,
/// <summary>
/// Host system = Macintosh
/// </summary>
Macintosh = 7,
/// <summary>
/// Host system = ZSystem
/// </summary>
ZSystem = 8,
/// <summary>
/// Host system = Cpm
/// </summary>
Cpm = 9,
/// <summary>
/// Host system = Windows NT
/// </summary>
WindowsNT = 10,
/// <summary>
/// Host system = MVS
/// </summary>
MVS = 11,
/// <summary>
/// Host system = VSE
/// </summary>
Vse = 12,
/// <summary>
/// Host system = Acorn RISC
/// </summary>
AcornRisc = 13,
/// <summary>
/// Host system = VFAT
/// </summary>
Vfat = 14,
/// <summary>
/// Host system = Alternate MVS
/// </summary>
AlternateMvs = 15,
/// <summary>
/// Host system = BEOS
/// </summary>
BeOS = 16,
/// <summary>
/// Host system = Tandem
/// </summary>
Tandem = 17,
/// <summary>
/// Host system = OS400
/// </summary>
OS400 = 18,
/// <summary>
/// Host system = OSX
/// </summary>
OSX = 19,
/// <summary>
/// Host system = WinZIP AES
/// </summary>
WinZipAES = 99,
}
/// <summary>
/// This class represents an entry in a zip archive. This can be a file
/// or a directory
/// ZipFile and ZipInputStream will give you instances of this class as
/// information about the members in an archive. ZipOutputStream
/// uses an instance of this class when creating an entry in a Zip file.
/// <br/>
/// <br/>Author of the original java version : Jochen Hoenicke
/// </summary>
public class ZipEntry
{
[Flags]
private enum Known : byte
{
None = 0,
Size = 0x01,
CompressedSize = 0x02,
Crc = 0x04,
Time = 0x08,
ExternalAttributes = 0x10,
}
#region Constructors
/// <summary>
/// Creates a zip entry with the given name.
/// </summary>
/// <param name="name">
/// The name for this entry. Can include directory components.
/// The convention for names is 'unix' style paths with relative names only.
/// There are with no device names and path elements are separated by '/' characters.
/// </param>
/// <exception cref="ArgumentNullException">
/// The name passed is null
/// </exception>
public ZipEntry(string name)
: this(name, 0, ZipConstants.VersionMadeBy, CompressionMethod.Deflated)
{
}
/// <summary>
/// Creates a zip entry with the given name and version required to extract
/// </summary>
/// <param name="name">
/// The name for this entry. Can include directory components.
/// The convention for names is 'unix' style paths with no device names and
/// path elements separated by '/' characters. This is not enforced see <see cref="CleanName(string)">CleanName</see>
/// on how to ensure names are valid if this is desired.
/// </param>
/// <param name="versionRequiredToExtract">
/// The minimum 'feature version' required this entry
/// </param>
/// <exception cref="ArgumentNullException">
/// The name passed is null
/// </exception>
internal ZipEntry(string name, int versionRequiredToExtract)
: this(name, versionRequiredToExtract, ZipConstants.VersionMadeBy,
CompressionMethod.Deflated)
{
}
/// <summary>
/// Initializes an entry with the given name and made by information
/// </summary>
/// <param name="name">Name for this entry</param>
/// <param name="madeByInfo">Version and HostSystem Information</param>
/// <param name="versionRequiredToExtract">Minimum required zip feature version required to extract this entry</param>
/// <param name="method">Compression method for this entry.</param>
/// <exception cref="ArgumentNullException">
/// The name passed is null
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// versionRequiredToExtract should be 0 (auto-calculate) or > 10
/// </exception>
/// <remarks>
/// This constructor is used by the ZipFile class when reading from the central header
/// It is not generally useful, use the constructor specifying the name only.
/// </remarks>
internal ZipEntry(string name, int versionRequiredToExtract, int madeByInfo,
CompressionMethod method)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (name.Length > 0xffff)
{
throw new ArgumentException("Name is too long", nameof(name));
}
if ((versionRequiredToExtract != 0) && (versionRequiredToExtract < 10))
{
throw new ArgumentOutOfRangeException(nameof(versionRequiredToExtract));
}
this.DateTime = DateTime.Now;
this.name = CleanName(name);
this.versionMadeBy = (ushort)madeByInfo;
this.versionToExtract = (ushort)versionRequiredToExtract;
this.method = method;
IsUnicodeText = ZipStrings.UseUnicode;
}
/// <summary>
/// Creates a deep copy of the given zip entry.
/// </summary>
/// <param name="entry">
/// The entry to copy.
/// </param>
[Obsolete("Use Clone instead")]
public ZipEntry(ZipEntry entry)
{
if (entry == null)
{
throw new ArgumentNullException(nameof(entry));
}
known = entry.known;
name = entry.name;
size = entry.size;
compressedSize = entry.compressedSize;
crc = entry.crc;
dosTime = entry.dosTime;
method = entry.method;
comment = entry.comment;
versionToExtract = entry.versionToExtract;
versionMadeBy = entry.versionMadeBy;
externalFileAttributes = entry.externalFileAttributes;
flags = entry.flags;
zipFileIndex = entry.zipFileIndex;
offset = entry.offset;
forceZip64_ = entry.forceZip64_;
if (entry.extra != null)
{
extra = new byte[entry.extra.Length];
Array.Copy(entry.extra, 0, extra, 0, entry.extra.Length);
}
}
#endregion Constructors
/// <summary>
/// Get a value indicating wether the entry has a CRC value available.
/// </summary>
public bool HasCrc
{
get
{
return (known & Known.Crc) != 0;
}
}
/// <summary>
/// Get/Set flag indicating if entry is encrypted.
/// A simple helper routine to aid interpretation of <see cref="Flags">flags</see>
/// </summary>
/// <remarks>This is an assistant that interprets the <see cref="Flags">flags</see> property.</remarks>
public bool IsCrypted
{
get
{
return (flags & 1) != 0;
}
set
{
if (value)
{
flags |= 1;
}
else
{
flags &= ~1;
}
}
}
/// <summary>
/// Get / set a flag indicating wether entry name and comment text are
/// encoded in <a href="http://www.unicode.org">unicode UTF8</a>.
/// </summary>
/// <remarks>This is an assistant that interprets the <see cref="Flags">flags</see> property.</remarks>
public bool IsUnicodeText
{
get
{
return (flags & (int)GeneralBitFlags.UnicodeText) != 0;
}
set
{
if (value)
{
flags |= (int)GeneralBitFlags.UnicodeText;
}
else
{
flags &= ~(int)GeneralBitFlags.UnicodeText;
}
}
}
/// <summary>
/// Value used during password checking for PKZIP 2.0 / 'classic' encryption.
/// </summary>
internal byte CryptoCheckValue
{
get
{
return cryptoCheckValue_;
}
set
{
cryptoCheckValue_ = value;
}
}
/// <summary>
/// Get/Set general purpose bit flag for entry
/// </summary>
/// <remarks>
/// General purpose bit flag<br/>
/// <br/>
/// Bit 0: If set, indicates the file is encrypted<br/>
/// Bit 1-2 Only used for compression type 6 Imploding, and 8, 9 deflating<br/>
/// Imploding:<br/>
/// Bit 1 if set indicates an 8K sliding dictionary was used. If clear a 4k dictionary was used<br/>
/// Bit 2 if set indicates 3 Shannon-Fanno trees were used to encode the sliding dictionary, 2 otherwise<br/>
/// <br/>
/// Deflating:<br/>
/// Bit 2 Bit 1<br/>
/// 0 0 Normal compression was used<br/>
/// 0 1 Maximum compression was used<br/>
/// 1 0 Fast compression was used<br/>
/// 1 1 Super fast compression was used<br/>
/// <br/>
/// Bit 3: If set, the fields crc-32, compressed size
/// and uncompressed size are were not able to be written during zip file creation
/// The correct values are held in a data descriptor immediately following the compressed data. <br/>
/// Bit 4: Reserved for use by PKZIP for enhanced deflating<br/>
/// Bit 5: If set indicates the file contains compressed patch data<br/>
/// Bit 6: If set indicates strong encryption was used.<br/>
/// Bit 7-10: Unused or reserved<br/>
/// Bit 11: If set the name and comments for this entry are in <a href="http://www.unicode.org">unicode</a>.<br/>
/// Bit 12-15: Unused or reserved<br/>
/// </remarks>
/// <seealso cref="IsUnicodeText"></seealso>
/// <seealso cref="IsCrypted"></seealso>
public int Flags
{
get
{
return flags;
}
set
{
flags = value;
}
}
/// <summary>
/// Get/Set index of this entry in Zip file
/// </summary>
/// <remarks>This is only valid when the entry is part of a <see cref="ZipFile"></see></remarks>
public long ZipFileIndex
{
get
{
return zipFileIndex;
}
set
{
zipFileIndex = value;
}
}
/// <summary>
/// Get/set offset for use in central header
/// </summary>
public long Offset
{
get
{
return offset;
}
set
{
offset = value;
}
}
/// <summary>
/// Get/Set external file attributes as an integer.
/// The values of this are operating system dependant see
/// <see cref="HostSystem">HostSystem</see> for details
/// </summary>
public int ExternalFileAttributes
{
get
{
if ((known & Known.ExternalAttributes) == 0)
{
return -1;
}
else
{
return externalFileAttributes;
}
}
set
{
externalFileAttributes = value;
known |= Known.ExternalAttributes;
}
}
/// <summary>
/// Get the version made by for this entry or zero if unknown.
/// The value / 10 indicates the major version number, and
/// the value mod 10 is the minor version number
/// </summary>
public int VersionMadeBy
{
get
{
return (versionMadeBy & 0xff);
}
}
/// <summary>
/// Get a value indicating this entry is for a DOS/Windows system.
/// </summary>
public bool IsDOSEntry
{
get
{
return ((HostSystem == (int)HostSystemID.Msdos) ||
(HostSystem == (int)HostSystemID.WindowsNT));
}
}
/// <summary>
/// Test the external attributes for this <see cref="ZipEntry"/> to
/// see if the external attributes are Dos based (including WINNT and variants)
/// and match the values
/// </summary>
/// <param name="attributes">The attributes to test.</param>
/// <returns>Returns true if the external attributes are known to be DOS/Windows
/// based and have the same attributes set as the value passed.</returns>
private bool HasDosAttributes(int attributes)
{
bool result = false;
if ((known & Known.ExternalAttributes) != 0)
{
result |= (((HostSystem == (int)HostSystemID.Msdos) ||
(HostSystem == (int)HostSystemID.WindowsNT)) &&
(ExternalFileAttributes & attributes) == attributes);
}
return result;
}
/// <summary>
/// Gets the compatability information for the <see cref="ExternalFileAttributes">external file attribute</see>
/// If the external file attributes are compatible with MS-DOS and can be read
/// by PKZIP for DOS version 2.04g then this value will be zero. Otherwise the value
/// will be non-zero and identify the host system on which the attributes are compatible.
/// </summary>
///
/// <remarks>
/// The values for this as defined in the Zip File format and by others are shown below. The values are somewhat
/// misleading in some cases as they are not all used as shown. You should consult the relevant documentation
/// to obtain up to date and correct information. The modified appnote by the infozip group is
/// particularly helpful as it documents a lot of peculiarities. The document is however a little dated.
/// <list type="table">
/// <item>0 - MS-DOS and OS/2 (FAT / VFAT / FAT32 file systems)</item>
/// <item>1 - Amiga</item>
/// <item>2 - OpenVMS</item>
/// <item>3 - Unix</item>
/// <item>4 - VM/CMS</item>
/// <item>5 - Atari ST</item>
/// <item>6 - OS/2 HPFS</item>
/// <item>7 - Macintosh</item>
/// <item>8 - Z-System</item>
/// <item>9 - CP/M</item>
/// <item>10 - Windows NTFS</item>
/// <item>11 - MVS (OS/390 - Z/OS)</item>
/// <item>12 - VSE</item>
/// <item>13 - Acorn Risc</item>
/// <item>14 - VFAT</item>
/// <item>15 - Alternate MVS</item>
/// <item>16 - BeOS</item>
/// <item>17 - Tandem</item>
/// <item>18 - OS/400</item>
/// <item>19 - OS/X (Darwin)</item>
/// <item>99 - WinZip AES</item>
/// <item>remainder - unused</item>
/// </list>
/// </remarks>
public int HostSystem
{
get
{
return (versionMadeBy >> 8) & 0xff;
}
set
{
versionMadeBy &= 0x00ff;
versionMadeBy |= (ushort)((value & 0xff) << 8);
}
}
/// <summary>
/// Get minimum Zip feature version required to extract this entry
/// </summary>
/// <remarks>
/// Minimum features are defined as:<br/>
/// 1.0 - Default value<br/>
/// 1.1 - File is a volume label<br/>
/// 2.0 - File is a folder/directory<br/>
/// 2.0 - File is compressed using Deflate compression<br/>
/// 2.0 - File is encrypted using traditional encryption<br/>
/// 2.1 - File is compressed using Deflate64<br/>
/// 2.5 - File is compressed using PKWARE DCL Implode<br/>
/// 2.7 - File is a patch data set<br/>
/// 4.5 - File uses Zip64 format extensions<br/>
/// 4.6 - File is compressed using BZIP2 compression<br/>
/// 5.0 - File is encrypted using DES<br/>
/// 5.0 - File is encrypted using 3DES<br/>
/// 5.0 - File is encrypted using original RC2 encryption<br/>
/// 5.0 - File is encrypted using RC4 encryption<br/>
/// 5.1 - File is encrypted using AES encryption<br/>
/// 5.1 - File is encrypted using corrected RC2 encryption<br/>
/// 5.1 - File is encrypted using corrected RC2-64 encryption<br/>
/// 6.1 - File is encrypted using non-OAEP key wrapping<br/>
/// 6.2 - Central directory encryption (not confirmed yet)<br/>
/// 6.3 - File is compressed using LZMA<br/>
/// 6.3 - File is compressed using PPMD+<br/>
/// 6.3 - File is encrypted using Blowfish<br/>
/// 6.3 - File is encrypted using Twofish<br/>
/// </remarks>
/// <seealso cref="CanDecompress"></seealso>
public int Version
{
get
{
// Return recorded version if known.
if (versionToExtract != 0)
{
return versionToExtract & 0x00ff; // Only lower order byte. High order is O/S file system.
}
else
{
int result = 10;
if (AESKeySize > 0)
{
result = ZipConstants.VERSION_AES; // Ver 5.1 = AES
}
else if (CentralHeaderRequiresZip64)
{
result = ZipConstants.VersionZip64;
}
else if (CompressionMethod.Deflated == method)
{
result = 20;
}
else if (IsDirectory == true)
{
result = 20;
}
else if (IsCrypted == true)
{
result = 20;
}
else if (HasDosAttributes(0x08))
{
result = 11;
}
return result;
}
}
}
/// <summary>
/// Get a value indicating whether this entry can be decompressed by the library.
/// </summary>
/// <remarks>This is based on the <see cref="Version"></see> and
/// wether the <see cref="IsCompressionMethodSupported()">compression method</see> is supported.</remarks>
public bool CanDecompress
{
get
{
return (Version <= ZipConstants.VersionMadeBy) &&
((Version == 10) ||
(Version == 11) ||
(Version == 20) ||
(Version == 45) ||
(Version == 51)) &&
IsCompressionMethodSupported();
}
}
/// <summary>
/// Force this entry to be recorded using Zip64 extensions.
/// </summary>
public void ForceZip64()
{
forceZip64_ = true;
}
/// <summary>
/// Get a value indicating wether Zip64 extensions were forced.
/// </summary>
/// <returns>A <see cref="bool"/> value of true if Zip64 extensions have been forced on; false if not.</returns>
public bool IsZip64Forced()
{
return forceZip64_;
}
/// <summary>
/// Gets a value indicating if the entry requires Zip64 extensions
/// to store the full entry values.
/// </summary>
/// <value>A <see cref="bool"/> value of true if a local header requires Zip64 extensions; false if not.</value>
public bool LocalHeaderRequiresZip64
{
get
{
bool result = forceZip64_;
if (!result)
{
ulong trueCompressedSize = compressedSize;
if ((versionToExtract == 0) && IsCrypted)
{
trueCompressedSize += ZipConstants.CryptoHeaderSize;
}
// TODO: A better estimation of the true limit based on compression overhead should be used
// to determine when an entry should use Zip64.
result =
((this.size >= uint.MaxValue) || (trueCompressedSize >= uint.MaxValue)) &&
((versionToExtract == 0) || (versionToExtract >= ZipConstants.VersionZip64));
}
return result;
}
}
/// <summary>
/// Get a value indicating wether the central directory entry requires Zip64 extensions to be stored.
/// </summary>
public bool CentralHeaderRequiresZip64
{
get
{
return LocalHeaderRequiresZip64 || (offset >= uint.MaxValue);
}
}
/// <summary>
/// Get/Set DosTime value.
/// </summary>
/// <remarks>
/// The MS-DOS date format can only represent dates between 1/1/1980 and 12/31/2107.
/// </remarks>
public long DosTime
{
get
{
if ((known & Known.Time) == 0)
{
return 0;
}
else
{
return dosTime;
}
}
set
{
unchecked
{
dosTime = (uint)value;
}
known |= Known.Time;
}
}
/// <summary>
/// Gets/Sets the time of last modification of the entry.
/// </summary>
/// <remarks>
/// The <see cref="DosTime"></see> property is updated to match this as far as possible.
/// </remarks>
public DateTime DateTime
{
get
{
uint sec = Math.Min(59, 2 * (dosTime & 0x1f));
uint min = Math.Min(59, (dosTime >> 5) & 0x3f);
uint hrs = Math.Min(23, (dosTime >> 11) & 0x1f);
uint mon = Math.Max(1, Math.Min(12, ((dosTime >> 21) & 0xf)));
uint year = ((dosTime >> 25) & 0x7f) + 1980;
int day = Math.Max(1, Math.Min(DateTime.DaysInMonth((int)year, (int)mon), (int)((dosTime >> 16) & 0x1f)));
return new System.DateTime((int)year, (int)mon, day, (int)hrs, (int)min, (int)sec);
}
set
{
var year = (uint)value.Year;
var month = (uint)value.Month;
var day = (uint)value.Day;
var hour = (uint)value.Hour;
var minute = (uint)value.Minute;
var second = (uint)value.Second;
if (year < 1980)
{
year = 1980;
month = 1;
day = 1;
hour = 0;
minute = 0;
second = 0;
}
else if (year > 2107)
{
year = 2107;
month = 12;
day = 31;
hour = 23;
minute = 59;
second = 59;
}
DosTime = ((year - 1980) & 0x7f) << 25 |
(month << 21) |
(day << 16) |
(hour << 11) |
(minute << 5) |
(second >> 1);
}
}
/// <summary>
/// Returns the entry name.
/// </summary>
/// <remarks>
/// The unix naming convention is followed.
/// Path components in the entry should always separated by forward slashes ('/').
/// Dos device names like C: should also be removed.
/// See the <see cref="ZipNameTransform"/> class, or <see cref="CleanName(string)"/>
///</remarks>
public string Name
{
get
{
return name;
}
}
/// <summary>
/// Gets/Sets the size of the uncompressed data.
/// </summary>
/// <returns>
/// The size or -1 if unknown.
/// </returns>
/// <remarks>Setting the size before adding an entry to an archive can help
/// avoid compatability problems with some archivers which dont understand Zip64 extensions.</remarks>
public long Size
{
get
{
return (known & Known.Size) != 0 ? (long)size : -1L;
}
set
{
this.size = (ulong)value;
this.known |= Known.Size;
}
}
/// <summary>
/// Gets/Sets the size of the compressed data.
/// </summary>
/// <returns>
/// The compressed entry size or -1 if unknown.
/// </returns>
public long CompressedSize
{
get
{
return (known & Known.CompressedSize) != 0 ? (long)compressedSize : -1L;
}
set
{
this.compressedSize = (ulong)value;
this.known |= Known.CompressedSize;
}
}
/// <summary>
/// Gets/Sets the crc of the uncompressed data.
/// </summary>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Crc is not in the range 0..0xffffffffL
/// </exception>
/// <returns>
/// The crc value or -1 if unknown.
/// </returns>
public long Crc
{
get
{
return (known & Known.Crc) != 0 ? crc & 0xffffffffL : -1L;
}
set
{
if (((ulong)crc & 0xffffffff00000000L) != 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
this.crc = (uint)value;
this.known |= Known.Crc;
}
}
/// <summary>
/// Gets/Sets the compression method. Only Deflated and Stored are supported.
/// </summary>
/// <returns>
/// The compression method for this entry
/// </returns>
/// <see cref="ICSharpCode.SharpZipLib.Zip.CompressionMethod.Deflated"/>
/// <see cref="ICSharpCode.SharpZipLib.Zip.CompressionMethod.Stored"/>
public CompressionMethod CompressionMethod
{
get
{
return method;
}
set
{
if (!IsCompressionMethodSupported(value))
{
throw new NotSupportedException("Compression method not supported");
}
this.method = value;
}
}
/// <summary>
/// Gets the compression method for outputting to the local or central header.
/// Returns same value as CompressionMethod except when AES encrypting, which
/// places 99 in the method and places the real method in the extra data.
/// </summary>
internal CompressionMethod CompressionMethodForHeader
{
get
{
return (AESKeySize > 0) ? CompressionMethod.WinZipAES : method;
}
}
/// <summary>
/// Gets/Sets the extra data.
/// </summary>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Extra data is longer than 64KB (0xffff) bytes.
/// </exception>
/// <returns>
/// Extra data or null if not set.
/// </returns>
public byte[] ExtraData
{
get
{
// TODO: This is slightly safer but less efficient. Think about wether it should change.
// return (byte[]) extra.Clone();
return extra;
}
set
{
if (value == null)
{
extra = null;
}
else
{
if (value.Length > 0xffff)
{
throw new System.ArgumentOutOfRangeException(nameof(value));
}
extra = new byte[value.Length];
Array.Copy(value, 0, extra, 0, value.Length);
}
}
}
/// <summary>
/// For AES encrypted files returns or sets the number of bits of encryption (128, 192 or 256).
/// When setting, only 0 (off), 128 or 256 is supported.
/// </summary>
public int AESKeySize
{
get
{
// the strength (1 or 3) is in the entry header
switch (_aesEncryptionStrength)
{
case 0:
return 0; // Not AES
case 1:
return 128;
case 2:
return 192; // Not used by WinZip
case 3:
return 256;
default:
throw new ZipException("Invalid AESEncryptionStrength " + _aesEncryptionStrength);
}
}
set
{
switch (value)
{
case 0:
_aesEncryptionStrength = 0;
break;
case 128:
_aesEncryptionStrength = 1;
break;
case 256:
_aesEncryptionStrength = 3;
break;
default:
throw new ZipException("AESKeySize must be 0, 128 or 256: " + value);
}
}
}
/// <summary>
/// AES Encryption strength for storage in extra data in entry header.
/// 1 is 128 bit, 2 is 192 bit, 3 is 256 bit.
/// </summary>
internal byte AESEncryptionStrength
{
get
{
return (byte)_aesEncryptionStrength;
}
}
/// <summary>
/// Returns the length of the salt, in bytes
/// </summary>
internal int AESSaltLen
{
get
{
// Key size -> Salt length: 128 bits = 8 bytes, 192 bits = 12 bytes, 256 bits = 16 bytes.
return AESKeySize / 16;
}
}
/// <summary>
/// Number of extra bytes required to hold the AES Header fields (Salt, Pwd verify, AuthCode)
/// </summary>
internal int AESOverheadSize
{
get
{
// File format:
// Bytes Content
// Variable Salt value
// 2 Password verification value
// Variable Encrypted file data
// 10 Authentication code
return 12 + AESSaltLen;
}
}
/// <summary>
/// Process extra data fields updating the entry based on the contents.
/// </summary>
/// <param name="localHeader">True if the extra data fields should be handled
/// for a local header, rather than for a central header.
/// </param>
internal void ProcessExtraData(bool localHeader)
{
var extraData = new ZipExtraData(this.extra);
if (extraData.Find(0x0001))
{
// Version required to extract is ignored here as some archivers dont set it correctly
// in theory it should be version 45 or higher
// The recorded size will change but remember that this is zip64.
forceZip64_ = true;
if (extraData.ValueLength < 4)
{
throw new ZipException("Extra data extended Zip64 information length is invalid");
}
// (localHeader ||) was deleted, because actually there is no specific difference with reading sizes between local header & central directory
// https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
// ...
// 4.4 Explanation of fields
// ...
// 4.4.8 compressed size: (4 bytes)
// 4.4.9 uncompressed size: (4 bytes)
//
// The size of the file compressed (4.4.8) and uncompressed,
// (4.4.9) respectively. When a decryption header is present it
// will be placed in front of the file data and the value of the
// compressed file size will include the bytes of the decryption
// header. If bit 3 of the general purpose bit flag is set,
// these fields are set to zero in the local header and the
// correct values are put in the data descriptor and
// in the central directory. If an archive is in ZIP64 format
// and the value in this field is 0xFFFFFFFF, the size will be
// in the corresponding 8 byte ZIP64 extended information
// extra field. When encrypting the central directory, if the
// local header is not in ZIP64 format and general purpose bit
// flag 13 is set indicating masking, the value stored for the
// uncompressed size in the Local Header will be zero.
//
// Othewise there is problem with minizip implementation
if (size == uint.MaxValue)
{
size = (ulong)extraData.ReadLong();
}
if (compressedSize == uint.MaxValue)
{
compressedSize = (ulong)extraData.ReadLong();
}
if (!localHeader && (offset == uint.MaxValue))
{
offset = extraData.ReadLong();
}
// Disk number on which file starts is ignored
}
else
{
if (
((versionToExtract & 0xff) >= ZipConstants.VersionZip64) &&
((size == uint.MaxValue) || (compressedSize == uint.MaxValue))
)
{
throw new ZipException("Zip64 Extended information required but is missing.");
}
}
DateTime = GetDateTime(extraData);
if (method == CompressionMethod.WinZipAES)
{
ProcessAESExtraData(extraData);
}
}
private DateTime GetDateTime(ZipExtraData extraData)
{
// Check for NT timestamp
// NOTE: Disable by default to match behavior of InfoZIP
#if RESPECT_NT_TIMESTAMP
NTTaggedData ntData = extraData.GetData<NTTaggedData>();
if (ntData != null)
return ntData.LastModificationTime;
#endif
// Check for Unix timestamp
ExtendedUnixData unixData = extraData.GetData<ExtendedUnixData>();
if (unixData != null &&
// Only apply modification time, but require all other values to be present
// This is done to match InfoZIP's behaviour
((unixData.Include & ExtendedUnixData.Flags.ModificationTime) != 0) &&
((unixData.Include & ExtendedUnixData.Flags.AccessTime) != 0) &&
((unixData.Include & ExtendedUnixData.Flags.CreateTime) != 0))
return unixData.ModificationTime;
// Fall back to DOS time
uint sec = Math.Min(59, 2 * (dosTime & 0x1f));
uint min = Math.Min(59, (dosTime >> 5) & 0x3f);
uint hrs = Math.Min(23, (dosTime >> 11) & 0x1f);
uint mon = Math.Max(1, Math.Min(12, ((dosTime >> 21) & 0xf)));
uint year = ((dosTime >> 25) & 0x7f) + 1980;
int day = Math.Max(1, Math.Min(DateTime.DaysInMonth((int)year, (int)mon), (int)((dosTime >> 16) & 0x1f)));
return new DateTime((int)year, (int)mon, day, (int)hrs, (int)min, (int)sec, DateTimeKind.Utc);
}
// For AES the method in the entry is 99, and the real compression method is in the extradata
//
private void ProcessAESExtraData(ZipExtraData extraData)
{
if (extraData.Find(0x9901))
{
// Set version for Zipfile.CreateAndInitDecryptionStream
versionToExtract = ZipConstants.VERSION_AES; // Ver 5.1 = AES see "Version" getter
//
// Unpack AES extra data field see http://www.winzip.com/aes_info.htm
int length = extraData.ValueLength; // Data size currently 7
if (length < 7)
throw new ZipException("AES Extra Data Length " + length + " invalid.");
int ver = extraData.ReadShort(); // Version number (1=AE-1 2=AE-2)
int vendorId = extraData.ReadShort(); // 2-character vendor ID 0x4541 = "AE"
int encrStrength = extraData.ReadByte(); // encryption strength 1 = 128 2 = 192 3 = 256
int actualCompress = extraData.ReadShort(); // The actual compression method used to compress the file
_aesVer = ver;
_aesEncryptionStrength = encrStrength;
method = (CompressionMethod)actualCompress;
}
else
throw new ZipException("AES Extra Data missing");
}
/// <summary>
/// Gets/Sets the entry comment.
/// </summary>
/// <exception cref="System.ArgumentOutOfRangeException">
/// If comment is longer than 0xffff.
/// </exception>
/// <returns>
/// The comment or null if not set.
/// </returns>
/// <remarks>
/// A comment is only available for entries when read via the <see cref="ZipFile"/> class.
/// The <see cref="ZipInputStream"/> class doesnt have the comment data available.
/// </remarks>
public string Comment
{
get
{
return comment;
}
set
{
// This test is strictly incorrect as the length is in characters
// while the storage limit is in bytes.
// While the test is partially correct in that a comment of this length or greater
// is definitely invalid, shorter comments may also have an invalid length
// where there are multi-byte characters
// The full test is not possible here however as the code page to apply conversions with
// isnt available.
if ((value != null) && (value.Length > 0xffff))
{
throw new ArgumentOutOfRangeException(nameof(value), "cannot exceed 65535");
}
comment = value;
}
}
/// <summary>
/// Gets a value indicating if the entry is a directory.
/// however.
/// </summary>
/// <remarks>
/// A directory is determined by an entry name with a trailing slash '/'.
/// The external file attributes can also indicate an entry is for a directory.
/// Currently only dos/windows attributes are tested in this manner.
/// The trailing slash convention should always be followed.
/// </remarks>
public bool IsDirectory
{
get
{
int nameLength = name.Length;
bool result =
((nameLength > 0) &&
((name[nameLength - 1] == '/') || (name[nameLength - 1] == '\\'))) ||
HasDosAttributes(16)
;
return result;
}
}
/// <summary>
/// Get a value of true if the entry appears to be a file; false otherwise
/// </summary>
/// <remarks>
/// This only takes account of DOS/Windows attributes. Other operating systems are ignored.
/// For linux and others the result may be incorrect.
/// </remarks>
public bool IsFile
{
get
{
return !IsDirectory && !HasDosAttributes(8);
}
}
/// <summary>
/// Test entry to see if data can be extracted.
/// </summary>
/// <returns>Returns true if data can be extracted for this entry; false otherwise.</returns>
public bool IsCompressionMethodSupported()
{
return IsCompressionMethodSupported(CompressionMethod);
}
#region ICloneable Members
/// <summary>
/// Creates a copy of this zip entry.
/// </summary>
/// <returns>An <see cref="Object"/> that is a copy of the current instance.</returns>
public object Clone()
{
var result = (ZipEntry)this.MemberwiseClone();
// Ensure extra data is unique if it exists.
if (extra != null)
{
result.extra = new byte[extra.Length];
Array.Copy(extra, 0, result.extra, 0, extra.Length);
}
return result;
}
#endregion ICloneable Members
/// <summary>
/// Gets a string representation of this ZipEntry.
/// </summary>
/// <returns>A readable textual representation of this <see cref="ZipEntry"/></returns>
public override string ToString()
{
return name;
}
/// <summary>
/// Test a <see cref="CompressionMethod">compression method</see> to see if this library
/// supports extracting data compressed with that method
/// </summary>
/// <param name="method">The compression method to test.</param>
/// <returns>Returns true if the compression method is supported; false otherwise</returns>
public static bool IsCompressionMethodSupported(CompressionMethod method)
{
return
(method == CompressionMethod.Deflated) ||
(method == CompressionMethod.Stored);
}
/// <summary>
/// Cleans a name making it conform to Zip file conventions.
/// Devices names ('c:\') and UNC share names ('\\server\share') are removed
/// and forward slashes ('\') are converted to back slashes ('/').
/// Names are made relative by trimming leading slashes which is compatible
/// with the ZIP naming convention.
/// </summary>
/// <param name="name">The name to clean</param>
/// <returns>The 'cleaned' name.</returns>
/// <remarks>
/// The <seealso cref="ZipNameTransform">Zip name transform</seealso> class is more flexible.
/// </remarks>
public static string CleanName(string name)
{
if (name == null)
{
return string.Empty;
}
if (Path.IsPathRooted(name))
{
// NOTE:
// for UNC names... \\machine\share\zoom\beet.txt gives \zoom\beet.txt
name = name.Substring(Path.GetPathRoot(name).Length);
}
name = name.Replace(@"\", "/");
while ((name.Length > 0) && (name[0] == '/'))
{
name = name.Remove(0, 1);
}
return name;
}
#region Instance Fields
private Known known;
private int externalFileAttributes = -1; // contains external attributes (O/S dependant)
private ushort versionMadeBy; // Contains host system and version information
// only relevant for central header entries
private string name;
private ulong size;
private ulong compressedSize;
private ushort versionToExtract; // Version required to extract (library handles <= 2.0)
private uint crc;
private uint dosTime;
private CompressionMethod method = CompressionMethod.Deflated;
private byte[] extra;
private string comment;
private int flags; // general purpose bit flags
private long zipFileIndex = -1; // used by ZipFile
private long offset; // used by ZipFile and ZipOutputStream
private bool forceZip64_;
private byte cryptoCheckValue_;
private int _aesVer; // Version number (2 = AE-2 ?). Assigned but not used.
private int _aesEncryptionStrength; // Encryption strength 1 = 128 2 = 192 3 = 256
#endregion Instance Fields
}
}
| |
//
// PkzipClassic encryption
//
// Copyright 2004 John Reilly
//
// 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.
//
#if !NETCF_1_0
using System;
using System.Security.Cryptography;
using GitHub.ICSharpCode.SharpZipLib.Checksums;
namespace GitHub.ICSharpCode.SharpZipLib.Encryption
{
/// <summary>
/// PkzipClassic embodies the classic or original encryption facilities used in Pkzip archives.
/// While it has been superceded by more recent and more powerful algorithms, its still in use and
/// is viable for preventing casual snooping
/// </summary>
public abstract class PkzipClassic : SymmetricAlgorithm
{
/// <summary>
/// Generates new encryption keys based on given seed
/// </summary>
/// <param name="seed">The seed value to initialise keys with.</param>
/// <returns>A new key value.</returns>
static public byte[] GenerateKeys(byte[] seed)
{
if ( seed == null ) {
throw new ArgumentNullException("seed");
}
if ( seed.Length == 0 ) {
throw new ArgumentException("Length is zero", "seed");
}
uint[] newKeys = new uint[] {
0x12345678,
0x23456789,
0x34567890
};
for (int i = 0; i < seed.Length; ++i) {
newKeys[0] = Crc32.ComputeCrc32(newKeys[0], seed[i]);
newKeys[1] = newKeys[1] + (byte)newKeys[0];
newKeys[1] = newKeys[1] * 134775813 + 1;
newKeys[2] = Crc32.ComputeCrc32(newKeys[2], (byte)(newKeys[1] >> 24));
}
byte[] result = new byte[12];
result[0] = (byte)(newKeys[0] & 0xff);
result[1] = (byte)((newKeys[0] >> 8) & 0xff);
result[2] = (byte)((newKeys[0] >> 16) & 0xff);
result[3] = (byte)((newKeys[0] >> 24) & 0xff);
result[4] = (byte)(newKeys[1] & 0xff);
result[5] = (byte)((newKeys[1] >> 8) & 0xff);
result[6] = (byte)((newKeys[1] >> 16) & 0xff);
result[7] = (byte)((newKeys[1] >> 24) & 0xff);
result[8] = (byte)(newKeys[2] & 0xff);
result[9] = (byte)((newKeys[2] >> 8) & 0xff);
result[10] = (byte)((newKeys[2] >> 16) & 0xff);
result[11] = (byte)((newKeys[2] >> 24) & 0xff);
return result;
}
}
/// <summary>
/// PkzipClassicCryptoBase provides the low level facilities for encryption
/// and decryption using the PkzipClassic algorithm.
/// </summary>
class PkzipClassicCryptoBase
{
/// <summary>
/// Transform a single byte
/// </summary>
/// <returns>
/// The transformed value
/// </returns>
protected byte TransformByte()
{
uint temp = ((keys[2] & 0xFFFF) | 2);
return (byte)((temp * (temp ^ 1)) >> 8);
}
/// <summary>
/// Set the key schedule for encryption/decryption.
/// </summary>
/// <param name="keyData">The data use to set the keys from.</param>
protected void SetKeys(byte[] keyData)
{
if ( keyData == null ) {
throw new ArgumentNullException("keyData");
}
if ( keyData.Length != 12 ) {
throw new InvalidOperationException("Key length is not valid");
}
keys = new uint[3];
keys[0] = (uint)((keyData[3] << 24) | (keyData[2] << 16) | (keyData[1] << 8) | keyData[0]);
keys[1] = (uint)((keyData[7] << 24) | (keyData[6] << 16) | (keyData[5] << 8) | keyData[4]);
keys[2] = (uint)((keyData[11] << 24) | (keyData[10] << 16) | (keyData[9] << 8) | keyData[8]);
}
/// <summary>
/// Update encryption keys
/// </summary>
protected void UpdateKeys(byte ch)
{
keys[0] = Crc32.ComputeCrc32(keys[0], ch);
keys[1] = keys[1] + (byte)keys[0];
keys[1] = keys[1] * 134775813 + 1;
keys[2] = Crc32.ComputeCrc32(keys[2], (byte)(keys[1] >> 24));
}
/// <summary>
/// Reset the internal state.
/// </summary>
protected void Reset()
{
keys[0] = 0;
keys[1] = 0;
keys[2] = 0;
}
#region Instance Fields
uint[] keys;
#endregion
}
/// <summary>
/// PkzipClassic CryptoTransform for encryption.
/// </summary>
class PkzipClassicEncryptCryptoTransform : PkzipClassicCryptoBase, ICryptoTransform
{
/// <summary>
/// Initialise a new instance of <see cref="PkzipClassicEncryptCryptoTransform"></see>
/// </summary>
/// <param name="keyBlock">The key block to use.</param>
internal PkzipClassicEncryptCryptoTransform(byte[] keyBlock)
{
SetKeys(keyBlock);
}
#region ICryptoTransform Members
/// <summary>
/// Transforms the specified region of the specified byte array.
/// </summary>
/// <param name="inputBuffer">The input for which to compute the transform.</param>
/// <param name="inputOffset">The offset into the byte array from which to begin using data.</param>
/// <param name="inputCount">The number of bytes in the byte array to use as data.</param>
/// <returns>The computed transform.</returns>
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
byte[] result = new byte[inputCount];
TransformBlock(inputBuffer, inputOffset, inputCount, result, 0);
return result;
}
/// <summary>
/// Transforms the specified region of the input byte array and copies
/// the resulting transform to the specified region of the output byte array.
/// </summary>
/// <param name="inputBuffer">The input for which to compute the transform.</param>
/// <param name="inputOffset">The offset into the input byte array from which to begin using data.</param>
/// <param name="inputCount">The number of bytes in the input byte array to use as data.</param>
/// <param name="outputBuffer">The output to which to write the transform.</param>
/// <param name="outputOffset">The offset into the output byte array from which to begin writing data.</param>
/// <returns>The number of bytes written.</returns>
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
for (int i = inputOffset; i < inputOffset + inputCount; ++i) {
byte oldbyte = inputBuffer[i];
outputBuffer[outputOffset++] = (byte)(inputBuffer[i] ^ TransformByte());
UpdateKeys(oldbyte);
}
return inputCount;
}
/// <summary>
/// Gets a value indicating whether the current transform can be reused.
/// </summary>
public bool CanReuseTransform
{
get {
return true;
}
}
/// <summary>
/// Gets the size of the input data blocks in bytes.
/// </summary>
public int InputBlockSize
{
get {
return 1;
}
}
/// <summary>
/// Gets the size of the output data blocks in bytes.
/// </summary>
public int OutputBlockSize
{
get {
return 1;
}
}
/// <summary>
/// Gets a value indicating whether multiple blocks can be transformed.
/// </summary>
public bool CanTransformMultipleBlocks
{
get {
return true;
}
}
#endregion
#region IDisposable Members
/// <summary>
/// Cleanup internal state.
/// </summary>
public void Dispose()
{
Reset();
}
#endregion
}
/// <summary>
/// PkzipClassic CryptoTransform for decryption.
/// </summary>
class PkzipClassicDecryptCryptoTransform : PkzipClassicCryptoBase, ICryptoTransform
{
/// <summary>
/// Initialise a new instance of <see cref="PkzipClassicDecryptCryptoTransform"></see>.
/// </summary>
/// <param name="keyBlock">The key block to decrypt with.</param>
internal PkzipClassicDecryptCryptoTransform(byte[] keyBlock)
{
SetKeys(keyBlock);
}
#region ICryptoTransform Members
/// <summary>
/// Transforms the specified region of the specified byte array.
/// </summary>
/// <param name="inputBuffer">The input for which to compute the transform.</param>
/// <param name="inputOffset">The offset into the byte array from which to begin using data.</param>
/// <param name="inputCount">The number of bytes in the byte array to use as data.</param>
/// <returns>The computed transform.</returns>
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
byte[] result = new byte[inputCount];
TransformBlock(inputBuffer, inputOffset, inputCount, result, 0);
return result;
}
/// <summary>
/// Transforms the specified region of the input byte array and copies
/// the resulting transform to the specified region of the output byte array.
/// </summary>
/// <param name="inputBuffer">The input for which to compute the transform.</param>
/// <param name="inputOffset">The offset into the input byte array from which to begin using data.</param>
/// <param name="inputCount">The number of bytes in the input byte array to use as data.</param>
/// <param name="outputBuffer">The output to which to write the transform.</param>
/// <param name="outputOffset">The offset into the output byte array from which to begin writing data.</param>
/// <returns>The number of bytes written.</returns>
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
for (int i = inputOffset; i < inputOffset + inputCount; ++i) {
byte newByte = (byte)(inputBuffer[i] ^ TransformByte());
outputBuffer[outputOffset++] = newByte;
UpdateKeys(newByte);
}
return inputCount;
}
/// <summary>
/// Gets a value indicating whether the current transform can be reused.
/// </summary>
public bool CanReuseTransform
{
get {
return true;
}
}
/// <summary>
/// Gets the size of the input data blocks in bytes.
/// </summary>
public int InputBlockSize
{
get {
return 1;
}
}
/// <summary>
/// Gets the size of the output data blocks in bytes.
/// </summary>
public int OutputBlockSize
{
get {
return 1;
}
}
/// <summary>
/// Gets a value indicating whether multiple blocks can be transformed.
/// </summary>
public bool CanTransformMultipleBlocks
{
get {
return true;
}
}
#endregion
#region IDisposable Members
/// <summary>
/// Cleanup internal state.
/// </summary>
public void Dispose()
{
Reset();
}
#endregion
}
/// <summary>
/// Defines a wrapper object to access the Pkzip algorithm.
/// This class cannot be inherited.
/// </summary>
public sealed class PkzipClassicManaged : PkzipClassic
{
/// <summary>
/// Get / set the applicable block size in bits.
/// </summary>
/// <remarks>The only valid block size is 8.</remarks>
public override int BlockSize
{
get {
return 8;
}
set {
if (value != 8) {
throw new CryptographicException("Block size is invalid");
}
}
}
/// <summary>
/// Get an array of legal <see cref="KeySizes">key sizes.</see>
/// </summary>
public override KeySizes[] LegalKeySizes
{
get {
KeySizes[] keySizes = new KeySizes[1];
keySizes[0] = new KeySizes(12 * 8, 12 * 8, 0);
return keySizes;
}
}
/// <summary>
/// Generate an initial vector.
/// </summary>
public override void GenerateIV()
{
// Do nothing.
}
/// <summary>
/// Get an array of legal <see cref="KeySizes">block sizes</see>.
/// </summary>
public override KeySizes[] LegalBlockSizes
{
get {
KeySizes[] keySizes = new KeySizes[1];
keySizes[0] = new KeySizes(1 * 8, 1 * 8, 0);
return keySizes;
}
}
/// <summary>
/// Get / set the key value applicable.
/// </summary>
public override byte[] Key
{
get {
if ( key_ == null ) {
GenerateKey();
}
return (byte[]) key_.Clone();
}
set {
if ( value == null ) {
throw new ArgumentNullException("value");
}
if ( value.Length != 12 ) {
throw new CryptographicException("Key size is illegal");
}
key_ = (byte[]) value.Clone();
}
}
/// <summary>
/// Generate a new random key.
/// </summary>
public override void GenerateKey()
{
key_ = new byte[12];
Random rnd = new Random();
rnd.NextBytes(key_);
}
/// <summary>
/// Create an encryptor.
/// </summary>
/// <param name="rgbKey">The key to use for this encryptor.</param>
/// <param name="rgbIV">Initialisation vector for the new encryptor.</param>
/// <returns>Returns a new PkzipClassic encryptor</returns>
public override ICryptoTransform CreateEncryptor(
byte[] rgbKey,
byte[] rgbIV)
{
key_ = rgbKey;
return new PkzipClassicEncryptCryptoTransform(Key);
}
/// <summary>
/// Create a decryptor.
/// </summary>
/// <param name="rgbKey">Keys to use for this new decryptor.</param>
/// <param name="rgbIV">Initialisation vector for the new decryptor.</param>
/// <returns>Returns a new decryptor.</returns>
public override ICryptoTransform CreateDecryptor(
byte[] rgbKey,
byte[] rgbIV)
{
key_ = rgbKey;
return new PkzipClassicDecryptCryptoTransform(Key);
}
#region Instance Fields
byte[] key_;
#endregion
}
}
#endif
| |
using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Vevo;
using Vevo.DataAccessLib;
using Vevo.Domain;
using Vevo.Domain.Base;
using Vevo.Domain.Configurations;
using Vevo.Domain.Stores;
using Vevo.Shared.Utilities;
using Vevo.WebAppLib;
using Vevo.WebUI;
using Vevo.Shared.DataAccess;
public partial class AdminAdvanced_MainControls_SearchConfigurationResult : AdminAdvancedBaseUserControl
{
#region Private
private const string _pathUpload = "Images/Configuration/";
private string[] excludeFreeConfig = { "BundlePromotionShow","BundlePromotionDisplay","BundlePromotionColumn",
"GiftRegistryModuleDisplay","EnableBundlePromo",
"ThubLogEnabled","eBayConfigAppID","eBayConfigCertID","eBayConfigDevID",
"eBayConfigToken","eBayConfigListingMode","AffiliateEnabled",
"AffiliateAutoApprove","AffiliateReference","AffiliateExpirePeriod",
"AffiliateCommissionRate","AffiliateDefaultPaidBalance","PointSystemEnabled",
"RewardPoints","PointValue","WebServiceAdminUser"};
private bool IsExcludeConfigInFree( string name )
{
foreach (string config in excludeFreeConfig)
{
if (config == name)
return true;
}
return false;
}
private string CurrentSearch
{
get
{
return MainContext.QueryString["Search"];
}
}
private string CurrentStore
{
get
{
if (!KeyUtilities.IsMultistoreLicense() )
{
return "1";
}
return MainContext.QueryString["Store"];
}
}
private string RedirectURL
{
get
{
return MainContext.QueryString["RedirectURL"];
}
}
private DropDownList CreateDropDownList( Configuration config )
{
DropDownList uxDropDownList = ConfigurationControlBuilder.CreateDropDownList( config, CurrentStore );
IList<Configuration> list
= DataAccessContext.ConfigurationRepository.GetByEnablerConfigName( config.Name );
if (config.ChildConfigurations.Count > 0 || list.Count > 0)
{
uxDropDownList.SelectedIndexChanged += new EventHandler( DropDownControl_SelectedIndexChanged );
uxDropDownList.AutoPostBack = true;
}
if (config.EnablerConfigName != "")
{
if (!Store.CanUseMultiStoreConfig( config.EnablerConfigName ))
{
uxDropDownList.Enabled = DataAccessContext.Configurations.GetBoolValue( config.EnablerConfigName );
}
else
{
uxDropDownList.Enabled = DataAccessContext.Configurations.GetBoolValue(
config.EnablerConfigName, DataAccessContext.StoreRepository.GetOne( CurrentStore ) );
}
}
return uxDropDownList;
}
private void CreateUploadPanel( Configuration config )
{
Panel uploadPanel = new Panel();
string clientID = "";
Panel panelControl = (Panel) uxPlaceHolder.FindControl( config.Name + "UploadPanel" );
if (panelControl != null)
{
TextBox textbox = (TextBox) panelControl.FindControl( config.Name );
if (textbox != null)
clientID = textbox.ClientID;
}
panelControl.Controls.Add( CreateUploadControl( config, clientID ) );
panelControl.Controls.Add( CreateLinkButton( config ) );
}
private AdminAdvanced_Components_Common_Upload CreateUploadControl(
Configuration config,
string textBoxClientID )
{
AdminAdvanced_Components_Common_Upload controlUpload =
LoadControl( "../Components/Common/Upload.ascx" ) as AdminAdvanced_Components_Common_Upload;
controlUpload.ID = config.Name + "Upload";
controlUpload.PathDestination = _pathUpload;
controlUpload.ButtonImage = "SelectImages.png";
controlUpload.ShowControl = false;
controlUpload.CssClass = "ConfigRow";
controlUpload.CheckType = UploadFileType.Image;
// controlUpload.LeftLabelClass = "Label";
controlUpload.ButtonWidth = new Unit( 105 );
controlUpload.ButtonHeight = new Unit( 20 );
controlUpload.ShowText = false;
controlUpload.ReturnTextControlClientID = textBoxClientID;
return controlUpload;
}
private LinkButton CreateLinkButton( Vevo.Domain.Configurations.Configuration config )
{
LinkButton linkButtonControl = new LinkButton();
linkButtonControl.ID = config.Name + "LinkButton";
linkButtonControl.OnClientClick = "UploadButtonClick_Command";
linkButtonControl.Text = "Upload...";
linkButtonControl.CssClass = "fl mgl5";
linkButtonControl.CommandArgument = config.Name;
linkButtonControl.Command += new CommandEventHandler( UploadButtonClick_Command );
return linkButtonControl;
}
private void UploadButtonClick_Command( object sender, CommandEventArgs e )
{
AdminAdvanced_Components_Common_Upload controlUpload
= uxPlaceHolder.FindControl( e.CommandArgument.ToString() + "Upload" ) as AdminAdvanced_Components_Common_Upload;
controlUpload.ShowControl = true;
LinkButton linkButtonControl
= (LinkButton) uxPlaceHolder.FindControl( e.CommandArgument.ToString() + "LinkButton" );
linkButtonControl.Visible = false;
}
private Panel CreateChildPanel( Configuration parentConfig, Configuration childConfig )
{
Panel childPanel = new Panel();
childPanel.ID = childConfig.Name + "Panel";
childPanel.CssClass = "ConfigRow";
AdminAdvanced_Components_Common_HelpIcon helpIcon
= LoadControl( "../Components/Common/HelpIcon.ascx" ) as AdminAdvanced_Components_Common_HelpIcon;
helpIcon.ID = childConfig.Name + "Help";
helpIcon.ConfigName = childConfig.Name;
childPanel.Controls.Add( helpIcon );
childPanel.Controls.Add(
ConfigurationControlBuilder.CreateLabel(
childConfig.Descriptions[0].DisplayName, "BulletLabel" ) );
if (ConfigurationControlBuilder.IsSpecialType( childConfig.Name ))
{
childPanel.Controls.Add(
ConfigurationControlBuilder.GetControl( childConfig, CurrentStore ) );
}
else
{
switch (childConfig.ConfigType)
{
case Configuration.ConfigurationType.DropDown:
childPanel.Controls.Add( CreateDropDownList( childConfig ) );
break;
case Configuration.ConfigurationType.TextBox:
childPanel.Controls.Add(
ConfigurationControlBuilder.CreateTextBox( childConfig, CurrentStore ) );
childPanel.Controls.Add( ConfigurationControlBuilder.CreateValidatorPanel( childConfig ) );
break;
}
}
childPanel.Visible = ConvertUtilities.ToBoolean( parentConfig.Values[0].ItemValue );
return childPanel;
}
private Panel CreateNewConfigPanel( Configuration config )
{
Panel panel = new Panel();
panel.CssClass = "ConfigRow";
panel.ID = config.Name + "Panel";
panel.Visible = true;
return panel;
}
private void AddNormalConfigPanel( PlaceHolder placeHolder, Configuration config )
{
Panel panel = CreateNewConfigPanel( config );
AdminAdvanced_Components_Common_HelpIcon helpIcon
= LoadControl( "../Components/Common/HelpIcon.ascx" ) as AdminAdvanced_Components_Common_HelpIcon;
helpIcon.ID = config.Name + "Help";
helpIcon.ConfigName = config.Name;
panel.Controls.Add( helpIcon );
panel.Controls.Add( ConfigurationControlBuilder.CreateLabel(
config.Descriptions[0].DisplayName, "Label" ) );
switch (config.ConfigType)
{
case Configuration.ConfigurationType.DropDown:
if (!ConfigurationControlBuilder.IsSpecialType( config.Name ))
panel.Controls.Add( CreateDropDownList( config ) );
else
panel.Controls.Add( ConfigurationControlBuilder.GetControl( config, CurrentStore ) );
placeHolder.Controls.Add( panel );
break;
case Configuration.ConfigurationType.TextBox:
panel.Controls.Add( ConfigurationControlBuilder.CreateTextBox( config, CurrentStore ) );
panel.Controls.Add( ConfigurationControlBuilder.CreateValidatorPanel( config ) );
placeHolder.Controls.Add( panel );
break;
case Configuration.ConfigurationType.RadioButton:
panel.Controls.Add( ConfigurationControlBuilder.CreateRadioButtonList( config, CurrentStore ) );
placeHolder.Controls.Add( panel );
break;
case Configuration.ConfigurationType.Upload:
TextBox textBoxUploadControl
= ConfigurationControlBuilder.CreateTextBox( config, CurrentStore, 210 );
panel.Controls.Add( textBoxUploadControl );
panel.ID = config.Name + "UploadPanel";
placeHolder.Controls.Add( panel );
CreateUploadPanel( config );
break;
}
if (config.ChildConfigurations.Count > 0)
{
foreach (Configuration childConfig in config.ChildConfigurations)
{
placeHolder.Controls.Add( CreateChildPanel( config, childConfig ) );
}
}
}
private void PopulateControls()
{
uxSearchTitle.Text = "Configuration result from keyword : " + CurrentSearch;
uxPlaceHolder.Controls.Clear();
IList<Configuration> list = DataAccessContext.ConfigurationRepository.SearchConfiguration(
AdminConfig.CurrentCulture,
"Configuration.ConfigID",
CurrentSearch,
StringUtilities.SplitString( ConfigurationDescription.ConfigurationSearchBy, ',' ) );
if (list.Count > 0)
{
int countConfig = 0;
foreach (Configuration item in list)
{
if (IsExcludeConfigInFree( item.Name ) && !KeyUtilities.IsDeluxeLicense( DataAccessHelper.DomainRegistrationkey, DataAccessHelper.DomainName ))
continue;
if ((!Store.CanUseMultiStoreConfig( item.Name ) && CurrentStore.Equals( "0" )) ||
(Store.CanUseMultiStoreConfig( item.Name ) && !CurrentStore.Equals( "0" )))
{
if (ConfigurationControlBuilder.IsSpecialType( item.Name ))
{
Panel panel = CreateNewConfigPanel( item );
AdminAdvanced_Components_Common_HelpIcon helpIcon
= LoadControl( "../Components/Common/HelpIcon.ascx" ) as AdminAdvanced_Components_Common_HelpIcon;
helpIcon.ID = item.Name + "Help";
helpIcon.ConfigName = item.Name;
panel.Controls.Add( helpIcon );
panel.Controls.Add( ConfigurationControlBuilder.CreateLabel(
item.Descriptions[0].DisplayName, "Label" ) );
panel.Controls.Add( ConfigurationControlBuilder.GetControl( item, CurrentStore ) );
uxPlaceHolder.Controls.Add( panel );
}
else if (item.ConfigType == Configuration.ConfigurationType.UserControl)
{
Panel panel = CreateNewConfigPanel( item );
UserControl control = (UserControl) LoadControl( "../" + item.DisplayUserControl );
control.ID = item.Name;
//"WidgetAddThisIsEnabled","WidgetLivePersonIsEnabled"
//This control need to set some property before populate control
if (ConfigurationControlBuilder.IsSpecialUserControl( item.Name ))
{
Admin_Components_SiteConfig_WidgetDetails widgetDetailsControl
= (Admin_Components_SiteConfig_WidgetDetails) control;
string name = String.Empty;
if (item.Name.Contains( "AddThis" ))
{
widgetDetailsControl.ParameterName = "AddThis Username";
widgetDetailsControl.WidgetStyle = "AddThis";
}
else if (item.Name.Contains( "LivePerson" ))
{
widgetDetailsControl.ParameterName = "LivePerson Account";
widgetDetailsControl.WidgetStyle = "LivePerson";
}
else if (item.Name.Contains( "LikeBox" ))
{
widgetDetailsControl.ParameterName = "Fanpage URL";
widgetDetailsControl.WidgetStyle = "LikeBox";
}
}
panel.Controls.Add( control );
uxPlaceHolder.Controls.Add( panel );
// Need to add dynamic controls after adding parent controls to place holder.
// Otherwise, the dynamic controls' ClientID may not be correct
// (e.g. Parent_uxDynmaic instead of uxFront_uxDiv_Parent_uxDynamic).
// If this happens, view state for the dynamic control will not be restored correctly.
((IConfigUserControl) control).Populate( item );
}
else
{
// Normal configurations (non-special, non-user-control)
AddNormalConfigPanel( uxPlaceHolder, item );
}
countConfig++;
}
}
if (countConfig == 0)
{
uxUpdateButton.Visible = false;
}
}
else
{
uxUpdateButton.Visible = false;
}
}
#endregion
#region Protected
protected void Page_Load( object sender, EventArgs e )
{
PopulateControls();
}
protected void Page_PreRender( object sender, EventArgs e )
{
if (!IsAdminModifiable())
{
uxUpdateButton.Visible = false;
}
}
protected void DropDownControl_SelectedIndexChanged( object sender, EventArgs e )
{
DropDownList sourceDropDownList = sender as DropDownList;
if (sourceDropDownList != null)
{
string dropDownName = sourceDropDownList.ID;
if (DataAccessContext.Configurations[dropDownName].ChildConfigurations.Count > 0)
{
foreach (Configuration childConfig
in DataAccessContext.Configurations[dropDownName].ChildConfigurations)
{
Control childControl = uxPlaceHolder.FindControl( childConfig.Name + "Panel" );
childControl.Visible = ConvertUtilities.ToBoolean( sourceDropDownList.SelectedValue );
}
}
IList<Configuration> list
= DataAccessContext.ConfigurationRepository.GetByEnablerConfigName( dropDownName );
if (list != null)
{
foreach (Configuration item in list)
{
DropDownList dropdown = (DropDownList) uxPlaceHolder.FindControl( item.Name );
if (dropdown != null)
{
dropdown.SelectedValue = sourceDropDownList.SelectedValue;
dropdown.Enabled = ConvertUtilities.ToBoolean( sourceDropDownList.SelectedValue );
}
}
}
}
}
protected void uxBackButton_Click( object sender, EventArgs e )
{
if (RedirectURL.Equals( "SiteConfig.ascx" ))
{
MainContext.RedirectMainControl( RedirectURL );
}
else if (RedirectURL.Equals( "StoreConfig.ascx" ))
{
MainContext.RedirectMainControl( RedirectURL, String.Format( "StoreID={0}", CurrentStore ) );
}
}
protected void uxUpdateButton_Click( object sender, EventArgs e )
{
ConfigurationCollection configurations = DataAccessContext.Configurations;
Store store = DataAccessContext.StoreRepository.GetOne( CurrentStore );
try
{
foreach (Control control in uxPlaceHolder.Controls)
{
if (control is Panel)
{
Panel panelControl = (Panel) control;
foreach (Control controlItem in panelControl.Controls)
{
if (controlItem is TextBox)
{
TextBox textBox = (TextBox) controlItem;
if (configurations.ContainsKey( textBox.ID ))
DataAccessContext.ConfigurationRepository.UpdateValue(
configurations[textBox.ID], textBox.Text, store );
}
else if (controlItem is DropDownList)
{
DropDownList dropdown = (DropDownList) controlItem;
if (ConfigurationControlBuilder.IsSpecialType( dropdown.ID ))
{
ConfigurationControlBuilder.UpdateControlSpecialType( dropdown.ID, dropdown.SelectedValue.ToString() );
}
else
{
if (configurations.ContainsKey( dropdown.ID ))
DataAccessContext.ConfigurationRepository.UpdateValue(
configurations[dropdown.ID], dropdown.SelectedValue.ToString(), store );
}
}
else if (controlItem is RadioButtonList)
{
RadioButtonList radioButton = (RadioButtonList) controlItem;
if (configurations.ContainsKey( radioButton.ID ))
DataAccessContext.ConfigurationRepository.UpdateValue(
configurations[radioButton.ID], radioButton.SelectedValue.ToString(), store );
}
else if (controlItem is UserControl)
{
if (configurations.ContainsKey( controlItem.ID ))
((IConfigUserControl) controlItem).Update();
}
}
}
}
SystemConfig.Load();
uxMessage.DisplayMessage( Resources.SetupMessages.UpdateSuccess );
PopulateControls();
}
catch (Exception ex)
{
// uxMessage.ClearMessage();
uxMessage.DisplayException( ex );
}
}
#endregion
}
| |
//******************************************************************************************************************************************************************************************//
// Public Domain //
// //
// Written by Peter O. in 2014. //
// //
// Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ //
// //
// If you like this, you should donate to Peter O. at: http://peteroupc.github.io/ //
//******************************************************************************************************************************************************************************************//
using System;
using System.Text;
namespace Neos.IdentityServer.MultiFactor.WebAuthN.Library.Cbor.Numbers
{
internal static class EIntegerTextString {
private const int ShortMask = 0xffff;
public static EInteger FromRadixSubstringImpl(
string cs,
int radix,
int index,
int endIndex,
bool throwException) {
if (radix < 2) {
if (!throwException) {
return null;
} else {
throw new ArgumentException("radix(" + radix + ") is less than 2");
}
}
if (radix > 36) {
if (!throwException) {
return null;
} else {
throw new ArgumentException("radix(" + radix + ") is more than 36");
}
}
if (index < 0) {
if (!throwException) {
return null;
} else {
throw new ArgumentException("index(" + index + ") is less than " + "0");
}
}
if (index > cs.Length) {
if (!throwException) {
return null;
} else {
throw new ArgumentException("index(" + index + ") is more than " + cs.Length);
}
}
if (endIndex < 0) {
if (!throwException) {
return null;
} else {
throw new ArgumentException("endIndex(" + endIndex + ") is less than 0");
}
}
if (endIndex > cs.Length) {
if (!throwException) {
return null;
} else {
throw new ArgumentException("endIndex(" + endIndex + ") is more than " +
cs.Length);
}
}
if (endIndex < index) {
if (!throwException) {
return null;
} else {
throw new ArgumentException("endIndex(" + endIndex + ") is less than " +
index);
}
}
if (index == endIndex) {
if (!throwException) {
return null;
} else {
throw new FormatException("No digits");
}
}
var negative = false;
if (cs[index] == '-') {
++index;
if (index == endIndex) {
if (!throwException) {
return null;
} else {
throw new FormatException("No digits");
}
}
negative = true;
}
// Skip leading zeros
for (; index < endIndex; ++index) {
char c = cs[index];
if (c != 0x30) {
break;
}
}
int effectiveLength = endIndex - index;
if (effectiveLength == 0) {
return EInteger.Zero;
}
int[] c2d = EInteger.CharToDigit;
short[] bigint;
if (radix == 16) {
// Special case for hexadecimal radix
int leftover = effectiveLength & 3;
int wordCount = effectiveLength >> 2;
if (leftover != 0) {
++wordCount;
}
bigint = new short[wordCount];
int currentDigit = wordCount - 1;
// Get most significant digits if effective
// length is not divisible by 4
if (leftover != 0) {
var extraWord = 0;
for (int i = 0; i < leftover; ++i) {
extraWord <<= 4;
char c = cs[index + i];
int digit = (c >= 0x80) ? 36 : c2d[(int)c];
if (digit >= 16) {
if (!throwException) {
return null;
} else {
throw new FormatException("Illegal character found");
}
}
extraWord |= digit;
}
bigint[currentDigit] = unchecked((short)extraWord);
--currentDigit;
index += leftover;
}
#if DEBUG
if ((endIndex - index) % 4 != 0) {
if (!throwException) {
return null;
} else {
throw new InvalidOperationException("doesn't satisfy (endIndex - index) %" +
"\u00204 == 0");
}
}
#endif
while (index < endIndex) {
char c = cs[index + 3];
int digit = (c >= 0x80) ? 36 : c2d[(int)c];
if (digit >= 16) {
if (!throwException) {
return null;
} else {
throw new FormatException("Illegal character found");
}
}
int word = digit;
c = cs[index + 2];
digit = (c >= 0x80) ? 36 : c2d[(int)c];
if (digit >= 16) {
if (!throwException) {
return null;
} else {
throw new FormatException("Illegal character found");
}
}
word |= digit << 4;
c = cs[index + 1];
digit = (c >= 0x80) ? 36 : c2d[(int)c];
if (digit >= 16) {
if (!throwException) {
return null;
} else {
throw new FormatException("Illegal character found");
}
}
word |= digit << 8;
c = cs[index];
digit = (c >= 0x80) ? 36 : c2d[(int)c];
if (digit >= 16) {
if (!throwException) {
return null;
} else {
throw new FormatException("Illegal character found");
}
}
word |= digit << 12;
index += 4;
bigint[currentDigit] = unchecked((short)word);
--currentDigit;
}
int count = EInteger.CountWords(bigint);
return (count == 0) ? EInteger.Zero : new EInteger(
count,
bigint,
negative);
} else if (radix == 2) {
// Special case for binary radix
int leftover = effectiveLength & 15;
int wordCount = effectiveLength >> 4;
if (leftover != 0) {
++wordCount;
}
bigint = new short[wordCount];
int currentDigit = wordCount - 1;
// Get most significant digits if effective
// length is not divisible by 4
if (leftover != 0) {
var extraWord = 0;
for (int i = 0; i < leftover; ++i) {
extraWord <<= 1;
char c = cs[index + i];
int digit = (c == '0') ? 0 : ((c == '1') ? 1 : 2);
if (digit >= 2) {
if (!throwException) {
return null;
} else {
throw new FormatException("Illegal character found");
}
}
extraWord |= digit;
}
bigint[currentDigit] = unchecked((short)extraWord);
--currentDigit;
index += leftover;
}
while (index < endIndex) {
var word = 0;
int idx = index + 15;
for (var i = 0; i < 16; ++i) {
char c = cs[idx];
int digit = (c == '0') ? 0 : ((c == '1') ? 1 : 2);
if (digit >= 2) {
if (!throwException) {
return null;
} else {
throw new FormatException("Illegal character found");
}
}
--idx;
word |= digit << i;
}
index += 16;
bigint[currentDigit] = unchecked((short)word);
--currentDigit;
}
int count = EInteger.CountWords(bigint);
return (count == 0) ? EInteger.Zero : new EInteger(
count,
bigint,
negative);
} else {
return FromRadixSubstringGeneral(
cs,
radix,
index,
endIndex,
negative,
throwException);
}
}
private static EInteger FromRadixSubstringGeneral(
string cs,
int radix,
int index,
int endIndex,
bool negative,
bool throwException) {
if (endIndex - index > 72) {
int midIndex = index + ((endIndex - index) / 2);
EInteger eia = FromRadixSubstringGeneral(
cs,
radix,
index,
midIndex,
false,
throwException);
// DebugUtility.Log("eia="+eia);
EInteger eib = FromRadixSubstringGeneral(
cs,
radix,
midIndex,
endIndex,
false,
throwException);
// DebugUtility.Log("eib="+eib);
EInteger mult = null;
int intpow = endIndex - midIndex;
if (radix == 10) {
eia = NumberUtility.MultiplyByPowerOfFive(eia,
intpow).ShiftLeft(intpow);
} else if (radix == 5) {
eia = NumberUtility.MultiplyByPowerOfFive(eia, intpow);
} else {
mult = EInteger.FromInt32(radix).Pow(endIndex - midIndex);
eia = eia.Multiply(mult);
}
eia = eia.Add(eib);
// DebugUtility.Log("index={0} {1} {2} [pow={3}] [pow={4} ms, muladd={5} ms]",
// index, midIndex, endIndex, endIndex-midIndex, swPow.ElapsedMilliseconds,
// swMulAdd.ElapsedMilliseconds);
if (negative) {
eia = eia.Negate();
}
// DebugUtility.Log("eia now="+eia);
return eia;
} else {
return FromRadixSubstringInner(
cs,
radix,
index,
endIndex,
negative,
throwException);
}
}
private static EInteger FromRadixSubstringInner(
string cs,
int radix,
int index,
int endIndex,
bool negative,
bool throwException) {
if (radix <= 10) {
long rv = 0;
var digitCount = 0;
if (radix == 10) {
for (int i = index; i < endIndex; ++i) {
char c = cs[i];
var digit = (int)c - 0x30;
if (digit >= radix || digit < 0) {
if (!throwException) {
return null;
} else {
throw new FormatException("Illegal character found");
}
}
if (digitCount < 0 || digitCount >= 18) {
digitCount = -1;
break;
} else if (digitCount > 0 || digit != 0) {
++digitCount;
}
rv = (rv * 10) + digit;
}
// DebugUtility.Log("short="+(negative ? -rv : rv));
if (digitCount >= 0) {
return EInteger.FromInt64(negative ? -rv : rv);
}
} else {
for (int i = index; i < endIndex; ++i) {
char c = cs[i];
int digit = (c >= 0x80) ? 36 : ((int)c - 0x30);
if (digit >= radix || digit < 0) {
if (!throwException) {
return null;
} else {
throw new FormatException("Illegal character found");
}
}
if (digitCount < 0 || digitCount >= 18) {
digitCount = -1;
break;
} else if (digitCount > 0 || digit != 0) {
++digitCount;
}
rv = (rv * radix) + digit;
}
if (digitCount >= 0) {
return EInteger.FromInt64(negative ? -rv : rv);
}
}
}
int[] c2d = EInteger.CharToDigit;
int[] d2w = EInteger.DigitsInWord;
long lsize = ((long)(endIndex - index) * 100 / d2w[radix]) + 1;
lsize = Math.Min(lsize, Int32.MaxValue);
lsize = Math.Max(lsize, 5);
var bigint = new short[(int)lsize];
if (radix == 10) {
long rv = 0;
int ei = endIndex - index <= 18 ? endIndex : index + 18;
for (int i = index; i < ei; ++i) {
char c = cs[i];
var digit = (int)c - 0x30;
if (digit >= radix || digit < 0) {
if (!throwException) {
return null;
} else {
throw new FormatException("Illegal character found");
}
}
rv = (rv * 10) + digit;
}
bigint[0] = unchecked((short)(rv & ShortMask));
bigint[1] = unchecked((short)((rv >> 16) & ShortMask));
bigint[2] = unchecked((short)((rv >> 32) & ShortMask));
bigint[3] = unchecked((short)((rv >> 48) & ShortMask));
int bn = Math.Min(bigint.Length, 5);
for (int i = ei; i < endIndex; ++i) {
short carry = 0;
var digit = 0;
var overf = 0;
if (i < endIndex - 3) {
overf = 55536; // 2**16 minus 10**4
var d1 = (int)cs[i] - 0x30;
var d2 = (int)cs[i + 1] - 0x30;
var d3 = (int)cs[i + 2] - 0x30;
var d4 = (int)cs[i + 3] - 0x30;
i += 3;
if (d1 >= 10 || d1 < 0 || d2 >= 10 || d2 < 0 || d3 >= 10 ||
d3 < 0 || d4 >= 10 || d4 < 0) {
if (!throwException) {
return null;
} else {
throw new FormatException("Illegal character found");
}
}
digit = (d1 * 1000) + (d2 * 100) + (d3 * 10) + d4;
// Multiply by 10**4
for (int j = 0; j < bn; ++j) {
int p;
p = unchecked((((int)bigint[j]) & ShortMask) *
10000);
int p2 = ((int)carry) & ShortMask;
p = unchecked(p + p2);
bigint[j] = unchecked((short)p);
carry = unchecked((short)(p >> 16));
}
} else {
overf = 65526; // 2**16 minus radix 10
char c = cs[i];
digit = (int)c - 0x30;
if (digit >= 10 || digit < 0) {
if (!throwException) {
return null;
} else {
throw new FormatException("Illegal character found");
}
}
// Multiply by 10
for (int j = 0; j < bn; ++j) {
int p;
p = unchecked((((int)bigint[j]) & ShortMask) * 10);
int p2 = ((int)carry) & ShortMask;
p = unchecked(p + p2);
bigint[j] = unchecked((short)p);
carry = unchecked((short)(p >> 16));
}
}
if (carry != 0) {
bigint = EInteger.GrowForCarry(bigint, carry);
}
// Add the parsed digit
if (digit != 0) {
int d = bigint[0] & ShortMask;
if (d <= overf) {
bigint[0] = unchecked((short)(d + digit));
} else if (EInteger.IncrementWords(
bigint,
0,
bigint.Length,
(short)digit) != 0) {
bigint = EInteger.GrowForCarry(bigint, (short)1);
}
}
bn = Math.Min(bigint.Length, bn + 1);
}
} else {
var haveSmallInt = true;
int[] msi = EInteger.MaxSafeInts;
int maxSafeInt = msi[radix - 2];
int maxShortPlusOneMinusRadix = 65536 - radix;
var smallInt = 0;
for (int i = index; i < endIndex; ++i) {
char c = cs[i];
int digit = (c >= 0x80) ? 36 : c2d[(int)c];
if (digit >= radix) {
if (!throwException) {
return null;
} else {
throw new FormatException("Illegal character found");
}
}
if (haveSmallInt && smallInt < maxSafeInt) {
smallInt = (smallInt * radix) + digit;
} else {
if (haveSmallInt) {
bigint[0] = unchecked((short)(smallInt &
ShortMask));
bigint[1] = unchecked((short)((smallInt >> 16) &
ShortMask));
haveSmallInt = false;
}
// Multiply by the radix
short carry = 0;
int n = bigint.Length;
for (int j = 0; j < n; ++j) {
int p;
p = unchecked((((int)bigint[j]) & ShortMask) *
radix);
int p2 = ((int)carry) & ShortMask;
p = unchecked(p + p2);
bigint[j] = unchecked((short)p);
carry = unchecked((short)(p >> 16));
}
if (carry != 0) {
bigint = EInteger.GrowForCarry(bigint, carry);
}
// Add the parsed digit
if (digit != 0) {
int d = bigint[0] & ShortMask;
if (d <= maxShortPlusOneMinusRadix) {
bigint[0] = unchecked((short)(d + digit));
} else if (EInteger.IncrementWords(
bigint,
0,
bigint.Length,
(short)digit) != 0) {
bigint = EInteger.GrowForCarry(bigint, (short)1);
}
}
}
}
if (haveSmallInt) {
bigint[0] = unchecked((short)(smallInt & ShortMask));
bigint[1] = unchecked((short)((smallInt >> 16) &
ShortMask));
}
}
int count = EInteger.CountWords(bigint);
return (count == 0) ? EInteger.Zero : new EInteger(
count,
bigint,
negative);
}
}
}
| |
// 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 Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudioTools.Project;
using VSConstants = Microsoft.VisualStudio.VSConstants;
namespace Microsoft.VisualStudioTools.Navigation
{
internal class HierarchyEventArgs : EventArgs
{
private uint _itemId;
private string _fileName;
private IVsTextLines _buffer;
public HierarchyEventArgs(uint itemId, string canonicalName)
{
this._itemId = itemId;
this._fileName = canonicalName;
}
public string CanonicalName => this._fileName; public uint ItemID => this._itemId; public IVsTextLines TextBuffer
{
get { return this._buffer; }
set { this._buffer = value; }
}
}
internal abstract partial class LibraryManager : IDisposable, IVsRunningDocTableEvents
{
internal class HierarchyListener : IVsHierarchyEvents, IDisposable
{
private IVsHierarchy _hierarchy;
private uint _cookie;
private LibraryManager _manager;
public HierarchyListener(IVsHierarchy hierarchy, LibraryManager manager)
{
Utilities.ArgumentNotNull("hierarchy", hierarchy);
Utilities.ArgumentNotNull("manager", manager);
this._hierarchy = hierarchy;
this._manager = manager;
}
protected IVsHierarchy Hierarchy => this._hierarchy;
#region Public Methods
public bool IsListening => (0 != this._cookie); public void StartListening(bool doInitialScan)
{
if (0 != this._cookie)
{
return;
}
ErrorHandler.ThrowOnFailure(
this._hierarchy.AdviseHierarchyEvents(this, out this._cookie));
if (doInitialScan)
{
InternalScanHierarchy(VSConstants.VSITEMID_ROOT);
}
}
public void StopListening()
{
InternalStopListening(true);
}
#endregion
#region IDisposable Members
public void Dispose()
{
InternalStopListening(false);
this._cookie = 0;
this._hierarchy = null;
}
#endregion
#region IVsHierarchyEvents Members
public int OnInvalidateIcon(IntPtr hicon)
{
// Do Nothing.
return VSConstants.S_OK;
}
public int OnInvalidateItems(uint itemidParent)
{
// TODO: Find out if this event is needed.
return VSConstants.S_OK;
}
public int OnItemAdded(uint itemidParent, uint itemidSiblingPrev, uint itemidAdded)
{
// Check if the item is my language file.
string name;
if (!IsAnalyzableSource(itemidAdded, out name))
{
return VSConstants.S_OK;
}
// This item is a my language file, so we can notify that it is added to the hierarchy.
var args = new HierarchyEventArgs(itemidAdded, name);
this._manager.OnNewFile(this._hierarchy, args);
return VSConstants.S_OK;
}
public int OnItemDeleted(uint itemid)
{
// Notify that the item is deleted only if it is my language file.
string name;
if (!IsAnalyzableSource(itemid, out name))
{
return VSConstants.S_OK;
}
var args = new HierarchyEventArgs(itemid, name);
this._manager.OnDeleteFile(this._hierarchy, args);
return VSConstants.S_OK;
}
public int OnItemsAppended(uint itemidParent)
{
// TODO: Find out what this event is about.
return VSConstants.S_OK;
}
public int OnPropertyChanged(uint itemid, int propid, uint flags)
{
if ((null == this._hierarchy) || (0 == this._cookie))
{
return VSConstants.S_OK;
}
string name;
if (!IsAnalyzableSource(itemid, out name))
{
return VSConstants.S_OK;
}
if (propid == (int)__VSHPROPID.VSHPROPID_IsNonMemberItem)
{
this._manager.IsNonMemberItemChanged(this._hierarchy, new HierarchyEventArgs(itemid, name));
}
return VSConstants.S_OK;
}
#endregion
private bool InternalStopListening(bool throwOnError)
{
if ((null == this._hierarchy) || (0 == this._cookie))
{
return false;
}
var hr = this._hierarchy.UnadviseHierarchyEvents(this._cookie);
if (throwOnError)
{
ErrorHandler.ThrowOnFailure(hr);
}
this._cookie = 0;
return ErrorHandler.Succeeded(hr);
}
/// <summary>
/// Do a recursive walk on the hierarchy to find all this language files in it.
/// It will generate an event for every file found.
/// </summary>
private void InternalScanHierarchy(uint itemId)
{
var currentItem = itemId;
while (VSConstants.VSITEMID_NIL != currentItem)
{
// If this item is a my language file, then send the add item event.
string itemName;
if (IsAnalyzableSource(currentItem, out itemName))
{
var args = new HierarchyEventArgs(currentItem, itemName);
this._manager.OnNewFile(this._hierarchy, args);
}
// NOTE: At the moment we skip the nested hierarchies, so here we look for the
// children of this node.
// Before looking at the children we have to make sure that the enumeration has not
// side effects to avoid unexpected behavior.
object propertyValue;
var canScanSubitems = true;
var hr = this._hierarchy.GetProperty(currentItem, (int)__VSHPROPID.VSHPROPID_HasEnumerationSideEffects, out propertyValue);
if ((VSConstants.S_OK == hr) && (propertyValue is bool))
{
canScanSubitems = !(bool)propertyValue;
}
// If it is allow to look at the sub-items of the current one, lets do it.
if (canScanSubitems)
{
object child;
hr = this._hierarchy.GetProperty(currentItem, (int)__VSHPROPID.VSHPROPID_FirstChild, out child);
if (VSConstants.S_OK == hr)
{
// There is a sub-item, call this same function on it.
InternalScanHierarchy(GetItemId(child));
}
}
// Move the current item to its first visible sibling.
object sibling;
hr = this._hierarchy.GetProperty(currentItem, (int)__VSHPROPID.VSHPROPID_NextSibling, out sibling);
if (VSConstants.S_OK != hr)
{
currentItem = VSConstants.VSITEMID_NIL;
}
else
{
currentItem = GetItemId(sibling);
}
}
}
private bool IsAnalyzableSource(uint itemId, out string canonicalName)
{
// Find out if this item is a physical file.
Guid typeGuid;
canonicalName = null;
int hr;
try
{
hr = this.Hierarchy.GetGuidProperty(itemId, (int)__VSHPROPID.VSHPROPID_TypeGuid, out typeGuid);
}
catch (System.Runtime.InteropServices.COMException)
{
return false;
}
if (Microsoft.VisualStudio.ErrorHandler.Failed(hr) ||
VSConstants.GUID_ItemType_PhysicalFile != typeGuid)
{
// It is not a file, we can exit now.
return false;
}
// This item is a file; find if current language can recognize it.
hr = this.Hierarchy.GetCanonicalName(itemId, out canonicalName);
if (ErrorHandler.Failed(hr))
{
return false;
}
return (System.IO.Path.GetExtension(canonicalName).Equals(".xaml", StringComparison.OrdinalIgnoreCase)) ||
this._manager._package.IsRecognizedFile(canonicalName);
}
/// <summary>
/// Gets the item id.
/// </summary>
/// <param name="variantValue">VARIANT holding an itemid.</param>
/// <returns>Item Id of the concerned node</returns>
private static uint GetItemId(object variantValue)
{
if (variantValue == null)
return VSConstants.VSITEMID_NIL;
if (variantValue is int)
return (uint)(int)variantValue;
if (variantValue is uint)
return (uint)variantValue;
if (variantValue is short)
return (uint)(short)variantValue;
if (variantValue is ushort)
return (uint)(ushort)variantValue;
if (variantValue is long)
return (uint)(long)variantValue;
return VSConstants.VSITEMID_NIL;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.Editor.Commands;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Operations;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests
{
internal abstract class AbstractCommandHandlerTestState : IDisposable
{
public readonly TestWorkspace Workspace;
public readonly IEditorOperations EditorOperations;
public readonly ITextUndoHistoryRegistry UndoHistoryRegistry;
private readonly ITextView _textView;
private readonly ITextBuffer _subjectBuffer;
public AbstractCommandHandlerTestState(
XElement workspaceElement,
ComposableCatalog extraParts = null,
bool useMinimumCatalog = false,
string workspaceKind = null)
: this(workspaceElement, GetExportProvider(useMinimumCatalog, extraParts), workspaceKind)
{
}
/// <summary>
/// This can use input files with an (optionally) annotated span 'Selection' and a cursor position ($$),
/// and use it to create a selected span in the TextView.
///
/// For instance, the following will create a TextView that has a multiline selection with the cursor at the end.
///
/// Sub Foo
/// {|Selection:SomeMethodCall()
/// AnotherMethodCall()$$|}
/// End Sub
/// </summary>
public AbstractCommandHandlerTestState(
XElement workspaceElement,
ExportProvider exportProvider,
string workspaceKind)
{
this.Workspace = TestWorkspaceFactory.CreateWorkspace(
workspaceElement,
exportProvider: exportProvider,
workspaceKind: workspaceKind);
var cursorDocument = this.Workspace.Documents.First(d => d.CursorPosition.HasValue);
_textView = cursorDocument.GetTextView();
_subjectBuffer = cursorDocument.GetTextBuffer();
IList<Text.TextSpan> selectionSpanList;
if (cursorDocument.AnnotatedSpans.TryGetValue("Selection", out selectionSpanList))
{
var span = selectionSpanList.First();
var cursorPosition = cursorDocument.CursorPosition.Value;
Assert.True(cursorPosition == span.Start || cursorPosition == span.Start + span.Length,
"cursorPosition wasn't at an endpoint of the 'Selection' annotated span");
_textView.Selection.Select(
new SnapshotSpan(_subjectBuffer.CurrentSnapshot, new Span(span.Start, span.Length)),
isReversed: cursorPosition == span.Start);
if (selectionSpanList.Count > 1)
{
_textView.Selection.Mode = TextSelectionMode.Box;
foreach (var additionalSpan in selectionSpanList.Skip(1))
{
_textView.Selection.Select(
new SnapshotSpan(_subjectBuffer.CurrentSnapshot, new Span(additionalSpan.Start, additionalSpan.Length)),
isReversed: false);
}
}
}
else
{
_textView.Caret.MoveTo(
new SnapshotPoint(
_textView.TextBuffer.CurrentSnapshot,
cursorDocument.CursorPosition.Value));
}
this.EditorOperations = GetService<IEditorOperationsFactoryService>().GetEditorOperations(_textView);
this.UndoHistoryRegistry = GetService<ITextUndoHistoryRegistry>();
}
public void Dispose()
{
Workspace.Dispose();
}
public T GetService<T>()
{
return Workspace.GetService<T>();
}
private static ExportProvider GetExportProvider(bool useMinimumCatalog, ComposableCatalog extraParts)
{
var baseCatalog = useMinimumCatalog
? TestExportProvider.MinimumCatalogWithCSharpAndVisualBasic
: TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic;
if (extraParts == null)
{
return MinimalTestExportProvider.CreateExportProvider(baseCatalog);
}
return MinimalTestExportProvider.CreateExportProvider(baseCatalog.WithParts(extraParts));
}
public virtual ITextView TextView
{
get { return _textView; }
}
public virtual ITextBuffer SubjectBuffer
{
get { return _subjectBuffer; }
}
#region MEF
public Lazy<TExport, TMetadata> GetExport<TExport, TMetadata>()
{
return (Lazy<TExport, TMetadata>)(object)Workspace.ExportProvider.GetExport<TExport, TMetadata>();
}
public IEnumerable<Lazy<TExport, TMetadata>> GetExports<TExport, TMetadata>()
{
return (IEnumerable<Lazy<TExport, TMetadata>>)Workspace.ExportProvider.GetExports<TExport, TMetadata>();
}
public T GetExportedValue<T>()
{
return Workspace.ExportProvider.GetExportedValue<T>();
}
public IEnumerable<T> GetExportedValues<T>()
{
return Workspace.ExportProvider.GetExportedValues<T>();
}
#endregion
#region editor related operation
public void SendBackspace()
{
EditorOperations.Backspace();
}
public void SendDelete()
{
EditorOperations.Delete();
}
public void SendRightKey(bool extendSelection = false)
{
EditorOperations.MoveToNextCharacter(extendSelection);
}
public void SendLeftKey(bool extendSelection = false)
{
EditorOperations.MoveToPreviousCharacter(extendSelection);
}
public void SendMoveToPreviousCharacter(bool extendSelection = false)
{
EditorOperations.MoveToPreviousCharacter(extendSelection);
}
public void SendDeleteWordToLeft()
{
EditorOperations.DeleteWordToLeft();
}
public void SendUndo(int count = 1)
{
var history = UndoHistoryRegistry.GetHistory(SubjectBuffer);
history.Undo(count);
}
#endregion
#region test/information/verification
public ITextSnapshotLine GetLineFromCurrentCaretPosition()
{
var caretPosition = GetCaretPoint();
return SubjectBuffer.CurrentSnapshot.GetLineFromPosition(caretPosition.BufferPosition);
}
public string GetLineTextFromCaretPosition()
{
var caretPosition = Workspace.Documents.Single(d => d.CursorPosition.HasValue).CursorPosition.Value;
return SubjectBuffer.CurrentSnapshot.GetLineFromPosition(caretPosition).GetText();
}
public string GetDocumentText()
{
return SubjectBuffer.CurrentSnapshot.GetText();
}
public CaretPosition GetCaretPoint()
{
return TextView.Caret.Position;
}
public void WaitForAsynchronousOperations()
{
var waiters = Workspace.ExportProvider.GetExportedValues<IAsynchronousOperationWaiter>();
var tasks = waiters.Select(w => w.CreateWaitTask()).ToList();
tasks.PumpingWaitAll();
}
public void AssertMatchesTextStartingAtLine(int line, string text)
{
var lines = text.Split('\r');
foreach (var expectedLine in lines)
{
Assert.Equal(expectedLine.Trim(), SubjectBuffer.CurrentSnapshot.GetLineFromLineNumber(line).GetText().Trim());
line += 1;
}
}
#endregion
#region command handler
public void SendBackspace(Action<BackspaceKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new BackspaceKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendDelete(Action<DeleteKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new DeleteKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendWordDeleteToStart(Action<WordDeleteToStartCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new WordDeleteToStartCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendEscape(Action<EscapeKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new EscapeKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendUpKey(Action<UpKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new UpKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendDownKey(Action<DownKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new DownKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendTab(Action<TabKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new TabKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendBackTab(Action<BackTabKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new BackTabKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendReturn(Action<ReturnKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new ReturnKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendPageUp(Action<PageUpKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new PageUpKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendPageDown(Action<PageDownKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new PageDownKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendCut(Action<CutCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new CutCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendPaste(Action<PasteCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new PasteCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendInvokeCompletionList(Action<InvokeCompletionListCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new InvokeCompletionListCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendCommitUniqueCompletionListItem(Action<CommitUniqueCompletionListItemCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new CommitUniqueCompletionListItemCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendInsertSnippetCommand(Action<InsertSnippetCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new InsertSnippetCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendSurroundWithCommand(Action<SurroundWithCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new SurroundWithCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendInvokeSignatureHelp(Action<InvokeSignatureHelpCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new InvokeSignatureHelpCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendTypeChar(char typeChar, Action<TypeCharCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new TypeCharCommandArgs(TextView, SubjectBuffer, typeChar), nextHandler);
}
public void SendTypeChars(string typeChars, Action<TypeCharCommandArgs, Action> commandHandler)
{
foreach (var ch in typeChars)
{
var localCh = ch;
SendTypeChar(ch, commandHandler, () => EditorOperations.InsertText(localCh.ToString()));
}
}
public void SendSave(Action<SaveCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new SaveCommandArgs(TextView, SubjectBuffer), nextHandler);
}
#endregion
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.DirectoryServices.ActiveDirectory.Domain.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.DirectoryServices.ActiveDirectory
{
public partial class Domain : ActiveDirectoryPartition
{
#region Methods and constructors
public void CreateLocalSideOfTrustRelationship(string targetDomainName, TrustDirection direction, string trustPassword)
{
Contract.Requires(!string.IsNullOrEmpty(targetDomainName));
Contract.Requires(!string.IsNullOrEmpty(trustPassword));
}
public void CreateTrustRelationship(Domain targetDomain, TrustDirection direction)
{
Contract.Requires(targetDomain != null);
}
public void DeleteLocalSideOfTrustRelationship(string targetDomainName)
{
Contract.Requires(!string.IsNullOrEmpty(targetDomainName));
}
public void DeleteTrustRelationship(Domain targetDomain)
{
Contract.Requires(targetDomain != null);
}
private Domain()
{
}
public DomainControllerCollection FindAllDiscoverableDomainControllers()
{
Contract.Ensures(Contract.Result<DomainControllerCollection>() != null);
return default(DomainControllerCollection);
}
public DomainControllerCollection FindAllDiscoverableDomainControllers(string siteName)
{
Contract.Requires(!string.IsNullOrEmpty(siteName));
Contract.Ensures(Contract.Result<DomainControllerCollection>() != null);
return default(DomainControllerCollection);
}
public DomainControllerCollection FindAllDomainControllers()
{
Contract.Ensures(Contract.Result<DomainControllerCollection>() != null);
return default(DomainControllerCollection);
}
public DomainControllerCollection FindAllDomainControllers(string siteName)
{
Contract.Requires(!string.IsNullOrEmpty(siteName));
Contract.Ensures(Contract.Result<DomainControllerCollection>() != null);
return default(DomainControllerCollection);
}
public DomainController FindDomainController(string siteName)
{
Contract.Requires(!string.IsNullOrEmpty(siteName));
Contract.Ensures(Contract.Result<DomainController>() != null);
return default(DomainController);
}
public DomainController FindDomainController(LocatorOptions flag)
{
Contract.Ensures(Contract.Result<DomainController>() != null);
return default(DomainController);
}
public DomainController FindDomainController()
{
Contract.Ensures(Contract.Result<DomainController>() != null);
return default(DomainController);
}
public DomainController FindDomainController(string siteName, LocatorOptions flag)
{
Contract.Ensures(Contract.Result<DomainController>() != null);
return default(DomainController);
}
public TrustRelationshipInformationCollection GetAllTrustRelationships()
{
Contract.Ensures(Contract.Result<TrustRelationshipInformationCollection>() != null);
return default(TrustRelationshipInformationCollection);
}
public static Domain GetComputerDomain()
{
Contract.Ensures(Contract.Result<Domain>() != null);
return default(Domain);
}
public static Domain GetCurrentDomain()
{
Contract.Ensures(Contract.Result<Domain>() != null);
return default(Domain);
}
public override System.DirectoryServices.DirectoryEntry GetDirectoryEntry()
{
Contract.Ensures(Contract.Result<DirectoryEntry>() != null);
return default(System.DirectoryServices.DirectoryEntry);
}
public static Domain GetDomain(DirectoryContext context)
{
Contract.Requires(context != null);
Contract.Ensures(Contract.Result<Domain>() != null);
return default(Domain);
}
public bool GetSelectiveAuthenticationStatus(string targetDomainName)
{
Contract.Requires(!string.IsNullOrEmpty(targetDomainName));
return default(bool);
}
public bool GetSidFilteringStatus(string targetDomainName)
{
Contract.Requires(!string.IsNullOrEmpty(targetDomainName));
return default(bool);
}
public TrustRelationshipInformation GetTrustRelationship(string targetDomainName)
{
Contract.Requires(!string.IsNullOrEmpty(targetDomainName));
return default(TrustRelationshipInformation);
}
public void RaiseDomainFunctionality(DomainMode domainMode)
{
}
public void RepairTrustRelationship(Domain targetDomain)
{
}
public void SetSelectiveAuthenticationStatus(string targetDomainName, bool enable)
{
Contract.Requires(!string.IsNullOrEmpty(targetDomainName));
}
public void SetSidFilteringStatus(string targetDomainName, bool enable)
{
Contract.Requires(!string.IsNullOrEmpty(targetDomainName));
}
public void UpdateLocalSideOfTrustRelationship(string targetDomainName, string newTrustPassword)
{
Contract.Requires(!string.IsNullOrEmpty(targetDomainName));
}
public void UpdateLocalSideOfTrustRelationship(string targetDomainName, TrustDirection newTrustDirection, string newTrustPassword)
{
Contract.Requires(!string.IsNullOrEmpty(targetDomainName));
}
public void UpdateTrustRelationship(Domain targetDomain, TrustDirection newTrustDirection)
{
Contract.Requires(targetDomain != null);
}
public void VerifyOutboundTrustRelationship(string targetDomainName)
{
Contract.Requires(!string.IsNullOrEmpty(targetDomainName));
}
public void VerifyTrustRelationship(Domain targetDomain, TrustDirection direction)
{
Contract.Requires(targetDomain != null);
}
#endregion
#region Properties and indexers
public DomainCollection Children
{
get
{
Contract.Ensures(Contract.Result<DomainCollection>() != null);
return default(DomainCollection);
}
}
public DomainControllerCollection DomainControllers
{
get
{
Contract.Ensures(Contract.Result<DomainCollection>() != null);
return default(DomainControllerCollection);
}
}
public DomainMode DomainMode
{
get
{
return default(DomainMode);
}
}
public Forest Forest
{
get
{
Contract.Ensures(Contract.Result<Forest>() != null);
return default(Forest);
}
}
public DomainController InfrastructureRoleOwner
{
get
{
Contract.Ensures(Contract.Result<DomainController>() != null);
return default(DomainController);
}
}
public Domain Parent
{
get
{
Contract.Ensures(Contract.Result<Domain>() != null);
return default(System.DirectoryServices.ActiveDirectory.Domain);
}
}
public DomainController PdcRoleOwner
{
get
{
Contract.Ensures(Contract.Result<DomainController>() != null);
return default(DomainController);
}
}
public DomainController RidRoleOwner
{
get
{
Contract.Ensures(Contract.Result<DomainController>() != null);
return default(DomainController);
}
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using tk2dRuntime.TileMap;
[ExecuteInEditMode]
[AddComponentMenu("2D Toolkit/TileMap/TileMap")]
/// <summary>
/// Tile Map
/// </summary>
public class tk2dTileMap : MonoBehaviour, tk2dRuntime.ISpriteCollectionForceBuild
{
/// <summary>
/// This is a link to the editor data object (tk2dTileMapEditorData).
/// It contains presets, and other data which isn't really relevant in game.
/// </summary>
public string editorDataGUID = "";
/// <summary>
/// Tile map data, stores shared parameters for tilemaps
/// </summary>
public tk2dTileMapData data;
/// <summary>
/// Tile map render and collider object
/// </summary>
public GameObject renderData;
/// <summary>
/// The sprite collection used by the tilemap
/// </summary>
[SerializeField]
private tk2dSpriteCollectionData spriteCollection = null;
public tk2dSpriteCollectionData Editor__SpriteCollection
{
get
{
return spriteCollection;
}
set
{
_spriteCollectionInst = null;
spriteCollection = value;
if (spriteCollection != null)
_spriteCollectionInst = spriteCollection.inst;
}
}
tk2dSpriteCollectionData _spriteCollectionInst = null;
public tk2dSpriteCollectionData SpriteCollectionInst
{
get
{
if (_spriteCollectionInst == null && spriteCollection != null)
_spriteCollectionInst = spriteCollection.inst;
return _spriteCollectionInst;
}
}
[SerializeField]
int spriteCollectionKey;
/// <summary>Width of the tilemap</summary>
public int width = 128;
/// <summary>Height of the tilemap</summary>
public int height = 128;
/// <summary>X axis partition size for this tilemap</summary>
public int partitionSizeX = 32;
/// <summary>Y axis partition size for this tilemap</summary>
public int partitionSizeY = 32;
[SerializeField]
Layer[] layers;
[SerializeField]
ColorChannel colorChannel;
public int buildKey;
[SerializeField]
bool _inEditMode = false;
public bool AllowEdit { get { return _inEditMode; } }
// do we need to retain meshes?
public bool serializeRenderData = false;
// holds a path to a serialized mesh, uses this to work out dump directory for meshes
public string serializedMeshPath;
void Awake()
{
if (spriteCollection != null)
_spriteCollectionInst = spriteCollection.inst;
bool spriteCollectionKeyMatch = true;
if (SpriteCollectionInst && SpriteCollectionInst.buildKey != spriteCollectionKey) spriteCollectionKeyMatch = false;
if (Application.platform == RuntimePlatform.WindowsEditor ||
Application.platform == RuntimePlatform.OSXEditor)
{
if ((Application.isPlaying && _inEditMode == true) || !spriteCollectionKeyMatch)
{
// Switched to edit mode while still in edit mode, rebuild
Build(BuildFlags.ForceBuild);
}
}
else
{
if (_inEditMode == true)
{
Debug.LogError("Tilemap " + name + " is still in edit mode. Please fix." +
"Building overhead will be significant.");
Build(BuildFlags.ForceBuild);
}
else if (!spriteCollectionKeyMatch)
{
Build(BuildFlags.ForceBuild);
}
}
}
[System.Flags]
public enum BuildFlags {
Default = 0,
EditMode = 1,
ForceBuild = 2
};
public void Build() { Build(BuildFlags.Default); }
public void ForceBuild() { Build(BuildFlags.ForceBuild); }
// Clears all spawned instances, but retains the renderData object
void ClearSpawnedInstances()
{
if (layers == null)
return;
for (int layerIdx = 0; layerIdx < layers.Length; ++layerIdx)
{
Layer layer = layers[layerIdx];
for (int chunkIdx = 0; chunkIdx < layer.spriteChannel.chunks.Length; ++chunkIdx)
{
var chunk = layer.spriteChannel.chunks[chunkIdx];
if (chunk.gameObject == null)
continue;
var transform = chunk.gameObject.transform;
List<Transform> children = new List<Transform>();
for (int i = 0; i < transform.GetChildCount(); ++i)
children.Add(transform.GetChild(i));
for (int i = 0; i < children.Count; ++i)
DestroyImmediate(children[i].gameObject);
}
}
}
public void Build(BuildFlags buildFlags)
{
if (spriteCollection != null)
_spriteCollectionInst = spriteCollection.inst;
#if UNITY_EDITOR || !UNITY_FLASH
// Sanitize tilePrefabs input, to avoid branches later
if (data != null)
{
if (data.tilePrefabs == null)
data.tilePrefabs = new Object[SpriteCollectionInst.Count];
else if (data.tilePrefabs.Length != SpriteCollectionInst.Count)
System.Array.Resize(ref data.tilePrefabs, SpriteCollectionInst.Count);
// Fix up data if necessary
BuilderUtil.InitDataStore(this);
}
else
{
return;
}
// Sanitize sprite collection material ids
if (SpriteCollectionInst)
SpriteCollectionInst.InitMaterialIds();
bool editMode = (buildFlags & BuildFlags.EditMode) != 0;
bool forceBuild = (buildFlags & BuildFlags.ForceBuild) != 0;
// When invalid, everything needs to be rebuilt
if (SpriteCollectionInst && SpriteCollectionInst.buildKey != spriteCollectionKey)
forceBuild = true;
if (forceBuild)
ClearSpawnedInstances();
BuilderUtil.CreateRenderData(this, editMode);
RenderMeshBuilder.Build(this, editMode, forceBuild);
if (!editMode)
{
ColliderBuilder.Build(this, forceBuild);
BuilderUtil.SpawnPrefabs(this);
}
// Clear dirty flag on everything
foreach (var layer in layers)
layer.ClearDirtyFlag();
if (colorChannel != null)
colorChannel.ClearDirtyFlag();
// One random number to detect undo
buildKey = Random.Range(0, int.MaxValue);
// Update sprite collection key
if (SpriteCollectionInst)
spriteCollectionKey = SpriteCollectionInst.buildKey;
#endif
}
/// <summary>
/// Gets the tile coordinate at position. This can be used to obtain tile or color data explicitly from layers
/// Returns true if the position is within the tilemap bounds
/// </summary>
public bool GetTileAtPosition(Vector3 position, out int x, out int y)
{
float ox, oy;
bool b = GetTileFracAtPosition(position, out ox, out oy);
x = (int)ox;
y = (int)oy;
return b;
}
/// <summary>
/// Gets the tile coordinate at position. This can be used to obtain tile or color data explicitly from layers
/// The fractional value returned is the fraction into the current tile
/// Returns true if the position is within the tilemap bounds
/// </summary>
public bool GetTileFracAtPosition(Vector3 position, out float x, out float y)
{
switch (data.tileType)
{
case tk2dTileMapData.TileType.Rectangular:
{
Vector3 localPosition = transform.worldToLocalMatrix.MultiplyPoint(position);
x = (localPosition.x - data.tileOrigin.x) / data.tileSize.x;
y = (localPosition.y - data.tileOrigin.y) / data.tileSize.y;
return (x >= 0 && x <= width && y >= 0 && y <= height);
}
case tk2dTileMapData.TileType.Isometric:
{
if (data.tileSize.x == 0.0f)
break;
float tileAngle = Mathf.Atan2(data.tileSize.y, data.tileSize.x / 2.0f);
Vector3 localPosition = transform.worldToLocalMatrix.MultiplyPoint(position);
x = (localPosition.x - data.tileOrigin.x) / data.tileSize.x;
y = ((localPosition.y - data.tileOrigin.y) / (data.tileSize.y));
float fy = y * 0.5f;
int iy = (int)fy;
float fry = fy - iy;
float frx = x % 1.0f;
x = (int)x;
y = iy * 2;
if (frx > 0.5f)
{
if (fry > 0.5f && Mathf.Atan2(1.0f - fry, (frx - 0.5f) * 2) < tileAngle)
y += 1;
else if (fry < 0.5f && Mathf.Atan2(fry, (frx - 0.5f) * 2) < tileAngle)
y -= 1;
}
else if (frx < 0.5f)
{
if (fry > 0.5f && Mathf.Atan2(fry - 0.5f, frx * 2) > tileAngle)
{
y += 1;
x -= 1;
}
if (fry < 0.5f && Mathf.Atan2(fry, (0.5f - frx) * 2) < tileAngle)
{
y -= 1;
x -= 1;
}
}
return (x >= 0 && x <= width && y >= 0 && y <= height);
}
}
x = 0.0f;
y = 0.0f;
return false;
}
/// <summary>
/// Returns the tile position in world space
/// </summary>
public Vector3 GetTilePosition(int x, int y)
{
switch (data.tileType)
{
case tk2dTileMapData.TileType.Rectangular:
default:
{
Vector3 localPosition = new Vector3(
x * data.tileSize.x + data.tileOrigin.x,
y * data.tileSize.y + data.tileOrigin.y,
0);
return transform.localToWorldMatrix.MultiplyPoint(localPosition);
}
case tk2dTileMapData.TileType.Isometric:
{
Vector3 localPosition = new Vector3(
((float)x + (((y & 1) == 0) ? 0.0f : 0.5f)) * data.tileSize.x + data.tileOrigin.x,
y * data.tileSize.y + data.tileOrigin.y,
0);
return transform.localToWorldMatrix.MultiplyPoint(localPosition);
}
}
}
/// <summary>
/// Gets the tile at position. This can be used to obtain tile data, etc
/// -1 = no data or empty tile
/// </summary>
public int GetTileIdAtPosition(Vector3 position, int layer)
{
if (layer < 0 || layer >= layers.Length)
return -1;
int x, y;
if (!GetTileAtPosition(position, out x, out y))
return -1;
return layers[layer].GetTile(x, y);
}
/// <summary>
/// Returns the tile info chunk for the tile. Use this to store additional metadata
/// </summary>
public tk2dRuntime.TileMap.TileInfo GetTileInfoForTileId(int tileId)
{
return data.GetTileInfoForSprite(tileId);
}
/// <summary>
/// Gets the tile at position. This can be used to obtain tile data, etc
/// -1 = no data or empty tile
/// </summary>
public Color GetInterpolatedColorAtPosition(Vector3 position)
{
Vector3 localPosition = transform.worldToLocalMatrix.MultiplyPoint(position);
int x = (int)((localPosition.x - data.tileOrigin.x) / data.tileSize.x);
int y = (int)((localPosition.y - data.tileOrigin.y) / data.tileSize.y);
if (colorChannel == null || colorChannel.IsEmpty)
return Color.white;
if (x < 0 || x >= width ||
y < 0 || y >= height)
{
return colorChannel.clearColor;
}
int offset;
ColorChunk colorChunk = colorChannel.FindChunkAndCoordinate(x, y, out offset);
if (colorChunk.Empty)
{
return colorChannel.clearColor;
}
else
{
int colorChunkRowOffset = partitionSizeX + 1;
Color tileColorx0y0 = colorChunk.colors[offset];
Color tileColorx1y0 = colorChunk.colors[offset + 1];
Color tileColorx0y1 = colorChunk.colors[offset + colorChunkRowOffset];
Color tileColorx1y1 = colorChunk.colors[offset + colorChunkRowOffset + 1];
float wx = x * data.tileSize.x + data.tileOrigin.x;
float wy = y * data.tileSize.y + data.tileOrigin.y;
float ix = (localPosition.x - wx) / data.tileSize.x;
float iy = (localPosition.y - wy) / data.tileSize.y;
Color cy0 = Color.Lerp(tileColorx0y0, tileColorx1y0, ix);
Color cy1 = Color.Lerp(tileColorx0y1, tileColorx1y1, ix);
return Color.Lerp(cy0, cy1, iy);
}
}
// ISpriteCollectionBuilder
public bool UsesSpriteCollection(tk2dSpriteCollectionData spriteCollection)
{
return spriteCollection == this.spriteCollection || _spriteCollectionInst == spriteCollection;
}
#if UNITY_EDITOR
public void BeginEditMode()
{
_inEditMode = true;
// Destroy all children
if (layers == null)
return;
ClearSpawnedInstances();
Build(BuildFlags.EditMode | BuildFlags.ForceBuild);
}
public void EndEditMode()
{
_inEditMode = false;
Build(BuildFlags.ForceBuild);
if (serializeRenderData && renderData != null)
{
#if (UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4)
Debug.LogError("Prefab needs to be updated");
#else
GameObject go = UnityEditor.PrefabUtility.FindValidUploadPrefabInstanceRoot(renderData);
Object obj = UnityEditor.PrefabUtility.GetPrefabParent(go);
if (obj != null)
UnityEditor.PrefabUtility.ReplacePrefab(go, obj, UnityEditor.ReplacePrefabOptions.ConnectToPrefab);
#endif
}
}
public bool AreSpritesInitialized()
{
return layers != null;
}
public bool HasColorChannel()
{
return (colorChannel != null && !colorChannel.IsEmpty);
}
public void CreateColorChannel()
{
colorChannel = new ColorChannel(width, height, partitionSizeX, partitionSizeY);
colorChannel.Create();
}
public void DeleteColorChannel()
{
colorChannel.Delete();
}
public void DeleteSprites(int layerId, int x0, int y0, int x1, int y1)
{
int numTilesX = x1 - x0 + 1;
int numTilesY = y1 - y0 + 1;
var layer = layers[layerId];
for (int y = 0; y < numTilesY; ++y)
{
for (int x = 0; x < numTilesX; ++x)
{
layer.SetTile(x0 + x, y0 + y, -1);
}
}
layer.OptimizeIncremental();
}
#endif
// used by util functions
public Mesh GetOrCreateMesh()
{
#if UNITY_EDITOR
Mesh mesh = new Mesh();
if (serializeRenderData && renderData)
{
if (serializedMeshPath == null) serializedMeshPath = "";
if (serializedMeshPath.Length == 0)
{
// find one serialized mesh
MeshFilter[] meshFilters = renderData.gameObject.GetComponentsInChildren<MeshFilter>();
foreach (var v in meshFilters)
{
Mesh m = v.sharedMesh;
serializedMeshPath = UnityEditor.AssetDatabase.GetAssetPath(m);
if (serializedMeshPath.Length > 0) break;
}
}
if (serializedMeshPath.Length == 0)
{
MeshCollider[] meshColliders = renderData.gameObject.GetComponentsInChildren<MeshCollider>();
foreach (var v in meshColliders)
{
Mesh m = v.sharedMesh;
serializedMeshPath = UnityEditor.AssetDatabase.GetAssetPath(m);
if (serializedMeshPath.Length > 0) break;
}
}
if (serializedMeshPath.Length == 0)
{
Debug.LogError("Unable to serialize meshes - please resave.");
serializeRenderData = false;
}
else
{
// save the mesh
string path = UnityEditor.AssetDatabase.GenerateUniqueAssetPath(serializedMeshPath);
UnityEditor.AssetDatabase.CreateAsset(mesh, path);
}
}
return mesh;
#else
return new Mesh();
#endif
}
public void TouchMesh(Mesh mesh)
{
#if UNITY_EDITOR
UnityEditor.EditorUtility.SetDirty(mesh);
#endif
}
public void DestroyMesh(Mesh mesh)
{
#if UNITY_EDITOR
if (UnityEditor.AssetDatabase.GetAssetPath(mesh).Length != 0)
{
mesh.Clear();
UnityEditor.AssetDatabase.DeleteAsset(UnityEditor.AssetDatabase.GetAssetPath(mesh));
}
else
{
DestroyImmediate(mesh);
}
#else
DestroyImmediate(mesh);
#endif
}
public Layer[] Layers
{
get { return layers; }
set { layers = value; }
}
public ColorChannel ColorChannel
{
get { return colorChannel; }
set { colorChannel = value; }
}
}
| |
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace IAMUserExampleTests
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Amazon.IdentityManagement;
using Amazon.IdentityManagement.Model;
using Amazon.S3;
using Amazon.S3.Model;
using Moq;
using Xunit;
/// <summary>
/// This examples shows how to use the AWS Identity and Access Management
/// (IAM) service to create and manage users and groups. The example was
/// created using the AWS SDK for .NET version 3.7 and .NET Core 5.0.
/// </summary>
public class IAMUserTests
{
private const string GroupName = "TestGroupName";
private const string PolicyName = "S3ReadOnlyAccess";
private const string S3ReadOnlyPolicy = "{" +
" \"Statement\" : [{" +
" \"Action\" : [\"s3:*\"]," +
" \"Effect\" : \"Allow\"," +
" \"Resource\" : \"*\"" +
"}]" +
"}";
private const string UserName = "S3ReadOnlyUser";
private const string AccessKeyId = "AKIAIOSFODNN7EXAMPLE";
string BucketName = "bucket-to-delete";
[Fact]
public async Task CreateGroupAsyncTest()
{
var mockIAMClient = new Mock<AmazonIdentityManagementServiceClient>();
mockIAMClient.Setup(client => client.CreateGroupAsync(
It.IsAny<CreateGroupRequest>(),
It.IsAny<CancellationToken>()
)).Callback<CreateGroupRequest, CancellationToken>((request, token) =>
{
if (!string.IsNullOrEmpty(request.GroupName))
{
Assert.Equal(request.GroupName, GroupName);
}
}).Returns((CreateGroupRequest r, CancellationToken token) =>
{
return Task.FromResult(new CreateGroupResponse()
{
Group = new Group
{
GroupName = GroupName,
},
HttpStatusCode = System.Net.HttpStatusCode.OK,
});
});
var client = mockIAMClient.Object;
var request = new CreateGroupRequest
{
GroupName = GroupName,
};
var response = await client.CreateGroupAsync(request);
var ok = (response is not null) &&
(response.HttpStatusCode == System.Net.HttpStatusCode.OK) &&
(response.Group.GroupName == GroupName);
Assert.True(ok, "Could not create group.");
}
[Fact]
public async Task PutGroupPolicyAsyncTest()
{
var mockIAMClient = new Mock<AmazonIdentityManagementServiceClient>();
mockIAMClient.Setup(client => client.PutGroupPolicyAsync(
It.IsAny<PutGroupPolicyRequest>(),
It.IsAny<CancellationToken>()
)).Callback<PutGroupPolicyRequest, CancellationToken>((request, token) =>
{
if (!string.IsNullOrEmpty(request.GroupName))
{
Assert.Equal(request.GroupName, GroupName);
}
}).Returns((PutGroupPolicyRequest r, CancellationToken token) =>
{
return Task.FromResult(new PutGroupPolicyResponse()
{
HttpStatusCode = System.Net.HttpStatusCode.OK,
});
});
var client = mockIAMClient.Object;
var request = new PutGroupPolicyRequest
{
GroupName = GroupName,
PolicyName = PolicyName,
PolicyDocument = S3ReadOnlyPolicy,
};
var response = await client.PutGroupPolicyAsync(request);
var ok = response.HttpStatusCode == System.Net.HttpStatusCode.OK;
Assert.True(ok, "Failed to add group policy.");
}
[Fact]
public async Task CreateUserAsyncTest()
{
var mockIAMClient = new Mock<AmazonIdentityManagementServiceClient>();
mockIAMClient.Setup(client => client.CreateUserAsync(
It.IsAny<CreateUserRequest>(),
It.IsAny<CancellationToken>()
)).Callback<CreateUserRequest, CancellationToken>((request, token) =>
{
if (!string.IsNullOrEmpty(request.UserName))
{
Assert.Equal(request.UserName, UserName);
}
}).Returns((CreateUserRequest r, CancellationToken token) =>
{
return Task.FromResult(new CreateUserResponse()
{
User = new User
{
UserName = UserName,
},
HttpStatusCode = System.Net.HttpStatusCode.OK,
});
});
var client = mockIAMClient.Object;
var request = new CreateUserRequest
{
UserName = UserName,
};
var response = await client.CreateUserAsync(request);
var ok = (response.HttpStatusCode == System.Net.HttpStatusCode.OK) && (response.User.UserName == UserName);
Assert.True(ok, "Was not able to create user.");
}
[Fact]
public async Task AddUserToGroupAsyncTest()
{
var mockIAMClient = new Mock<AmazonIdentityManagementServiceClient>();
mockIAMClient.Setup(client => client.AddUserToGroupAsync(
It.IsAny<AddUserToGroupRequest>(),
It.IsAny<CancellationToken>()
)).Callback<AddUserToGroupRequest, CancellationToken>((request, token) =>
{
if (!string.IsNullOrEmpty(request.GroupName))
{
Assert.Equal(request.GroupName, GroupName);
}
;
if (!string.IsNullOrEmpty(request.UserName))
{
Assert.Equal(request.UserName, UserName);
}
}).Returns((AddUserToGroupRequest r, CancellationToken token) =>
{
return Task.FromResult(new AddUserToGroupResponse()
{
HttpStatusCode = System.Net.HttpStatusCode.OK,
});
});
var client = mockIAMClient.Object;
var request = new AddUserToGroupRequest
{
GroupName = GroupName,
UserName = UserName,
};
var response = await client.AddUserToGroupAsync(request);
var ok = response.HttpStatusCode == System.Net.HttpStatusCode.OK;
Assert.True(ok, "Was not able to add the user to the group.");
}
[Fact]
public async Task CreateAccessKeyAsyncTest()
{
var mockIAMClient = new Mock<AmazonIdentityManagementServiceClient>();
mockIAMClient.Setup(client => client.CreateAccessKeyAsync(
It.IsAny<CreateAccessKeyRequest>(),
It.IsAny<CancellationToken>()
)).Callback<CreateAccessKeyRequest, CancellationToken>((request, token) =>
{
if (!string.IsNullOrEmpty(request.UserName))
{
Assert.Equal(request.UserName, UserName);
}
}).Returns((CreateAccessKeyRequest r, CancellationToken token) =>
{
return Task.FromResult(new CreateAccessKeyResponse()
{
AccessKey = new AccessKey
{
UserName = UserName,
},
HttpStatusCode = System.Net.HttpStatusCode.OK,
});
});
var client = mockIAMClient.Object;
var request = new CreateAccessKeyRequest
{
UserName = UserName,
};
var response = await client.CreateAccessKeyAsync(request);
var ok = (response.AccessKey.UserName == UserName) && (response.HttpStatusCode == System.Net.HttpStatusCode.OK);
Assert.True(ok, "Could not create AccessKey.");
}
[Fact]
public async Task ListBucketsAsyncTest()
{
var mockS3Client = new Mock<IAmazonS3>();
mockS3Client.Setup(client => client.ListBucketsAsync(
It.IsAny<CancellationToken>()
)).Returns((CancellationToken token) =>
{
return Task.FromResult(new ListBucketsResponse()
{
Buckets = new List<S3Bucket>
{
new S3Bucket
{
BucketName = "doc-example-bucket",
CreationDate = DateTime.Now,
},
new S3Bucket
{
BucketName = "doc-example-bucket1",
CreationDate = DateTime.Now,
},
new S3Bucket
{
BucketName = "doc-example-bucket2",
CreationDate = DateTime.Now,
},
},
HttpStatusCode = System.Net.HttpStatusCode.OK,
});
});
var client = mockS3Client.Object;
var response = await client.ListBucketsAsync();
var gotResponse = response is not null;
if (gotResponse)
{
var ok = (response.HttpStatusCode == System.Net.HttpStatusCode.OK) && (response.Buckets.Count == 3);
Assert.True(ok, "Couldn't get list of buckets.");
}
}
[Fact]
public async Task CleanUpResourcesTest()
{
var mockIAMClient = new Mock<AmazonIdentityManagementServiceClient>();
var mockS3Client = new Mock<AmazonS3Client>();
mockIAMClient.Setup(client => client.RemoveUserFromGroupAsync(
It.IsAny<RemoveUserFromGroupRequest>(),
It.IsAny<CancellationToken>()
)).Callback<RemoveUserFromGroupRequest, CancellationToken>((request, token) =>
{
if (!string.IsNullOrEmpty(request.GroupName))
{
Assert.Equal(request.GroupName, GroupName);
}
}).Returns((RemoveUserFromGroupRequest r, CancellationToken token) =>
{
return Task.FromResult(new RemoveUserFromGroupResponse()
{
HttpStatusCode = System.Net.HttpStatusCode.OK,
});
});
mockIAMClient.Setup(client => client.DeleteAccessKeyAsync(
It.IsAny<DeleteAccessKeyRequest>(),
It.IsAny<CancellationToken>()
)).Callback<DeleteAccessKeyRequest, CancellationToken>((request, token) =>
{
if (!string.IsNullOrEmpty(request.UserName))
{
Assert.Equal(request.UserName, UserName);
}
if (!string.IsNullOrEmpty(request.AccessKeyId))
{
Assert.Equal(request.AccessKeyId, AccessKeyId);
}
}).Returns((DeleteAccessKeyRequest r, CancellationToken token) =>
{
return Task.FromResult(new DeleteAccessKeyResponse()
{
HttpStatusCode = System.Net.HttpStatusCode.OK,
});
});
mockIAMClient.Setup(client => client.DeleteUserAsync(
It.IsAny<DeleteUserRequest>(),
It.IsAny<CancellationToken>()
)).Callback<DeleteUserRequest, CancellationToken>((request, token) =>
{
if (!string.IsNullOrEmpty(request.UserName))
{
Assert.Equal(request.UserName, UserName);
}
}).Returns((DeleteUserRequest r, CancellationToken token) =>
{
return Task.FromResult(new DeleteUserResponse()
{
HttpStatusCode = System.Net.HttpStatusCode.OK,
});
});
mockIAMClient.Setup(client => client.DeleteGroupPolicyAsync(
It.IsAny<DeleteGroupPolicyRequest>(),
It.IsAny<CancellationToken>()
)).Callback<DeleteGroupPolicyRequest, CancellationToken>((request, token) =>
{
if (!string.IsNullOrEmpty(request.GroupName))
{
Assert.Equal(request.GroupName, GroupName);
}
}).Returns((DeleteGroupPolicyRequest r, CancellationToken token) =>
{
return Task.FromResult(new DeleteGroupPolicyResponse()
{
HttpStatusCode = System.Net.HttpStatusCode.OK,
});
});
mockIAMClient.Setup(client => client.DeleteGroupAsync(
It.IsAny<DeleteGroupRequest>(),
It.IsAny<CancellationToken>()
)).Callback<DeleteGroupRequest, CancellationToken>((request, token) =>
{
if (!string.IsNullOrEmpty(request.GroupName))
{
Assert.Equal(request.GroupName, GroupName);
}
}).Returns((DeleteGroupRequest r, CancellationToken token) =>
{
return Task.FromResult(new DeleteGroupResponse()
{
HttpStatusCode = System.Net.HttpStatusCode.OK,
});
});
var iamClient = mockIAMClient.Object;
mockS3Client.Setup(client => client.DeleteBucketAsync(
It.IsAny<string>(),
It.IsAny<CancellationToken>()
)).Callback<string, CancellationToken>((bucketName, token) =>
{
if (!string.IsNullOrEmpty(bucketName))
{
Assert.Equal(bucketName, BucketName);
}
}).Returns((string bucketName, CancellationToken token) =>
{
return Task.FromResult(new DeleteBucketResponse()
{
HttpStatusCode = System.Net.HttpStatusCode.OK,
});
});
var s3Client = mockS3Client.Object;
await IAMUserExample.IAMUser.CleanUpResources(iamClient, s3Client, UserName, GroupName, BucketName, AccessKeyId);
}
}
}
| |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Universal charset detector code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Shy Shalom <shooshX@gmail.com>
* Rudi Pettazzi <rudi.pettazzi@gmail.com> (C# port)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
namespace UniversalDetector.Core
{
public class ThaiModel : SequenceModel
{
/****************************************************************
255: Control characters that usually does not exist in any text
254: Carriage/Return
253: symbol (punctuation) that does not belong to word
252: 0 - 9
*****************************************************************/
// The following result for thai was collected from a limited sample (1M)
private readonly static byte[] TIS620_CHAR_TO_ORDER_MAP = {
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10
+253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30
253,182,106,107,100,183,184,185,101, 94,186,187,108,109,110,111, //40
188,189,190, 89, 95,112,113,191,192,193,194,253,253,253,253,253, //50
253, 64, 72, 73,114, 74,115,116,102, 81,201,117, 90,103, 78, 82, //60
96,202, 91, 79, 84,104,105, 97, 98, 92,203,253,253,253,253,253, //70
209,210,211,212,213, 88,214,215,216,217,218,219,220,118,221,222,
223,224, 99, 85, 83,225,226,227,228,229,230,231,232,233,234,235,
236, 5, 30,237, 24,238, 75, 8, 26, 52, 34, 51,119, 47, 58, 57,
49, 53, 55, 43, 20, 19, 44, 14, 48, 3, 17, 25, 39, 62, 31, 54,
45, 9, 16, 2, 61, 15,239, 12, 42, 46, 18, 21, 76, 4, 66, 63,
22, 10, 1, 36, 23, 13, 40, 27, 32, 35, 86,240,241,242,243,244,
11, 28, 41, 29, 33,245, 50, 37, 6, 7, 67, 77, 38, 93,246,247,
68, 56, 59, 65, 69, 60, 70, 80, 71, 87,248,249,250,251,252,253,
};
//Model Table:
//total sequences: 100%
//first 512 sequences: 92.6386%
//first 1024 sequences:7.3177%
//rest sequences: 1.0230%
//negative sequences: 0.0436%
private readonly static byte[] THAI_LANG_MODEL = {
0,1,3,3,3,3,0,0,3,3,0,3,3,0,3,3,3,3,3,3,3,3,0,0,3,3,3,0,3,3,3,3,
0,3,3,0,0,0,1,3,0,3,3,2,3,3,0,1,2,3,3,3,3,0,2,0,2,0,0,3,2,1,2,2,
3,0,3,3,2,3,0,0,3,3,0,3,3,0,3,3,3,3,3,3,3,3,3,0,3,2,3,0,2,2,2,3,
0,2,3,0,0,0,0,1,0,1,2,3,1,1,3,2,2,0,1,1,0,0,1,0,0,0,0,0,0,0,1,1,
3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,3,3,2,3,2,3,3,2,2,2,
3,1,2,3,0,3,3,2,2,1,2,3,3,1,2,0,1,3,0,1,0,0,1,0,0,0,0,0,0,0,1,1,
3,3,2,2,3,3,3,3,1,2,3,3,3,3,3,2,2,2,2,3,3,2,2,3,3,2,2,3,2,3,2,2,
3,3,1,2,3,1,2,2,3,3,1,0,2,1,0,0,3,1,2,1,0,0,1,0,0,0,0,0,0,1,0,1,
3,3,3,3,3,3,2,2,3,3,3,3,2,3,2,2,3,3,2,2,3,2,2,2,2,1,1,3,1,2,1,1,
3,2,1,0,2,1,0,1,0,1,1,0,1,1,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,
3,3,3,2,3,2,3,3,2,2,3,2,3,3,2,3,1,1,2,3,2,2,2,3,2,2,2,2,2,1,2,1,
2,2,1,1,3,3,2,1,0,1,2,2,0,1,3,0,0,0,1,1,0,0,0,0,0,2,3,0,0,2,1,1,
3,3,2,3,3,2,0,0,3,3,0,3,3,0,2,2,3,1,2,2,1,1,1,0,2,2,2,0,2,2,1,1,
0,2,1,0,2,0,0,2,0,1,0,0,1,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,0,
3,3,2,3,3,2,0,0,3,3,0,2,3,0,2,1,2,2,2,2,1,2,0,0,2,2,2,0,2,2,1,1,
0,2,1,0,2,0,0,2,0,1,1,0,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,
3,3,2,3,2,3,2,0,2,2,1,3,2,1,3,2,1,2,3,2,2,3,0,2,3,2,2,1,2,2,2,2,
1,2,2,0,0,0,0,2,0,1,2,0,1,1,1,0,1,0,3,1,1,0,0,0,0,0,0,0,0,0,1,0,
3,3,2,3,3,2,3,2,2,2,3,2,2,3,2,2,1,2,3,2,2,3,1,3,2,2,2,3,2,2,2,3,
3,2,1,3,0,1,1,1,0,2,1,1,1,1,1,0,1,0,1,1,0,0,0,0,0,0,0,0,0,2,0,0,
1,0,0,3,0,3,3,3,3,3,0,0,3,0,2,2,3,3,3,3,3,0,0,0,1,1,3,0,0,0,0,2,
0,0,1,0,0,0,0,0,0,0,2,3,0,0,0,3,0,2,0,0,0,0,0,3,0,0,0,0,0,0,0,0,
2,0,3,3,3,3,0,0,2,3,0,0,3,0,3,3,2,3,3,3,3,3,0,0,3,3,3,0,0,0,3,3,
0,0,3,0,0,0,0,2,0,0,2,1,1,3,0,0,1,0,0,2,3,0,1,0,0,0,0,0,0,0,1,0,
3,3,3,3,2,3,3,3,3,3,3,3,1,2,1,3,3,2,2,1,2,2,2,3,1,1,2,0,2,1,2,1,
2,2,1,0,0,0,1,1,0,1,0,1,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,
3,0,2,1,2,3,3,3,0,2,0,2,2,0,2,1,3,2,2,1,2,1,0,0,2,2,1,0,2,1,2,2,
0,1,1,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,2,1,3,3,1,1,3,0,2,3,1,1,3,2,1,1,2,0,2,2,3,2,1,1,1,1,1,2,
3,0,0,1,3,1,2,1,2,0,3,0,0,0,1,0,3,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,
3,3,1,1,3,2,3,3,3,1,3,2,1,3,2,1,3,2,2,2,2,1,3,3,1,2,1,3,1,2,3,0,
2,1,1,3,2,2,2,1,2,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,
3,3,2,3,2,3,3,2,3,2,3,2,3,3,2,1,0,3,2,2,2,1,2,2,2,1,2,2,1,2,1,1,
2,2,2,3,0,1,3,1,1,1,1,0,1,1,0,2,1,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,2,3,2,2,1,1,3,2,3,2,3,2,0,3,2,2,1,2,0,2,2,2,1,2,2,2,2,1,
3,2,1,2,2,1,0,2,0,1,0,0,1,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,1,
3,3,3,3,3,2,3,1,2,3,3,2,2,3,0,1,1,2,0,3,3,2,2,3,0,1,1,3,0,0,0,0,
3,1,0,3,3,0,2,0,2,1,0,0,3,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,2,3,2,3,3,0,1,3,1,1,2,1,2,1,1,3,1,1,0,2,3,1,1,1,1,1,1,1,1,
3,1,1,2,2,2,2,1,1,1,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
3,2,2,1,1,2,1,3,3,2,3,2,2,3,2,2,3,1,2,2,1,2,0,3,2,1,2,2,2,2,2,1,
3,2,1,2,2,2,1,1,1,1,0,0,1,1,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,3,1,3,3,0,2,1,0,3,2,0,0,3,1,0,1,1,0,1,0,0,0,0,0,1,
1,0,0,1,0,3,2,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,0,2,2,2,3,0,0,1,3,0,3,2,0,3,2,2,3,3,3,3,3,1,0,2,2,2,0,2,2,1,2,
0,2,3,0,0,0,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
3,0,2,3,1,3,3,2,3,3,0,3,3,0,3,2,2,3,2,3,3,3,0,0,2,2,3,0,1,1,1,3,
0,0,3,0,0,0,2,2,0,1,3,0,1,2,2,2,3,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,
3,2,3,3,2,0,3,3,2,2,3,1,3,2,1,3,2,0,1,2,2,0,2,3,2,1,0,3,0,0,0,0,
3,0,0,2,3,1,3,0,0,3,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,1,3,2,2,2,1,2,0,1,3,1,1,3,1,3,0,0,2,1,1,1,1,2,1,1,1,0,2,1,0,1,
1,2,0,0,0,3,1,1,0,0,0,0,1,0,1,0,0,1,0,1,0,0,0,0,0,3,1,0,0,0,1,0,
3,3,3,3,2,2,2,2,2,1,3,1,1,1,2,0,1,1,2,1,2,1,3,2,0,0,3,1,1,1,1,1,
3,1,0,2,3,0,0,0,3,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,2,3,0,3,3,0,2,0,0,0,0,0,0,0,3,0,0,1,0,0,0,0,0,0,0,0,0,0,0,
0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,2,3,1,3,0,0,1,2,0,0,2,0,3,3,2,3,3,3,2,3,0,0,2,2,2,0,0,0,2,2,
0,0,1,0,0,0,0,3,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,
0,0,0,3,0,2,0,0,0,0,0,0,0,0,0,0,1,2,3,1,3,3,0,0,1,0,3,0,0,0,0,0,
0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,1,2,3,1,2,3,1,0,3,0,2,2,1,0,2,1,1,2,0,1,0,0,1,1,1,1,0,1,0,0,
1,0,0,0,0,1,1,0,3,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,2,1,0,1,1,1,3,1,2,2,2,2,2,2,1,1,1,1,0,3,1,0,1,3,1,1,1,1,
1,1,0,2,0,1,3,1,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,1,
3,0,2,2,1,3,3,2,3,3,0,1,1,0,2,2,1,2,1,3,3,1,0,0,3,2,0,0,0,0,2,1,
0,1,0,0,0,0,1,2,0,1,1,3,1,1,2,2,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,
0,0,3,0,0,1,0,0,0,3,0,0,3,0,3,1,0,1,1,1,3,2,0,0,0,3,0,0,0,0,2,0,
0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0,0,
3,3,1,3,2,1,3,3,1,2,2,0,1,2,1,0,1,2,0,0,0,0,0,3,0,0,0,3,0,0,0,0,
3,0,0,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,0,1,2,0,3,3,3,2,2,0,1,1,0,1,3,0,0,0,2,2,0,0,0,0,3,1,0,1,0,0,0,
0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,0,2,3,1,2,0,0,2,1,0,3,1,0,1,2,0,1,1,1,1,3,0,0,3,1,1,0,2,2,1,1,
0,2,0,0,0,0,0,1,0,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,0,0,3,1,2,0,0,2,2,0,1,2,0,1,0,1,3,1,2,1,0,0,0,2,0,3,0,0,0,1,0,
0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,0,1,1,2,2,0,0,0,2,0,2,1,0,1,1,0,1,1,1,2,1,0,0,1,1,1,0,2,1,1,1,
0,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,1,
0,0,0,2,0,1,3,1,1,1,1,0,0,0,0,3,2,0,1,0,0,0,1,2,0,0,0,1,0,0,0,0,
0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,3,3,3,3,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,0,2,3,2,2,0,0,0,1,0,0,0,0,2,3,2,1,2,2,3,0,0,0,2,3,1,0,0,0,1,1,
0,0,1,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,
3,3,2,2,0,1,0,0,0,0,2,0,2,0,1,0,0,0,1,1,0,0,0,2,1,0,1,0,1,1,0,0,
0,1,0,2,0,0,1,0,3,0,1,0,0,0,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,1,0,0,1,0,0,0,0,0,1,1,2,0,0,0,0,1,0,0,1,3,1,0,0,0,0,1,1,0,0,
0,1,0,0,0,0,3,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,
3,3,1,1,1,1,2,3,0,0,2,1,1,1,1,1,0,2,1,1,0,0,0,2,1,0,1,2,1,1,0,1,
2,1,0,3,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,3,1,0,0,0,0,0,0,0,3,0,0,0,3,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,
0,0,0,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,2,0,0,0,0,0,0,1,2,1,0,1,1,0,2,0,0,1,0,0,2,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,2,0,0,0,1,3,0,1,0,0,0,2,0,0,0,0,0,0,0,1,2,0,0,0,0,0,
3,3,0,0,1,1,2,0,0,1,2,1,0,1,1,1,0,1,1,0,0,2,1,1,0,1,0,0,1,1,1,0,
0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,2,2,1,0,0,0,0,1,0,0,0,0,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,
2,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,3,0,0,1,1,0,0,0,2,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,1,0,1,2,0,1,2,0,0,1,1,0,2,0,1,0,0,1,0,0,0,0,1,0,0,0,2,0,0,0,0,
1,0,0,1,0,1,1,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,1,0,0,0,0,0,0,0,1,1,0,1,1,0,2,1,3,0,0,0,0,1,1,0,0,0,0,0,0,0,3,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,0,1,0,1,0,0,2,0,0,2,0,0,1,1,2,0,0,1,1,0,0,0,1,0,0,0,1,1,0,0,0,
1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,
1,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,1,1,0,0,0,
2,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,0,0,0,0,2,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,3,0,0,0,
2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,1,0,0,0,0,
1,0,0,0,0,0,0,0,0,1,0,0,0,0,2,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,1,1,0,0,2,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
};
public ThaiModel(byte[] charToOrderMap, string name)
: base(TIS620_CHAR_TO_ORDER_MAP, THAI_LANG_MODEL,
0.926386f, false, "TIS-620")
{
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
namespace ELua {
/// <summary>
/// @author Easily
/// </summary>
public class WordExExpression : Expression {
public Expression targetExp;
public WordExExpression(List<Expression> list, int position, int len) {
type = Type.WordEx;
targetExp = list[position];
}
public override string GetDebugInfo() {
return DebugInfo.ToString(targetExp);
}
public override string ToString() {
return targetExp.ToString();
}
}
/// <summary>
/// @author Easily
/// </summary>
public class WordList1Expression : Expression {
public List<Expression> itemsList;
public WordList1Expression(List<Expression> list, int position, int len) {
type = Type.WordList1;
itemsList = new List<Expression>();
for (var i = 0; i < len; i++) {
itemsList.Add(((WordExExpression)list[position + i]).targetExp);
}
}
public string[] ToParams() {
return itemsList.Cast<WordExpression>().Select(t => t.value).ToArray();
}
public override void Generate(ModuleContext context) {
for (var i = itemsList.Count - 1; i >= 0; i--) {
itemsList[i].Generate(context);
}
}
public override string GetDebugInfo() {
return DebugInfo.ToString(itemsList.ToArray());
}
public override string ToString() {
return itemsList.FormatListString();
}
}
/// <summary>
/// @author Easily
/// </summary>
public class WordList2Expression : Expression {
public List<Expression> itemsList;
public WordList2Expression(List<Expression> list, int position, int len) {
type = Type.WordList2;
itemsList = new List<Expression>();
for (var i = 0; i < len; i++) {
itemsList.Add(((WordExExpression)list[position + i]).targetExp);
}
}
public WordList2Expression(List<Expression> itemsList) {
this.itemsList = itemsList;
}
public void ToVars() {
for (var i = 0; i < itemsList.Count; i++) {
itemsList[i] = new LocalExpression(itemsList[i]);
}
}
public override void Generate(ModuleContext context) {
for (var i = itemsList.Count - 1; i >= 0; i--) {
itemsList[i].Generate(context);
}
}
public override string GetDebugInfo() {
return DebugInfo.ToString(itemsList.ToArray());
}
public override string ToString() {
return itemsList.FormatListString();
}
}
/// <summary>
/// @author Easily
/// </summary>
public class LeftExExpression : Expression {
public Expression targetExp;
public LeftExExpression(List<Expression> list, int position, int len) {
type = Type.LeftEx;
targetExp = list[position];
}
public override string GetDebugInfo() {
return DebugInfo.ToString(targetExp);
}
public override string ToString() {
return targetExp.ToString();
}
}
/// <summary>
/// @author Easily
/// </summary>
public class LeftList1Expression : Expression {
public List<Expression> itemsList;
public LeftList1Expression(List<Expression> list, int position, int len) {
type = Type.LeftList1;
itemsList = new List<Expression>();
for (var i = 0; i < len; i++) {
var targetExp = ((LeftExExpression)list[position + i]).targetExp;
targetExp.isBinder = true;
itemsList.Add(targetExp);
}
}
public override void Extract(SyntaxContext context) {
for (var i = 0; i < itemsList.Count; i++) {
itemsList[i] = ParserHelper.Extract(context, itemsList[i]);
}
}
public override void Generate(ModuleContext context) {
for (var i = itemsList.Count - 1; i >= 0; i--) {
itemsList[i].Generate(context);
}
}
public override string GetDebugInfo() {
return DebugInfo.ToString(itemsList.ToArray());
}
public override string ToString() {
return itemsList.FormatListString();
}
}
/// <summary>
/// @author Easily
/// </summary>
public class LeftList2Expression : Expression {
public List<Expression> itemsList;
public LeftList2Expression(List<Expression> list, int position, int len) {
type = Type.LeftList2;
itemsList = new List<Expression>();
for (var i = 0; i < len; i++) {
var targetExp = ((LeftExExpression)list[position + i]).targetExp;
targetExp.isBinder = true;
itemsList.Add(targetExp);
}
}
public LeftList2Expression(List<Expression> itemsList) {
this.itemsList = itemsList;
}
public override void Extract(SyntaxContext context) {
for (var i = 0; i < itemsList.Count; i++) {
itemsList[i] = ParserHelper.Extract(context, itemsList[i]);
}
}
public override void Generate(ModuleContext context) {
for (var i = itemsList.Count - 1; i >= 0; i--) {
itemsList[i].Generate(context);
}
}
public override string GetDebugInfo() {
return DebugInfo.ToString(itemsList.ToArray());
}
public override string ToString() {
return itemsList.FormatListString();
}
}
/// <summary>
/// @author Easily
/// </summary>
public class RightExExpression : Expression {
public Expression targetExp;
public RightExExpression(List<Expression> list, int position, int len) {
type = Type.RightEx;
targetExp = list[position];
}
public override string GetDebugInfo() {
return DebugInfo.ToString(targetExp);
}
public override string ToString() {
return targetExp.ToString();
}
}
/// <summary>
/// @author Easily
/// </summary>
public class RightList1Expression : Expression {
public List<Expression> itemsList;
public RightList1Expression(List<Expression> list, int position, int len) {
type = Type.RightList1;
itemsList = new List<Expression>();
for (var i = 0; i < len; i++) {
itemsList.Add(((RightExExpression)list[position + i]).targetExp);
}
}
public RightList1Expression(List<Expression> itemsList) {
this.itemsList = itemsList;
}
public override void Extract(SyntaxContext context) {
for (var i = 0; i < itemsList.Count; i++) {
itemsList[i] = ParserHelper.Extract(context, itemsList[i]);
}
}
public override void Generate(ModuleContext context) {
for (var i = itemsList.Count - 1; i >= 0; i--) {
itemsList[i].Generate(context);
}
}
public override string GetDebugInfo() {
return DebugInfo.ToString(itemsList.ToArray());
}
public override string ToString() {
return itemsList.FormatListString();
}
}
/// <summary>
/// @author Easily
/// </summary>
public class RightList2Expression : Expression {
public List<Expression> itemsList;
public RightList2Expression(List<Expression> list, int position, int len) {
type = Type.RightList2;
itemsList = new List<Expression>();
for (var i = 0; i < len; i++) {
itemsList.Add(((RightExExpression)list[position + i]).targetExp);
}
}
public RightList2Expression(List<Expression> itemsList) {
this.itemsList = itemsList;
}
public override void Extract(SyntaxContext context) {
for (var i = 0; i < itemsList.Count; i++) {
itemsList[i] = ParserHelper.Extract(context, itemsList[i]);
}
}
public override void Generate(ModuleContext context) {
for (var i = itemsList.Count - 1; i >= 0; i--) {
itemsList[i].Generate(context);
}
}
public override string GetDebugInfo() {
return DebugInfo.ToString(itemsList.ToArray());
}
public override string ToString() {
return itemsList.FormatListString();
}
}
/// <summary>
/// @author Easily
/// </summary>
public class KV1Expression : Expression {
public Expression keyExp;
public Expression valueExp;
public KV1Expression(List<Expression> list, int position, int len) {
type = Type.KV1;
keyExp = ParserHelper.Word2String(list[position]);
valueExp = list[position + 2];
}
public override void Extract(SyntaxContext context) {
keyExp = ParserHelper.Extract(context, keyExp);
valueExp = ParserHelper.Extract(context, valueExp);
}
public override void Generate(ModuleContext context) {
valueExp.Generate(context);
keyExp.Generate(context);
}
public override string GetDebugInfo() {
return DebugInfo.ToString(keyExp, valueExp);
}
public override string ToString() {
return string.Format("[{0}]={1}", keyExp, valueExp);
}
}
/// <summary>
/// @author Easily
/// </summary>
public class KVList1Expression : Expression {
public List<Expression> itemsList;
public KVList1Expression(List<Expression> list, int position, int len) {
type = Type.KVList1;
itemsList = new List<Expression>();
for (var i = 0; i < len; i++) {
itemsList.Add(list[position + i]);
}
}
public override void Extract(SyntaxContext context) {
for (var i = 0; i < itemsList.Count; i++) {
itemsList[i].Extract(context);
}
}
public override void Generate(ModuleContext context) {
for (var i = itemsList.Count - 1; i >= 0; i--) {
itemsList[i].Generate(context);
}
}
public override string GetDebugInfo() {
return DebugInfo.ToString(itemsList.ToArray());
}
public override string ToString() {
return itemsList.FormatListString();
}
}
/// <summary>
/// @author Easily
/// </summary>
public class KV2Expression : Expression {
public Expression keyExp;
public Expression valueExp;
public KV2Expression(List<Expression> list, int position, int len) {
type = Type.KV2;
keyExp = list[position + 1];
valueExp = list[position + 4];
}
public override void Extract(SyntaxContext context) {
keyExp = ParserHelper.Extract(context, keyExp);
valueExp = ParserHelper.Extract(context, valueExp);
}
public override void Generate(ModuleContext context) {
valueExp.Generate(context);
keyExp.Generate(context);
}
public override string GetDebugInfo() {
return DebugInfo.ToString(keyExp, valueExp);
}
public override string ToString() {
return string.Format("[{0}]={1}", keyExp, valueExp);
}
}
/// <summary>
/// @author Easily
/// </summary>
public class KVList2Expression : Expression {
public List<Expression> itemsList;
public KVList2Expression(List<Expression> list, int position, int len) {
type = Type.KVList2;
itemsList = new List<Expression>();
for (var i = 0; i < len; i++) {
itemsList.Add(list[position + i]);
}
}
public override void Extract(SyntaxContext context) {
for (var i = 0; i < itemsList.Count; i++) {
itemsList[i].Extract(context);
}
}
public override void Generate(ModuleContext context) {
for (var i = itemsList.Count - 1; i >= 0; i--) {
itemsList[i].Generate(context);
}
}
public override string GetDebugInfo() {
return DebugInfo.ToString(itemsList.ToArray());
}
public override string ToString() {
return itemsList.FormatListString();
}
}
}
| |
//
// Copyright (c) 2004-2018 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.LayoutRenderers
{
using System;
using System.ComponentModel;
using System.IO;
using System.Text;
using NLog.Config;
using NLog.Internal;
/// <summary>
/// The call site (class name, method name and source information).
/// </summary>
[LayoutRenderer("callsite")]
[ThreadAgnostic]
[ThreadSafe]
public class CallSiteLayoutRenderer : LayoutRenderer, IUsesStackTrace
{
/// <summary>
/// Initializes a new instance of the <see cref="CallSiteLayoutRenderer" /> class.
/// </summary>
public CallSiteLayoutRenderer()
{
ClassName = true;
MethodName = true;
CleanNamesOfAnonymousDelegates = false;
IncludeNamespace = true;
#if !SILVERLIGHT
FileName = false;
IncludeSourcePath = true;
#endif
}
/// <summary>
/// Gets or sets a value indicating whether to render the class name.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(true)]
public bool ClassName { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to render the include the namespace with <see cref="ClassName"/>.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(true)]
public bool IncludeNamespace { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to render the method name.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(true)]
public bool MethodName { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the method name will be cleaned up if it is detected as an anonymous delegate.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(false)]
public bool CleanNamesOfAnonymousDelegates { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the method and class names will be cleaned up if it is detected as an async continuation
/// (everything after an await-statement inside of an async method).
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(false)]
public bool CleanNamesOfAsyncContinuations { get; set; }
/// <summary>
/// Gets or sets the number of frames to skip.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(0)]
public int SkipFrames { get; set; }
#if !SILVERLIGHT
/// <summary>
/// Gets or sets a value indicating whether to render the source file name and line number.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(false)]
public bool FileName { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to include source file path.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(true)]
public bool IncludeSourcePath { get; set; }
#endif
/// <summary>
/// Gets the level of stack trace information required by the implementing class.
/// </summary>
StackTraceUsage IUsesStackTrace.StackTraceUsage
{
get
{
#if !SILVERLIGHT
if (FileName)
{
return StackTraceUsage.Max;
}
#endif
return StackTraceUsage.WithoutSource;
}
}
/// <summary>
/// Renders the call site and appends it to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="logEvent">Logging event.</param>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
if (logEvent.CallSiteInformation != null)
{
if (ClassName || MethodName)
{
var method = logEvent.CallSiteInformation.GetCallerStackFrameMethod(SkipFrames);
if (ClassName)
{
string className = logEvent.CallSiteInformation.GetCallerClassName(method, IncludeNamespace, CleanNamesOfAsyncContinuations, CleanNamesOfAnonymousDelegates);
if (string.IsNullOrEmpty(className))
className = "<no type>";
builder.Append(className);
}
if (MethodName)
{
string methodName = logEvent.CallSiteInformation.GetCallerMemberName(method, false, CleanNamesOfAsyncContinuations, CleanNamesOfAnonymousDelegates);
if (string.IsNullOrEmpty(methodName))
methodName = "<no method>";
if (ClassName)
{
builder.Append(".");
}
builder.Append(methodName);
}
}
#if !SILVERLIGHT
if (FileName)
{
string fileName = logEvent.CallSiteInformation.GetCallerFilePath(SkipFrames);
if (!string.IsNullOrEmpty(fileName))
{
int lineNumber = logEvent.CallSiteInformation.GetCallerLineNumber(SkipFrames);
AppendFileName(builder, fileName, lineNumber);
}
}
#endif
}
}
#if !SILVERLIGHT
private void AppendFileName(StringBuilder builder, string fileName, int lineNumber)
{
builder.Append("(");
if (IncludeSourcePath)
{
builder.Append(fileName);
}
else
{
builder.Append(Path.GetFileName(fileName));
}
builder.Append(":");
builder.AppendInvariant(lineNumber);
builder.Append(")");
}
#endif
}
}
| |
#region License Header
// /*******************************************************************************
// * Open Behavioral Health Information Technology Architecture (OBHITA.org)
// *
// * 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 <organization> 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ******************************************************************************/
#endregion
namespace ProCenter.Domain.Tests.AssessmentModule
{
#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading;
using CommonModule;
using Domain.AssessmentModule;
using Domain.AssessmentModule.Event;
using Infrastructure;
using Infrastructure.EventStore;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using NSubstitute;
using Pillar.Common.Metadata;
using Pillar.Common.Tests;
using Pillar.Common.Utility;
using Pillar.Domain.Event;
using ProCenter.Common;
using ProCenter.Domain.AssessmentModule.Lookups;
using ProCenter.Domain.AssessmentModule.Metadata;
using ProCenter.Domain.AssessmentModule.Rules;
#endregion
[TestClass]
public class AssessmentInstanceTests
{
#region Public Methods and Operators
private const string assessmentName = "TestName";
[TestMethod]
public void ShouldApplyCreatedEvent()
{
using (var serviceLocatorFixture = new ServiceLocatorFixture())
{
// Setup
SetupServiceLocatorFixture(serviceLocatorFixture);
var events = new List<IDomainEvent>();
CommitEvent.RegisterAll(events.Add);
// Exercise
Guid patientGuid = CombGuid.NewCombGuid();
var assessmentDefinition = Substitute.For<AssessmentDefinition>();
var assessment = new AssessmentInstanceFactory().Create(assessmentDefinition, patientGuid, "TestName", false);
// Verify
Assert.AreEqual(1, events.Count);
var createdEvent = events[0];
Assert.IsNotNull(createdEvent);
Assert.AreEqual(typeof (AssessmentCreatedEvent), createdEvent.GetType());
Assert.AreEqual((createdEvent as AssessmentCreatedEvent).PatientKey, patientGuid);
Assert.AreEqual((createdEvent as AssessmentCreatedEvent).AssessmentName, assessmentName);
Assert.AreEqual(1, assessment.Version);
}
}
[TestMethod]
public void ShouldApplyItemUpdatedEvent()
{
using (var serviceLocatorFixture = new ServiceLocatorFixture())
{
// Setup
SetupServiceLocatorFixture(serviceLocatorFixture);
var events = new List<IDomainEvent>();
CommitEvent.RegisterAll(events.Add);
// Exercise
Guid patientGuid = CombGuid.NewCombGuid();
var assessmentDefinition = Substitute.For<AssessmentDefinition>();
var assessment = new AssessmentInstanceFactory().Create(assessmentDefinition, patientGuid, "TestName", false);
assessment.UpdateItem(new ItemDefinition(new CodedConcept(new CodeSystem("1", "1", "Test"), "1", "Test"), ItemType.Question, null), 0);
// Verify
Assert.AreEqual(2, events.Count);
var itemUpdatedEvent = events[1];
Assert.IsNotNull(itemUpdatedEvent);
Assert.AreEqual(typeof (ItemUpdatedEvent), itemUpdatedEvent.GetType());
Assert.AreEqual((itemUpdatedEvent as ItemUpdatedEvent).Value, 0);
Assert.AreEqual(2, assessment.Version);
}
}
[TestMethod]
public void ShouldApplySubmittedEvent()
{
using (var serviceLocatorFixture = new ServiceLocatorFixture())
{
// Setup
SetupServiceLocatorFixture(serviceLocatorFixture);
var events = new List<IDomainEvent>();
CommitEvent.RegisterAll(events.Add);
// Exercise
Guid patientGuid = CombGuid.NewCombGuid();
var assessmentDefinition = Substitute.For<AssessmentDefinition>();
var assessment = new AssessmentInstanceFactory().Create(assessmentDefinition, patientGuid, "TestName", false);
assessment.Submit();
// Verify
Assert.AreEqual(2, events.Count);
var submittedEvent = events[1];
Assert.IsNotNull(submittedEvent);
Assert.AreEqual(typeof (AssessmentSubmittedEvent), submittedEvent.GetType());
Assert.AreEqual((submittedEvent as AssessmentSubmittedEvent).Submit, true);
Assert.AreEqual(2, assessment.Version);
}
}
[TestMethod]
public void ShouldApplyScoredEvent()
{
using (var serviceLocatorFixture = new ServiceLocatorFixture())
{
// Setup
SetupServiceLocatorFixture(serviceLocatorFixture);
var events = new List<IDomainEvent>();
CommitEvent.RegisterAll(events.Add);
// Exercise
var patientGuid = CombGuid.NewCombGuid();
var assessmentDefinition = Substitute.For<AssessmentDefinition>();
var assessment = new AssessmentInstanceFactory().Create(assessmentDefinition, patientGuid, "TestName", false);
assessment.ScoreComplete(new CodedConcept(CodeSystems.Obhita, "dummayCode", ""), "result");
// Verify
Assert.AreEqual(2, events.Count);
var scoredEvent = events[1];
Assert.IsNotNull(scoredEvent);
Assert.AreEqual(typeof (AssessmentScoredEvent), scoredEvent.GetType());
Assert.AreEqual((scoredEvent as AssessmentScoredEvent).Value, "result");
Assert.AreEqual((scoredEvent as AssessmentScoredEvent).ScoreCode.Code, "dummayCode");
Assert.IsNull((scoredEvent as AssessmentScoredEvent).Guidance);
Assert.AreEqual(2, assessment.Version);
}
}
[TestMethod]
public void ShouldApplyAddedToWorkflowEvent()
{
using (var serviceLocatorFixture = new ServiceLocatorFixture())
{
// Setup
SetupServiceLocatorFixture(serviceLocatorFixture);
var events = new List<IDomainEvent>();
CommitEvent.RegisterAll(events.Add);
// Exercise
var patientGuid = CombGuid.NewCombGuid();
var assessmentDefinition = Substitute.For<AssessmentDefinition>();
var assessment = new AssessmentInstanceFactory().Create(assessmentDefinition, patientGuid, "TestName", false);
var workflowKey = CombGuid.NewCombGuid();
assessment.AddToWorkflow(workflowKey);
// Verify
Assert.AreEqual(2, events.Count);
var addedToWorkflowEvent = events[1];
Assert.IsNotNull(addedToWorkflowEvent);
Assert.AreEqual(typeof (AssessmentAddedToWorkflowEvent), addedToWorkflowEvent.GetType());
Assert.AreEqual((addedToWorkflowEvent as AssessmentAddedToWorkflowEvent).WorkflowKey, workflowKey);
Assert.AreEqual(2, assessment.Version);
}
}
[TestMethod]
public void CalculateCompleteness_NothingSkipped_CompletenessTotalCorrect()
{
using ( var serviceLocatorFixture = new ServiceLocatorFixture () )
{
// Setup
SetupServiceLocatorFixture ( serviceLocatorFixture );
var assessmentDefinition = Substitute.For<AssessmentDefinition> ();
var itemDefinitions = GetItemDefinitions ();
assessmentDefinition.GetAllItemDefinitionsOfType ( Arg.Any<ItemType> () ).Returns ( itemDefinitions );
var assessmentInstance = new AssessmentInstance ( assessmentDefinition, Guid.NewGuid (), "Test", false );
var completeness = assessmentInstance.CalculateCompleteness ();
Assert.AreEqual ( itemDefinitions.Count ( i => i.GetIsRequired () ), completeness.Total );
}
}
[TestMethod]
public void CalculateCompleteness_SkippedItems_CompletenessTotalCorrect()
{
using (var serviceLocatorFixture = new ServiceLocatorFixture())
{
// Setup
SetupServiceLocatorFixture(serviceLocatorFixture);
var itemDefinitions = GetItemDefinitions();
var ruleCollection = Substitute.For<IAssessmentRuleCollection> ();
var rule = Substitute.For<IItemSkippingRule> ();
rule.SkippedItemDefinitions.Returns ( itemDefinitions.Where ( i => i.CodedConcept.Code == "3" ) );
ruleCollection.ItemSkippingRules.Returns(new List<IItemSkippingRule> { rule });
serviceLocatorFixture.StructureMapContainer.Configure(
c => c.For<IAssessmentRuleCollection>().Use( ruleCollection ).Named ( "Test" ));
var assessmentDefinition = Substitute.For<AssessmentDefinition>();
assessmentDefinition.GetAllItemDefinitionsOfType(Arg.Any<ItemType>()).Returns(itemDefinitions);
var assessmentInstance = new AssessmentInstance(assessmentDefinition, Guid.NewGuid(), "Test", false);
var completeness = assessmentInstance.CalculateCompleteness();
Assert.AreEqual(itemDefinitions.Count(i => i.GetIsRequired()) - 1, completeness.Total);
}
}
private IEnumerable<ItemDefinition> GetItemDefinitions ()
{
var codeSystem = new CodeSystem ( "1", "1", "1" );
return new List<ItemDefinition>
{
new ItemDefinition ( new CodedConcept ( codeSystem, "1", "Test" ), ItemType.Question, null )
{
ItemMetadata = new ItemMetadata
{
MetadataItems = new List<IMetadataItem> { new RequiredForCompletenessMetadataItem ( "Report" ) }
}
},
new ItemDefinition ( new CodedConcept ( codeSystem, "2", "Test" ), ItemType.Question, null ),
new ItemDefinition ( new CodedConcept ( codeSystem, "3", "Test" ), ItemType.Question, null )
{
ItemMetadata = new ItemMetadata
{
MetadataItems = new List<IMetadataItem> { new RequiredForCompletenessMetadataItem ( "Report" ) }
}
},
new ItemDefinition ( new CodedConcept ( codeSystem, "4", "Test" ), ItemType.Question, null )
{
ItemMetadata = new ItemMetadata
{
MetadataItems = new List<IMetadataItem> { new RequiredForCompletenessMetadataItem ( "Report" ) }
}
},
};
}
[TestInitialize]
public void TestInitialize()
{
}
#endregion
#region Methods
private static void SetupServiceLocatorFixture(ServiceLocatorFixture serviceLocatorFixture)
{
serviceLocatorFixture.StructureMapContainer.Configure(
c => c.For<ICommitDomainEventService>().Singleton().Use<CommitDomainEventService>());
serviceLocatorFixture.StructureMapContainer.Configure(
c => c.For<IUnitOfWorkProvider>().Use<UnitOfWorkProvider>());
serviceLocatorFixture.StructureMapContainer.Configure(
c => c.For<IAssessmentRuleCollectionFactory>().Use<AssessmentRuleCollectionFactory>());
serviceLocatorFixture.StructureMapContainer.Configure(
c => c.For<IUnitOfWork>().Use(new Mock<IUnitOfWork>().Object));
Thread.CurrentPrincipal = new ClaimsPrincipal(new ClaimsIdentity(
new List<Claim>
{
new Claim(ProCenterClaimType.StaffKeyClaimType, Guid.NewGuid().ToString())
}));
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AddUInt32()
{
var test = new SimpleBinaryOpTest__AddUInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AddUInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt32[] inArray1, UInt32[] inArray2, UInt32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<UInt32> _fld1;
public Vector256<UInt32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AddUInt32 testClass)
{
var result = Avx2.Add(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddUInt32 testClass)
{
fixed (Vector256<UInt32>* pFld1 = &_fld1)
fixed (Vector256<UInt32>* pFld2 = &_fld2)
{
var result = Avx2.Add(
Avx.LoadVector256((UInt32*)(pFld1)),
Avx.LoadVector256((UInt32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector256<UInt32> _clsVar1;
private static Vector256<UInt32> _clsVar2;
private Vector256<UInt32> _fld1;
private Vector256<UInt32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddUInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
}
public SimpleBinaryOpTest__AddUInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new DataTable(_data1, _data2, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.Add(
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.Add(
Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.Add(
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<UInt32>* pClsVar1 = &_clsVar1)
fixed (Vector256<UInt32>* pClsVar2 = &_clsVar2)
{
var result = Avx2.Add(
Avx.LoadVector256((UInt32*)(pClsVar1)),
Avx.LoadVector256((UInt32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr);
var result = Avx2.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr));
var result = Avx2.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr));
var result = Avx2.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddUInt32();
var result = Avx2.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__AddUInt32();
fixed (Vector256<UInt32>* pFld1 = &test._fld1)
fixed (Vector256<UInt32>* pFld2 = &test._fld2)
{
var result = Avx2.Add(
Avx.LoadVector256((UInt32*)(pFld1)),
Avx.LoadVector256((UInt32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.Add(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<UInt32>* pFld1 = &_fld1)
fixed (Vector256<UInt32>* pFld2 = &_fld2)
{
var result = Avx2.Add(
Avx.LoadVector256((UInt32*)(pFld1)),
Avx.LoadVector256((UInt32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.Add(
Avx.LoadVector256((UInt32*)(&test._fld1)),
Avx.LoadVector256((UInt32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt32> op1, Vector256<UInt32> op2, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((uint)(left[0] + right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((uint)(left[i] + right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Add)}<UInt32>(Vector256<UInt32>, Vector256<UInt32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 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.
//-----------------------------------------------------------------------------
// Code for the main Gui Editor tree view that shows the hierarchy of the
// current GUI being edited.
//---------------------------------------------------------------------------------------------
function GuiEditorTreeView::init(%this)
{
if( !isObject( %this.contextMenu ) )
%this.contextMenu = new PopupMenu()
{
superClass = "MenuBuilder";
isPopup = true;
item[ 0 ] = "Rename" TAB "" TAB "GuiEditorTreeView.showItemRenameCtrl( GuiEditorTreeView.findItemByObjectId( %this.object ) );";
item[ 1 ] = "Delete" TAB "" TAB "GuiEditor.deleteControl( %this.object );";
item[ 2 ] = "-";
item[ 3 ] = "Locked" TAB "" TAB "%this.object.setLocked( !%this.object.locked ); GuiEditorTreeView.update();";
item[ 4 ] = "Hidden" TAB "" TAB "%this.object.setVisible( !%this.object.isVisible() ); GuiEditorTreeView.update();";
item[ 5 ] = "-";
item[ 6 ] = "Add New Controls Here" TAB "" TAB "GuiEditor.setCurrentAddSet( %this.object );";
item[ 7 ] = "Add Child Controls to Selection" TAB "" TAB "GuiEditor.selectAllControlsInSet( %this.object, false );";
item[ 8 ] = "Remove Child Controls from Selection" TAB "" TAB "GuiEditor.selectAllControlsInSet( %this.object, true );";
object = -1;
};
if( !isObject( %this.contextMenuMultiSel ) )
%this.contextMenuMultiSel = new PopupMenu()
{
superClass = "MenuBuilder";
isPopup = true;
item[ 0 ] = "Delete" TAB "" TAB "GuiEditor.deleteSelection();";
};
}
//---------------------------------------------------------------------------------------------
function GuiEditorTreeView::update( %this )
{
%obj = GuiEditorContent.getObject( 0 );
if( !isObject( %obj ) )
GuiEditorTreeView.clear();
else
{
// Open inspector tree.
GuiEditorTreeView.open( %obj );
// Sync selection with GuiEditor.
GuiEditorTreeView.clearSelection();
%selection = GuiEditor.getSelection();
%count = %selection.getCount();
for( %i = 0; %i < %count; %i ++ )
GuiEditorTreeView.addSelection( %selection.getObject( %i ) );
}
}
//=============================================================================================
// Event Handlers.
//=============================================================================================
//---------------------------------------------------------------------------------------------
/// Defines the icons to be used in the tree view control.
/// Provide the paths to each icon minus the file extension.
/// Seperate them with ':'.
/// The order of the icons must correspond to the bit array defined
/// in the GuiTreeViewCtrl.h.
function GuiEditorTreeView::onDefineIcons(%this)
{
%icons = ":" @ // Default1
":" @ // SimGroup1
":" @ // SimGroup2
":" @ // SimGroup3
":" @ // SimGroup4
"tools/gui/images/treeview/hidden:" @
"tools/worldEditor/images/lockedHandle";
GuiEditorTreeView.buildIconTable( %icons );
}
//---------------------------------------------------------------------------------------------
function GuiEditorTreeView::onRightMouseDown( %this, %item, %pts, %obj )
{
if( %this.getSelectedItemsCount() > 1 )
{
%popup = %this.contextMenuMultiSel;
%popup.showPopup( Canvas );
}
else if( %obj )
{
%popup = %this.contextMenu;
%popup.checkItem( 3, %obj.locked );
%popup.checkItem( 4, !%obj.isVisible() );
%popup.enableItem( 6, %obj.isContainer );
%popup.enableItem( 7, %obj.getCount() > 0 );
%popup.enableItem( 8, %obj.getCount() > 0 );
%popup.object = %obj;
%popup.showPopup( Canvas );
}
}
//---------------------------------------------------------------------------------------------
function GuiEditorTreeView::onAddSelection(%this,%ctrl)
{
GuiEditor.dontSyncTreeViewSelection = true;
GuiEditor.addSelection( %ctrl );
GuiEditor.dontSyncTreeViewSelection = false;
GuiEditor.setFirstResponder();
}
//---------------------------------------------------------------------------------------------
function GuiEditorTreeView::onRemoveSelection( %this, %ctrl )
{
GuiEditor.dontSyncTreeViewSelection = true;
GuiEditor.removeSelection( %ctrl );
GuiEditor.dontSyncTreeViewSelection = false;
}
//---------------------------------------------------------------------------------------------
function GuiEditorTreeView::onDeleteSelection(%this)
{
GuiEditor.clearSelection();
}
//---------------------------------------------------------------------------------------------
function GuiEditorTreeView::onSelect( %this, %obj )
{
if( isObject( %obj ) )
{
GuiEditor.dontSyncTreeViewSelection = true;
GuiEditor.select( %obj );
GuiEditor.dontSyncTreeViewSelection = false;
GuiEditorInspectFields.update( %obj );
}
}
//---------------------------------------------------------------------------------------------
function GuiEditorTreeView::isValidDragTarget( %this, %id, %obj )
{
return ( %obj.isContainer || %obj.getCount() > 0 );
}
//---------------------------------------------------------------------------------------------
function GuiEditorTreeView::onBeginReparenting( %this )
{
if( isObject( %this.reparentUndoAction ) )
%this.reparentUndoAction.delete();
%action = UndoActionReparentObjects::create( %this );
%this.reparentUndoAction = %action;
}
//---------------------------------------------------------------------------------------------
function GuiEditorTreeView::onReparent( %this, %obj, %oldParent, %newParent )
{
%this.reparentUndoAction.add( %obj, %oldParent, %newParent );
}
//---------------------------------------------------------------------------------------------
function GuiEditorTreeView::onEndReparenting( %this )
{
%action = %this.reparentUndoAction;
%this.reparentUndoAction = "";
if( %action.numObjects > 0 )
{
if( %action.numObjects == 1 )
%action.actionName = "Reparent Control";
else
%action.actionName = "Reparent Controls";
%action.addToManager( GuiEditor.getUndoManager() );
GuiEditor.updateUndoMenu();
}
else
%action.delete();
}
| |
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using Moq;
using OrchardCore.Layers.Services;
using OrchardCore.Localization;
using OrchardCore.Rules;
using OrchardCore.Rules.Models;
using OrchardCore.Rules.Services;
using OrchardCore.Scripting;
using OrchardCore.Scripting.JavaScript;
using Xunit;
namespace OrchardCore.Tests.Modules.OrchardCore.Rules
{
public class RuleTests
{
[Fact]
public async Task ShouldEvaluateRuleFalseWhenNoConditions()
{
var rule = new Rule();
var services = CreateRuleServiceCollection();
var serviceProvider = services.BuildServiceProvider();
var ruleService = serviceProvider.GetRequiredService<IRuleService>();
Assert.False(await ruleService.EvaluateAsync(rule));
}
[Theory]
[InlineData("/", true, true)]
[InlineData("/notthehomepage", true, false)]
[InlineData("/", false, false)]
[InlineData("/notthehomepage", false, true)]
public async Task ShouldEvaluateHomepage(string path, bool isHomepage, bool expected)
{
var rule = new Rule
{
Conditions = new List<Condition>
{
new HomepageCondition
{
Value = isHomepage
}
}
};
var services = CreateRuleServiceCollection()
.AddCondition<HomepageCondition, HomepageConditionEvaluator, ConditionFactory<HomepageCondition>>();
var mockHttpContextAccessor = new Mock<IHttpContextAccessor>();
var context = new DefaultHttpContext();
context.Request.Path = new PathString(path);
mockHttpContextAccessor.Setup(_ => _.HttpContext).Returns(context);
services.AddSingleton<IHttpContextAccessor>(mockHttpContextAccessor.Object);
var serviceProvider = services.BuildServiceProvider();
var ruleService = serviceProvider.GetRequiredService<IRuleService>();
Assert.Equal(expected, await ruleService.EvaluateAsync(rule));
}
[Theory]
[InlineData(true, true)]
[InlineData(false, false)]
public async Task ShouldEvaluateBoolean(bool boolean, bool expected)
{
var rule = new Rule
{
Conditions = new List<Condition>
{
new BooleanCondition { Value = boolean }
}
};
var services = CreateRuleServiceCollection()
.AddCondition<BooleanCondition, BooleanConditionEvaluator, ConditionFactory<BooleanCondition>>();
var serviceProvider = services.BuildServiceProvider();
var ruleService = serviceProvider.GetRequiredService<IRuleService>();
Assert.Equal(expected, await ruleService.EvaluateAsync(rule));
}
[Theory]
[InlineData(false, true, true)]
[InlineData(true, true, true)]
[InlineData(false, false, false)]
public async Task ShouldEvaluateAny(bool first, bool second, bool expected)
{
var rule = new Rule
{
Conditions = new List<Condition>
{
new AnyConditionGroup
{
Conditions = new List<Condition>
{
new BooleanCondition { Value = first },
new BooleanCondition { Value = second }
}
}
}
};
var services = CreateRuleServiceCollection()
.AddCondition<AnyConditionGroup, AnyConditionEvaluator, ConditionFactory<AnyConditionGroup>>()
.AddCondition<BooleanCondition, BooleanConditionEvaluator, ConditionFactory<BooleanCondition>>();
var serviceProvider = services.BuildServiceProvider();
var ruleService = serviceProvider.GetRequiredService<IRuleService>();
Assert.Equal(expected, await ruleService.EvaluateAsync(rule));
}
[Theory]
[InlineData("/foo", "/foo", true)]
[InlineData("/bar", "/foo", false)]
public async Task ShouldEvaluateUrlEquals(string path, string requestPath, bool expected)
{
var rule = new Rule
{
Conditions = new List<Condition>
{
new UrlCondition
{
Value = path,
Operation = new StringEqualsOperator()
}
}
};
var services = CreateRuleServiceCollection()
.AddCondition<UrlCondition, UrlConditionEvaluator, ConditionFactory<UrlCondition>>();
var mockHttpContextAccessor = new Mock<IHttpContextAccessor>();
var context = new DefaultHttpContext();
context.Request.Path = new PathString(requestPath);
mockHttpContextAccessor.Setup(_ => _.HttpContext).Returns(context);
services.AddSingleton<IHttpContextAccessor>(mockHttpContextAccessor.Object);
var serviceProvider = services.BuildServiceProvider();
var ruleService = serviceProvider.GetRequiredService<IRuleService>();
Assert.Equal(expected, await ruleService.EvaluateAsync(rule));
}
[Theory]
[InlineData("isHomepage()", "/", true)]
[InlineData("isHomepage()", "/foo", false)]
public async Task ShouldEvaluateJavascriptCondition(string script, string requestPath, bool expected)
{
var rule = new Rule
{
Conditions = new List<Condition>
{
new JavascriptCondition
{
Script = script
}
}
};
var services = CreateRuleServiceCollection()
.AddCondition<JavascriptCondition, JavascriptConditionEvaluator, ConditionFactory<JavascriptCondition>>()
.AddSingleton<IGlobalMethodProvider, DefaultLayersMethodProvider>()
.AddMemoryCache()
.AddScripting()
.AddJavaScriptEngine();
var mockHttpContextAccessor = new Mock<IHttpContextAccessor>();
var context = new DefaultHttpContext();
context.Request.Path = new PathString(requestPath);
mockHttpContextAccessor.Setup(_ => _.HttpContext).Returns(context);
services.AddSingleton<IHttpContextAccessor>(mockHttpContextAccessor.Object);
var serviceProvider = services.BuildServiceProvider();
var ruleService = serviceProvider.GetRequiredService<IRuleService>();
Assert.Equal(expected, await ruleService.EvaluateAsync(rule));
}
public static ServiceCollection CreateRuleServiceCollection()
{
var services = new ServiceCollection();
services.AddOptions<ConditionOptions>();
services.AddTransient<IConditionResolver, ConditionResolver>();
services.AddTransient<IConditionOperatorResolver, ConditionOperatorResolver>();
services.AddTransient<IRuleService, RuleService>();
services.AddTransient<AllConditionEvaluator>();
services.AddLocalization();
services.AddSingleton<IStringLocalizerFactory, NullStringLocalizerFactory>();
services.AddTransient<IConfigureOptions<ConditionOperatorOptions>, ConditionOperatorConfigureOptions>();
return services;
}
}
}
| |
using System;
using System.Collections;
using DevExpress.CodeRush.Core;
namespace CR_XkeysEngine
{
public enum SortOrder
{
ByName,
ByCommand,
ByContext
}
#region ShortcutNameComparer
public class ShortcutNameComparer: IComparer
{
public int Compare(object a, object b)
{
string astr = ((CommandKeyBinding)a).DisplayShortcut;
string bstr = ((CommandKeyBinding)b).DisplayShortcut;
return (astr).CompareTo(bstr);
}
}
#endregion
#region ShortcutCommandComparer
public class ShortcutCommandComparer: IComparer
{
public int Compare(object a, object b)
{
string astr = ((CommandKeyBinding)a).DisplayCommand;
string bstr = ((CommandKeyBinding)b).DisplayCommand;
return (astr).CompareTo(bstr);
}
}
#endregion
#region ShortcutReadableContextComparer
public class ShortcutReadableContextComparer: IComparer
{
public int Compare(object a, object b)
{
string astr = ((CommandKeyBinding)a).ReadableContext;
string bstr = ((CommandKeyBinding)b).ReadableContext;
return (astr).CompareTo(bstr);
}
}
#endregion
public class CommandKeyBindingCollection: CollectionBase, ICloneable
{
// public static fields
public static ShortcutNameComparer SortByName = new ShortcutNameComparer();
public static ShortcutCommandComparer SortByCommand = new ShortcutCommandComparer();
public static ShortcutReadableContextComparer SortByContext = new ShortcutReadableContextComparer();
// public methods...
#region Add
public void Add(CommandKeyBinding aCommandKeyBinding)
{
InnerList.Add(aCommandKeyBinding);
}
#endregion
#region AddRange
public void AddRange(ICollection collection)
{
InnerList.AddRange(collection);
}
#endregion
#region Remove
public void Remove(CommandKeyBinding aCommandKeyBinding)
{
InnerList.Remove(aCommandKeyBinding);
}
#endregion
#region Find(EditorCustomInputEventArgs ea)
public CommandKeyBinding Find(EditorCustomInputEventArgs ea)
{
MatchQuality matchQuality;
foreach (CommandKeyBinding commandKeyBinding in this)
{
if (!commandKeyBinding.Enabled)
continue;
matchQuality = commandKeyBinding.Matches(ea.CustomData);
if (matchQuality == MatchQuality.FullMatch) // Found it
{
// TODO: Check to see if the command itself is enabled here. If not, continue to look.
return commandKeyBinding;
}
}
return null; // Not found
}
#endregion
#region Find(string name)
public CommandKeyBinding Find(string name)
{
foreach (CommandKeyBinding lShortcut in this)
{
if (lShortcut.DisplayShortcut == name)
return lShortcut;
}
return null;
}
#endregion
#region FindByDisplayCommand
public CommandKeyBinding FindByDisplayCommand(string diplayCommand)
{
foreach (CommandKeyBinding lShortcut in this)
{
if (lShortcut.DisplayCommand == diplayCommand)
return lShortcut;
}
return null;
}
#endregion
#region Save
public void Save(DecoupledStorage aDecoupledStorage, CommandKeyBinding lastSelected)
{
aDecoupledStorage.WriteInt32("Header", "Count", Count);
int lIndex = 0;
foreach(CommandKeyBinding lCommandKeyBinding in this)
{
lCommandKeyBinding.Save(aDecoupledStorage, "Command" + lIndex.ToString(), lastSelected == lCommandKeyBinding);
lIndex++;
}
}
#endregion
#region Load
/// <summary>
/// Loads the command key bindings from storage.
/// </summary>
/// <param name="aDecoupledStorage"></param>
/// <returns>Returns the most recently selected command key binding.</returns>
public CommandKeyBinding Load(DecoupledStorage aDecoupledStorage, CommandKeyFolder parentFolder)
{
Clear();
CommandKeyBinding lLastSelected = null;
CommandKeyBinding lCommandKeyBinding = null;
int thisCount = aDecoupledStorage.ReadInt32("Header", "Count", Count);
for (int i = 0; i < thisCount; i++)
{
lCommandKeyBinding = new CommandKeyBinding();
lCommandKeyBinding.SetParentFolder(parentFolder);
if (lCommandKeyBinding.Load(aDecoupledStorage, "Command" + i.ToString()))
lLastSelected = lCommandKeyBinding;
Add(lCommandKeyBinding);
}
return lLastSelected;
}
#endregion
#region Load
/// <summary>
/// Loads the command key bindings from storage.
/// </summary>
/// <param name="aDecoupledStorage"></param>
/// <returns>Returns the most recently selected command key binding.</returns>
public CommandKeyBinding Load(DecoupledStorage aDecoupledStorage)
{
return Load(aDecoupledStorage, null);
}
#endregion
#region Sort
public void Sort(IComparer comparer)
{
InnerList.Sort(comparer);
}
#endregion
#region GetComparer
public static IComparer GetComparer(SortOrder order)
{
switch (order)
{
case SortOrder.ByCommand:
return SortByCommand;
case SortOrder.ByContext:
return SortByContext;
case SortOrder.ByName:
default:
return SortByName;
}
}
#endregion
#region ICloneable Members
object ICloneable.Clone()
{
return Clone();
}
public CommandKeyBindingCollection Clone()
{
CommandKeyBindingCollection lNewCollection = new CommandKeyBindingCollection();
for (int i = 0; i < this.Count; i++)
{
CommandKeyBinding lNewBinding = this[i].Clone();
lNewCollection.Add(lNewBinding);
}
return lNewCollection;
}
#endregion
public void SetParent(CommandKeyFolder parentFolder)
{
for (int i = 0; i < this.Count; i++)
this[i].SetParentFolder(parentFolder);
}
// public properties...
#region (default indexer)
public CommandKeyBinding this[int aIndex]
{
get
{
return (CommandKeyBinding) InnerList[aIndex];
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Build.RestApi.Swagger.Internals
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.DocAsCode.Common;
using Microsoft.DocAsCode.Exceptions;
using Microsoft.DocAsCode.Plugins;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
internal class SwaggerJsonBuilder
{
private readonly IDictionary<JsonLocationInfo, SwaggerObjectBase> _documentObjectCache;
private const string DefinitionsKey = "definitions";
private const string ReferenceKey = "$ref";
private const string ParametersKey = "parameters";
private const string InternalRefNameKey = "x-internal-ref-name";
private const string InternalLoopRefNameKey = "x-internal-loop-ref-name";
public SwaggerJsonBuilder()
{
_documentObjectCache = new Dictionary<JsonLocationInfo, SwaggerObjectBase>();
}
public SwaggerObjectBase Read(string swaggerPath)
{
var swagger = Load(swaggerPath);
RemoveReferenceDefinitions((SwaggerObject) swagger);
return ResolveReferences(swagger, swaggerPath, new Stack<JsonLocationInfo>());
}
private SwaggerObjectBase Load(string swaggerPath)
{
using (JsonReader reader = new JsonTextReader(EnvironmentContext.FileAbstractLayer.OpenReadText(swaggerPath)))
{
var token = JToken.ReadFrom(reader);
return LoadCore(token, swaggerPath);
}
}
private SwaggerObjectBase LoadCore(JToken token, string swaggerPath)
{
// Fetch from cache first
var location = JsonLocationHelper.GetLocation(token);
var jsonLocationInfo = new JsonLocationInfo(swaggerPath, location);
SwaggerObjectBase existingObject;
if (_documentObjectCache.TryGetValue(jsonLocationInfo, out existingObject))
{
return existingObject;
}
var jObject = token as JObject;
if (jObject != null)
{
// Only one $ref is allowed inside a swagger JObject
JToken referenceToken;
if (jObject.TryGetValue(ReferenceKey, out referenceToken))
{
if (referenceToken.Type != JTokenType.String && referenceToken.Type != JTokenType.Null)
{
throw new JsonException($"JSON reference $ref property must have a string or null value, instead of {referenceToken.Type}, location: {referenceToken.Path}.");
}
var swaggerReference = RestApiHelper.FormatReferenceFullPath((string)referenceToken);
switch (swaggerReference.Type)
{
case SwaggerFormattedReferenceType.InternalReference:
var deferredObject = new SwaggerReferenceObject
{
DeferredReference = swaggerReference.Path,
ReferenceName = swaggerReference.Name,
Location = location
};
// For swagger, other properties are still allowed besides $ref, e.g.
// "schema": {
// "$ref": "#/definitions/foo"
// "example": { }
// }
// Use Token property to keep other properties
// These properties cannot be referenced
jObject.Remove("$ref");
deferredObject.Token = jObject;
_documentObjectCache.Add(jsonLocationInfo, deferredObject);
return deferredObject;
case SwaggerFormattedReferenceType.ExternalReference:
jObject.Remove("$ref");
var externalJObject = LoadExternalReference(Path.Combine(Path.GetDirectoryName(swaggerPath), swaggerReference.ExternalFilePath));
RestApiHelper.CheckSpecificKey(externalJObject, ReferenceKey, () =>
{
throw new DocfxException($"{ReferenceKey} in {swaggerReference.ExternalFilePath} is not supported in external reference currently.");
});
foreach (var item in externalJObject)
{
JToken value;
if (jObject.TryGetValue(item.Key, out value))
{
Logger.LogWarning($"{item.Key} inside {jObject.Path} would be overwritten by the value of same key inside {swaggerReference.ExternalFilePath} with path {externalJObject.Path}.");
}
jObject[item.Key] = item.Value;
}
var resolved = new SwaggerValue
{
Location = location,
Token = jObject
};
_documentObjectCache.Add(jsonLocationInfo, resolved);
return resolved;
case SwaggerFormattedReferenceType.ExternalEmbeddedReference:
// Defer resolving external reference to resolve step, to prevent loop reference.
var externalDeferredObject = new SwaggerReferenceObject
{
ExternalFilePath = Path.Combine(Path.GetDirectoryName(swaggerPath), swaggerReference.ExternalFilePath),
DeferredReference = swaggerReference.Path,
ReferenceName = swaggerReference.Name,
Location = location
};
jObject.Remove("$ref");
externalDeferredObject.Token = jObject;
_documentObjectCache.Add(jsonLocationInfo, externalDeferredObject);
return externalDeferredObject;
default:
throw new DocfxException($"{referenceToken} does not support type {swaggerReference.Type}.");
}
}
var swaggerObject = new SwaggerObject { Location = location };
foreach (KeyValuePair<string, JToken> property in jObject)
{
swaggerObject.Dictionary.Add(property.Key, LoadCore(property.Value, swaggerPath));
}
_documentObjectCache.Add(jsonLocationInfo, swaggerObject);
return swaggerObject;
}
var jArray = token as JArray;
if (jArray != null)
{
var swaggerArray = new SwaggerArray { Location = location };
foreach (var property in jArray)
{
swaggerArray.Array.Add(LoadCore(property, swaggerPath));
}
return swaggerArray;
}
return new SwaggerValue
{
Location = location,
Token = token
};
}
private static JObject LoadExternalReference(string externalSwaggerPath)
{
if (!EnvironmentContext.FileAbstractLayer.Exists(externalSwaggerPath))
{
throw new DocfxException($"External swagger path not exist: {externalSwaggerPath}.");
}
using (JsonReader reader = new JsonTextReader(EnvironmentContext.FileAbstractLayer.OpenReadText(externalSwaggerPath)))
{
return JObject.Load(reader);
}
}
private static void RemoveReferenceDefinitions(SwaggerObject root)
{
// Remove definitions and parameters which has been added into _documentObjectCache
if (root.Dictionary.ContainsKey(DefinitionsKey))
{
root.Dictionary.Remove(DefinitionsKey);
}
if (root.Dictionary.ContainsKey(ParametersKey))
{
root.Dictionary.Remove(ParametersKey);
}
}
private SwaggerObjectBase ResolveReferences(SwaggerObjectBase swaggerBase, string swaggerPath, Stack<JsonLocationInfo> refStack)
{
if (swaggerBase.ReferencesResolved)
{
return swaggerBase;
}
swaggerBase.ReferencesResolved = true;
switch (swaggerBase.ObjectType)
{
case SwaggerObjectType.ReferenceObject:
{
var swagger = (SwaggerReferenceObject)swaggerBase;
if (!string.IsNullOrEmpty(swagger.DeferredReference))
{
if (swagger.DeferredReference[0] != '/')
{
throw new JsonException($"reference \"{swagger.DeferredReference}\" is not supported. Reference must be inside current schema document starting with /");
}
SwaggerObjectBase referencedObjectBase;
var jsonLocationInfo = new JsonLocationInfo(swagger.ExternalFilePath ?? swaggerPath, swagger.DeferredReference);
if (!_documentObjectCache.TryGetValue(jsonLocationInfo, out referencedObjectBase))
{
if (swagger.ExternalFilePath == null)
{
throw new JsonException($"Could not resolve reference '{swagger.DeferredReference}' in the document.");
}
// Load external swagger, to fill in the document cache.
Load(swagger.ExternalFilePath);
if (!_documentObjectCache.TryGetValue(jsonLocationInfo, out referencedObjectBase))
{
throw new JsonException($"Could not resolve reference '{swagger.DeferredReference}' in the document.");
}
}
if (refStack.Contains(jsonLocationInfo))
{
var loopRef = new SwaggerLoopReferenceObject();
loopRef.Dictionary.Add(InternalLoopRefNameKey, new SwaggerValue { Token = swagger.ReferenceName });
return loopRef;
}
// Clone to avoid change the reference object in _documentObjectCache
refStack.Push(jsonLocationInfo);
var resolved = ResolveReferences(referencedObjectBase.Clone(), jsonLocationInfo.FilePath, refStack);
var swaggerObject = ResolveSwaggerObject(resolved);
if (!swaggerObject.Dictionary.ContainsKey(InternalRefNameKey))
{
swaggerObject.Dictionary.Add(InternalRefNameKey, new SwaggerValue { Token = swagger.ReferenceName });
}
swagger.Reference = swaggerObject;
refStack.Pop();
}
return swagger;
}
case SwaggerObjectType.Object:
{
var swagger = (SwaggerObject)swaggerBase;
foreach (var key in swagger.Dictionary.Keys.ToList())
{
swagger.Dictionary[key] = ResolveReferences(swagger.Dictionary[key], swaggerPath, refStack);
}
return swagger;
}
case SwaggerObjectType.Array:
{
var swagger = (SwaggerArray)swaggerBase;
for (int i = 0; i < swagger.Array.Count; i++)
{
swagger.Array[i] = ResolveReferences(swagger.Array[i], swaggerPath, refStack);
}
return swagger;
}
case SwaggerObjectType.ValueType:
return swaggerBase;
default:
throw new NotSupportedException(swaggerBase.ObjectType.ToString());
}
}
private static SwaggerObject ResolveSwaggerObject(SwaggerObjectBase swaggerObjectBase)
{
var swaggerObject = swaggerObjectBase as SwaggerObject;
if (swaggerObject != null)
{
return swaggerObject;
}
var swaggerReferenceObject = swaggerObjectBase as SwaggerReferenceObject;
if (swaggerReferenceObject != null)
{
return swaggerReferenceObject.Reference;
}
throw new ArgumentException($"When resolving reference for {nameof(SwaggerReferenceObject)}, only support {nameof(SwaggerObject)} and {nameof(SwaggerReferenceObject)} as parameter.");
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
using NUnit.Framework;
using Newtonsoft.Json.Schema;
using System.IO;
using System.Linq;
using Newtonsoft.Json.Linq;
using System.Text;
using Extensions=Newtonsoft.Json.Schema.Extensions;
namespace Newtonsoft.Json.Tests.Schema
{
public class JsonSchemaGeneratorTests : TestFixtureBase
{
[Test]
public void Generate_GenericDictionary()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof (Dictionary<string, List<string>>));
string json = schema.ToString();
Assert.AreEqual(@"{
""type"": ""object"",
""additionalProperties"": {
""type"": [
""array"",
""null""
],
""items"": {
""type"": [
""string"",
""null""
]
}
}
}", json);
Dictionary<string, List<string>> value = new Dictionary<string, List<string>>
{
{"HasValue", new List<string>() { "first", "second", null }},
{"NoValue", null}
};
string valueJson = JsonConvert.SerializeObject(value, Formatting.Indented);
JObject o = JObject.Parse(valueJson);
Assert.IsTrue(o.IsValid(schema));
}
#if !PocketPC
[Test]
public void Generate_DefaultValueAttributeTestClass()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(DefaultValueAttributeTestClass));
string json = schema.ToString();
Assert.AreEqual(@"{
""description"": ""DefaultValueAttributeTestClass description!"",
""type"": ""object"",
""additionalProperties"": false,
""properties"": {
""TestField1"": {
""type"": ""integer"",
""default"": 21
},
""TestProperty1"": {
""type"": [
""string"",
""null""
],
""default"": ""TestProperty1Value""
}
}
}", json);
}
#endif
[Test]
public void Generate_Person()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Person));
string json = schema.ToString();
Assert.AreEqual(@"{
""id"": ""Person"",
""title"": ""Title!"",
""description"": ""JsonObjectAttribute description!"",
""type"": ""object"",
""properties"": {
""Name"": {
""type"": [
""string"",
""null""
]
},
""BirthDate"": {
""type"": ""string""
},
""LastModified"": {
""type"": ""string""
}
}
}", json);
}
[Test]
public void Generate_UserNullable()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(UserNullable));
string json = schema.ToString();
Assert.AreEqual(@"{
""type"": ""object"",
""properties"": {
""Id"": {
""type"": ""string""
},
""FName"": {
""type"": [
""string"",
""null""
]
},
""LName"": {
""type"": [
""string"",
""null""
]
},
""RoleId"": {
""type"": ""integer""
},
""NullableRoleId"": {
""type"": [
""integer"",
""null""
]
},
""NullRoleId"": {
""type"": [
""integer"",
""null""
]
},
""Active"": {
""type"": [
""boolean"",
""null""
]
}
}
}", json);
}
[Test]
public void Generate_RequiredMembersClass()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(RequiredMembersClass));
Assert.AreEqual(JsonSchemaType.String, schema.Properties["FirstName"].Type);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["MiddleName"].Type);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["LastName"].Type);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["BirthDate"].Type);
}
[Test]
public void Generate_Store()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Store));
Assert.AreEqual(11, schema.Properties.Count);
JsonSchema productArraySchema = schema.Properties["product"];
JsonSchema productSchema = productArraySchema.Items[0];
Assert.AreEqual(4, productSchema.Properties.Count);
}
[Test]
public void MissingSchemaIdHandlingTest()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Store));
Assert.AreEqual(null, schema.Id);
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
schema = generator.Generate(typeof (Store));
Assert.AreEqual(typeof(Store).FullName, schema.Id);
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseAssemblyQualifiedName;
schema = generator.Generate(typeof(Store));
Assert.AreEqual(typeof(Store).AssemblyQualifiedName, schema.Id);
}
[Test]
public void Generate_NumberFormatInfo()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(NumberFormatInfo));
string json = schema.ToString();
Console.WriteLine(json);
// Assert.AreEqual(@"{
// ""type"": ""object"",
// ""additionalProperties"": {
// ""type"": ""array"",
// ""items"": {
// ""type"": ""string""
// }
// }
//}", json);
}
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage = @"Unresolved circular reference for type 'Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.")]
public void CircularReferenceError()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.Generate(typeof(CircularReferenceClass));
}
[Test]
public void CircularReferenceWithTypeNameId()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(CircularReferenceClass), true);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["Name"].Type);
Assert.AreEqual(typeof(CircularReferenceClass).FullName, schema.Id);
Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Null, schema.Properties["Child"].Type);
Assert.AreEqual(schema, schema.Properties["Child"]);
}
[Test]
public void CircularReferenceWithExplicitId()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(CircularReferenceWithIdClass));
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["Name"].Type);
Assert.AreEqual("MyExplicitId", schema.Id);
Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Null, schema.Properties["Child"].Type);
Assert.AreEqual(schema, schema.Properties["Child"]);
}
[Test]
public void GenerateSchemaForType()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(Type));
Assert.AreEqual(JsonSchemaType.String, schema.Type);
string json = JsonConvert.SerializeObject(typeof(Version), Formatting.Indented);
JValue v = new JValue(json);
Assert.IsTrue(v.IsValid(schema));
}
#if !SILVERLIGHT && !PocketPC
[Test]
public void GenerateSchemaForISerializable()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(Exception));
Assert.AreEqual(JsonSchemaType.Object, schema.Type);
Assert.AreEqual(true, schema.AllowAdditionalProperties);
Assert.AreEqual(null, schema.Properties);
}
#endif
[Test]
public void GenerateSchemaForDBNull()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(DBNull));
Assert.AreEqual(JsonSchemaType.Null, schema.Type);
}
public class CustomDirectoryInfoMapper : DefaultContractResolver
{
public CustomDirectoryInfoMapper()
: base(true)
{
}
protected override JsonContract CreateContract(Type objectType)
{
if (objectType == typeof(DirectoryInfo))
return base.CreateObjectContract(objectType);
return base.CreateContract(objectType);
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
JsonPropertyCollection c = new JsonPropertyCollection(type);
CollectionUtils.AddRange(c, (IEnumerable)properties.Where(m => m.PropertyName != "Root"));
return c;
}
}
[Test]
public void GenerateSchemaForDirectoryInfo()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
generator.ContractResolver = new CustomDirectoryInfoMapper();
JsonSchema schema = generator.Generate(typeof(DirectoryInfo), true);
string json = schema.ToString();
Assert.AreEqual(@"{
""id"": ""System.IO.DirectoryInfo"",
""type"": [
""object"",
""null""
],
""additionalProperties"": false,
""properties"": {
""Name"": {
""type"": [
""string"",
""null""
]
},
""Parent"": {
""$ref"": ""System.IO.DirectoryInfo""
},
""Exists"": {
""type"": ""boolean""
},
""FullName"": {
""type"": [
""string"",
""null""
]
},
""Extension"": {
""type"": [
""string"",
""null""
]
},
""CreationTime"": {
""type"": ""string""
},
""CreationTimeUtc"": {
""type"": ""string""
},
""LastAccessTime"": {
""type"": ""string""
},
""LastAccessTimeUtc"": {
""type"": ""string""
},
""LastWriteTime"": {
""type"": ""string""
},
""LastWriteTimeUtc"": {
""type"": ""string""
},
""Attributes"": {
""type"": ""integer""
}
}
}", json);
DirectoryInfo temp = new DirectoryInfo(@"c:\temp");
JTokenWriter jsonWriter = new JTokenWriter();
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new IsoDateTimeConverter());
serializer.ContractResolver = new CustomDirectoryInfoMapper();
serializer.Serialize(jsonWriter, temp);
List<string> errors = new List<string>();
jsonWriter.Token.Validate(schema, (sender, args) => errors.Add(args.Message));
Assert.AreEqual(0, errors.Count);
}
[Test]
public void GenerateSchemaCamelCase()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
generator.ContractResolver = new CamelCasePropertyNamesContractResolver();
JsonSchema schema = generator.Generate(typeof (Version), true);
string json = schema.ToString();
Assert.AreEqual(@"{
""id"": ""System.Version"",
""type"": [
""object"",
""null""
],
""additionalProperties"": false,
""properties"": {
""major"": {
""type"": ""integer""
},
""minor"": {
""type"": ""integer""
},
""build"": {
""type"": ""integer""
},
""revision"": {
""type"": ""integer""
},
""majorRevision"": {
""type"": ""integer""
},
""minorRevision"": {
""type"": ""integer""
}
}
}", json);
}
public enum SortTypeFlag
{
No = 0,
Asc = 1,
Desc = -1
}
public class X
{
public SortTypeFlag x;
}
[Test]
public void GenerateSchemaWithNegativeEnum()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
JsonSchema schema = jsonSchemaGenerator.Generate(typeof(X));
string json = schema.ToString();
Assert.AreEqual(@"{
""type"": ""object"",
""properties"": {
""x"": {
""type"": ""integer"",
""enum"": [
0,
1,
-1
],
""options"": [
{
""value"": 0,
""value"": ""No""
},
{
""value"": 1,
""value"": ""Asc""
},
{
""value"": -1,
""value"": ""Desc""
}
]
}
}
}", json);
}
[Test]
public void CircularCollectionReferences()
{
Type type = typeof (Workspace);
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(type);
// should succeed
Assert.IsNotNull(jsonSchema);
}
[Test]
public void CircularReferenceWithMixedRequires()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(CircularReferenceClass));
string json = jsonSchema.ToString();
Assert.AreEqual(@"{
""id"": ""Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass"",
""optional"": true,
""type"": [
""object"",
""null""
],
""properties"": {
""Name"": {
""type"": ""string""
},
""Child"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass""
}
}
}", json);
}
[Test]
public void JsonPropertyWithHandlingValues()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(JsonPropertyWithHandlingValues));
string json = jsonSchema.ToString();
Assert.AreEqual(@"{
""id"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues"",
""type"": [
""object"",
""null""
],
""properties"": {
""DefaultValueHandlingIgnoreProperty"": {
""optional"": true,
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""DefaultValueHandlingIncludeProperty"": {
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""NullValueHandlingIgnoreProperty"": {
""optional"": true,
""type"": [
""string"",
""null""
]
},
""NullValueHandlingIncludeProperty"": {
""type"": [
""string"",
""null""
]
},
""ReferenceLoopHandlingErrorProperty"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues""
},
""ReferenceLoopHandlingIgnoreProperty"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues""
},
""ReferenceLoopHandlingSerializeProperty"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues""
}
}
}", json);
}
}
public class DMDSLBase
{
public String Comment;
}
public class Workspace : DMDSLBase
{
public ControlFlowItemCollection Jobs = new ControlFlowItemCollection();
}
public class ControlFlowItemBase : DMDSLBase
{
public String Name;
}
public class ControlFlowItem : ControlFlowItemBase//A Job
{
public TaskCollection Tasks = new TaskCollection();
public ContainerCollection Containers = new ContainerCollection();
}
public class ControlFlowItemCollection : List<ControlFlowItem>
{
}
public class Task : ControlFlowItemBase
{
public DataFlowTaskCollection DataFlowTasks = new DataFlowTaskCollection();
public BulkInsertTaskCollection BulkInsertTask = new BulkInsertTaskCollection();
}
public class TaskCollection : List<Task>
{
}
public class Container : ControlFlowItemBase
{
public ControlFlowItemCollection ContainerJobs = new ControlFlowItemCollection();
}
public class ContainerCollection : List<Container>
{
}
public class DataFlowTask_DSL : ControlFlowItemBase
{
}
public class DataFlowTaskCollection : List<DataFlowTask_DSL>
{
}
public class SequenceContainer_DSL : Container
{
}
public class BulkInsertTaskCollection : List<BulkInsertTask_DSL>
{
}
public class BulkInsertTask_DSL
{
}
}
| |
using System;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Xml;
using GenLib;
namespace PrimerProObjects
{
/// <summary>
/// Grapheme Taught Order
/// </summary>
public class GraphemeTaughtOrder
{
private Settings m_Settings;
private string m_FileName;
private ArrayList m_Graphemes;
private const string cTagOrder = "graphemetaughtorder";
private const string cTagGrapheme = "grapheme";
private const string cTagGraphemeX = "Grapheme";
private const string cUndercore = "_";
public GraphemeTaughtOrder(Settings s)
{
m_Settings = s;
m_FileName = "";
m_Graphemes = new ArrayList();
}
public string FileName
{
get {return m_FileName;}
set {m_FileName = value;}
}
public ArrayList Graphemes
{
get {return m_Graphemes;}
set {m_Graphemes = value;}
}
public void AddGrapheme(string grf)
{
m_Graphemes.Add(grf);
}
public void DelGrapheme(int n)
{
m_Graphemes.RemoveAt(n);
}
public string GetGrapheme(int n)
{
if (n < this.Count())
return (string) m_Graphemes[n];
else return null;
}
public int Count()
{
if (m_Graphemes == null )
return 0;
else return m_Graphemes.Count;
}
public bool IsTaughtGrapheme(string strGrapheme)
{
bool fReturn = false;
for (int i = 0; i < this.Count(); i++)
{
if (this.GetGrapheme(i) == strGrapheme)
{
fReturn = true;
break;
}
}
return fReturn;
}
public bool LoadFromFile(string strFileName)
{
bool flag = false;
m_Graphemes = new ArrayList();
if (File.Exists(strFileName))
{
XmlTextReader reader = null;
try
{
// Load the reader with the data file and ignore all white space nodes.
reader = new XmlTextReader(strFileName);
reader.WhitespaceHandling = WhitespaceHandling.None;
// Parse the file
string nam = "";
string val = "";
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
nam = reader.Name;
val = "";
break;
case XmlNodeType.Text:
val = reader.Value;
if ( (nam == GraphemeTaughtOrder.cTagGrapheme)
|| (nam == GraphemeTaughtOrder.cTagGraphemeX) )
{
this.AddGrapheme(val);
}
break;
case XmlNodeType.CDATA:
break;
case XmlNodeType.ProcessingInstruction:
break;
case XmlNodeType.Comment:
break;
case XmlNodeType.XmlDeclaration:
break;
case XmlNodeType.Document:
break;
case XmlNodeType.DocumentType:
break;
case XmlNodeType.EntityReference:
break;
case XmlNodeType.EndElement:
nam = reader.Name;
break;
}
}
flag = true;
}
catch
{
flag = false;
}
finally
{
if (reader != null)
{
m_FileName = strFileName;
reader.Close();
}
}
}
return flag;
}
public void SaveToFile(string strFileName)
{
string strPath = "";
if (m_Settings.OptionSettings.GraphemeTaughtOrderFile != "")
{
m_FileName = m_Settings.OptionSettings.GraphemeTaughtOrderFile;
strPath = Funct.GetFolder(m_FileName);
if (!Directory.Exists(strPath))
{
m_FileName = m_Settings.PrimerProFolder + Constants.Backslash
+ Funct.ShortFileNameWithExt(m_FileName);
m_Settings.OptionSettings.GraphemeTaughtOrderFile = m_FileName;
}
if (!File.Exists(m_FileName))
{
StreamWriter sw = File.CreateText(m_FileName);
sw.Close();
}
XmlTextWriter writer = new XmlTextWriter(m_FileName, System.Text.Encoding.UTF8);
writer.Formatting = Formatting.Indented;
writer.WriteStartElement(cTagOrder);
string strGrapheme = "";
for (int i = 0; i < m_Graphemes.Count; i++)
{
strGrapheme = (string)m_Graphemes[i];
writer.WriteElementString(cTagGrapheme, strGrapheme);
}
writer.WriteEndElement();
writer.Close();
}
//else MessageBox.Show("Grapheme Taught Order file not specified");
else
{
string strText = m_Settings.LocalizationTable.GetMessage("GraphemeTaughtOrder1");
if (strText == "")
strText = "Grapheme Taught Order file not specified";
MessageBox.Show(strText);
}
}
public string RetrieveGraphemes()
{
string strText = "";
string strLine = "";
if (this != null)
{
for (int i = 0; i < this.Count(); i++)
{
strLine = this.GetGrapheme(i);
strText += strLine + Environment.NewLine;
}
}
//else MessageBox.Show("Graphemes Taught List is missing");
else
{
strText = m_Settings.LocalizationTable.GetMessage("GraphemeTaughtOrder2");
if (strText == "")
strText = "Graphemes Taught List is missing";
MessageBox.Show(strText);
}
return strText;
}
//public string GetMissingGraphemes()
//{
// string strText = "";
// ArrayList alMissingGraphemes = new ArrayList();
// string strGrapheme = "";
// for (int i = 0; i < this.Count(); i++)
// {
// strGrapheme = (string)this.GetGrapheme(i);
// if (!m_Settings.GraphemeInventory.IsInInventory(strGrapheme))
// {
// if (!alMissingGraphemes.Contains(strGrapheme))
// {
// alMissingGraphemes.Add(strGrapheme);
// strText += strGrapheme + Environment.NewLine;
// }
// }
// }
// return strText;
//}
public string GetMissingGraphemes()
{
string strText = "";
ArrayList alMissingGraphemes = new ArrayList();
string strGrapheme = "";
for (int i = 0; i < this.Count(); i++)
{
strGrapheme = (string)this.GetGrapheme(i);
int nLenght = strGrapheme.Length;
string strGrf = strGrapheme;
if (nLenght > 1)
{
if (strGrf.Substring(0, 1) == cUndercore)
strGrf = strGrf.Substring(1);
else if (strGrf.Substring(nLenght - 1, 1) == cUndercore)
strGrf = strGrapheme.Substring(0, nLenght - 1);
}
if (!m_Settings.GraphemeInventory.IsInInventory(strGrf))
{
if (!alMissingGraphemes.Contains(strGrf))
{
alMissingGraphemes.Add(strGrapheme);
strText += strGrapheme + Environment.NewLine;
}
}
}
return strText;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace DropnWatch.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ActionDescriptor.ReturnType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
/*
* 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 copyrightD
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using OMV = OpenMetaverse;
namespace OpenSim.Region.Physics.BulletSPlugin
{
// Classes to allow some type checking for the API
// These hold pointers to allocated objects in the unmanaged space.
// These classes are subclassed by the various physical implementations of
// objects. In particular, there is a version for physical instances in
// unmanaged memory ("unman") and one for in managed memory ("XNA").
// Currently, the instances of these classes are a reference to a
// physical representation and this has no releationship to other
// instances. Someday, refarb the usage of these classes so each instance
// refers to a particular physical instance and this class controls reference
// counts and such. This should be done along with adding BSShapes.
public class BulletWorld
{
public BulletWorld(uint worldId, BSScene bss)
{
worldID = worldId;
physicsScene = bss;
}
public uint worldID;
// The scene is only in here so very low level routines have a handle to print debug/error messages
public BSScene physicsScene;
}
// An allocated Bullet btRigidBody
public class BulletBody
{
public BulletBody(uint id)
{
ID = id;
collisionType = CollisionType.Static;
}
public uint ID;
public CollisionType collisionType;
public virtual void Clear() { }
public virtual bool HasPhysicalBody { get { return false; } }
// Apply the specificed collision mask into the physical world
public virtual bool ApplyCollisionMask(BSScene physicsScene)
{
// Should assert the body has been added to the physical world.
// (The collision masks are stored in the collision proxy cache which only exists for
// a collision body that is in the world.)
return physicsScene.PE.SetCollisionGroupMask(this,
BulletSimData.CollisionTypeMasks[collisionType].group,
BulletSimData.CollisionTypeMasks[collisionType].mask);
}
// Used for log messages for a unique display of the memory/object allocated to this instance
public virtual string AddrString
{
get { return "unknown"; }
}
public override string ToString()
{
StringBuilder buff = new StringBuilder();
buff.Append("<id=");
buff.Append(ID.ToString());
buff.Append(",p=");
buff.Append(AddrString);
buff.Append(",c=");
buff.Append(collisionType);
buff.Append(">");
return buff.ToString();
}
}
public class BulletShape
{
public BulletShape()
{
shapeType = BSPhysicsShapeType.SHAPE_UNKNOWN;
shapeKey = (System.UInt64)FixedShapeKey.KEY_NONE;
isNativeShape = false;
}
public BSPhysicsShapeType shapeType;
public System.UInt64 shapeKey;
public bool isNativeShape;
public virtual void Clear() { }
public virtual bool HasPhysicalShape { get { return false; } }
// Make another reference to this physical object.
public virtual BulletShape Clone() { return new BulletShape(); }
// Return 'true' if this and other refer to the same physical object
public virtual bool ReferenceSame(BulletShape xx) { return false; }
// Used for log messages for a unique display of the memory/object allocated to this instance
public virtual string AddrString
{
get { return "unknown"; }
}
public override string ToString()
{
StringBuilder buff = new StringBuilder();
buff.Append("<p=");
buff.Append(AddrString);
buff.Append(",s=");
buff.Append(shapeType.ToString());
buff.Append(",k=");
buff.Append(shapeKey.ToString("X"));
buff.Append(",n=");
buff.Append(isNativeShape.ToString());
buff.Append(">");
return buff.ToString();
}
}
// An allocated Bullet btConstraint
public class BulletConstraint
{
public BulletConstraint()
{
}
public virtual void Clear() { }
public virtual bool HasPhysicalConstraint { get { return false; } }
// Used for log messages for a unique display of the memory/object allocated to this instance
public virtual string AddrString
{
get { return "unknown"; }
}
}
// An allocated HeightMapThing which holds various heightmap info.
// Made a class rather than a struct so there would be only one
// instance of this and C# will pass around pointers rather
// than making copies.
public class BulletHMapInfo
{
public BulletHMapInfo(uint id, float[] hm, float pSizeX, float pSizeY) {
ID = id;
heightMap = hm;
terrainRegionBase = OMV.Vector3.Zero;
minCoords = new OMV.Vector3(100f, 100f, 25f);
maxCoords = new OMV.Vector3(101f, 101f, 26f);
minZ = maxZ = 0f;
sizeX = pSizeX;
sizeY = pSizeY;
}
public uint ID;
public float[] heightMap;
public OMV.Vector3 terrainRegionBase;
public OMV.Vector3 minCoords;
public OMV.Vector3 maxCoords;
public float sizeX, sizeY;
public float minZ, maxZ;
public BulletShape terrainShape;
public BulletBody terrainBody;
}
// The general class of collsion object.
public enum CollisionType
{
Avatar,
Groundplane,
Terrain,
Static,
Dynamic,
VolumeDetect,
// Linkset, // A linkset should be either Static or Dynamic
LinksetChild,
Unknown
};
// Hold specification of group and mask collision flags for a CollisionType
public struct CollisionTypeFilterGroup
{
public CollisionTypeFilterGroup(CollisionType t, uint g, uint m)
{
type = t;
group = g;
mask = m;
}
public CollisionType type;
public uint group;
public uint mask;
};
public static class BulletSimData
{
// Map of collisionTypes to flags for collision groups and masks.
// An object's 'group' is the collison groups this object belongs to
// An object's 'filter' is the groups another object has to belong to in order to collide with me
// A collision happens if ((obj1.group & obj2.filter) != 0) || ((obj2.group & obj1.filter) != 0)
//
// As mentioned above, don't use the CollisionFilterGroups definitions directly in the code
// but, instead, use references to this dictionary. Finding and debugging
// collision flag problems will be made easier.
public static Dictionary<CollisionType, CollisionTypeFilterGroup> CollisionTypeMasks
= new Dictionary<CollisionType, CollisionTypeFilterGroup>()
{
{ CollisionType.Avatar,
new CollisionTypeFilterGroup(CollisionType.Avatar,
(uint)CollisionFilterGroups.BCharacterGroup,
(uint)CollisionFilterGroups.BAllGroup)
},
{ CollisionType.Groundplane,
new CollisionTypeFilterGroup(CollisionType.Groundplane,
(uint)CollisionFilterGroups.BGroundPlaneGroup,
// (uint)CollisionFilterGroups.BAllGroup)
(uint)(CollisionFilterGroups.BCharacterGroup | CollisionFilterGroups.BSolidGroup))
},
{ CollisionType.Terrain,
new CollisionTypeFilterGroup(CollisionType.Terrain,
(uint)CollisionFilterGroups.BTerrainGroup,
(uint)(CollisionFilterGroups.BAllGroup & ~CollisionFilterGroups.BStaticGroup))
},
{ CollisionType.Static,
new CollisionTypeFilterGroup(CollisionType.Static,
(uint)CollisionFilterGroups.BStaticGroup,
(uint)(CollisionFilterGroups.BCharacterGroup | CollisionFilterGroups.BSolidGroup))
},
{ CollisionType.Dynamic,
new CollisionTypeFilterGroup(CollisionType.Dynamic,
(uint)CollisionFilterGroups.BSolidGroup,
(uint)(CollisionFilterGroups.BAllGroup))
},
{ CollisionType.VolumeDetect,
new CollisionTypeFilterGroup(CollisionType.VolumeDetect,
(uint)CollisionFilterGroups.BSensorTrigger,
(uint)(~CollisionFilterGroups.BSensorTrigger))
},
{ CollisionType.LinksetChild,
new CollisionTypeFilterGroup(CollisionType.LinksetChild,
(uint)CollisionFilterGroups.BLinksetChildGroup,
(uint)(CollisionFilterGroups.BNoneGroup))
// (uint)(CollisionFilterGroups.BCharacterGroup | CollisionFilterGroups.BSolidGroup))
},
};
}
}
| |
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections.Generic;
using System.IO;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization.Converters;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Serialization.NodeDeserializers;
using YamlDotNet.Serialization.NodeTypeResolvers;
using YamlDotNet.Serialization.ObjectFactories;
using YamlDotNet.Serialization.TypeInspectors;
using YamlDotNet.Serialization.TypeResolvers;
using YamlDotNet.Serialization.Utilities;
using YamlDotNet.Serialization.ValueDeserializers;
namespace YamlDotNet.Serialization
{
/// <summary>
/// Deserializes objects from the YAML format.
/// To customize the behavior of <see cref="Deserializer" />,
/// use the <see cref="DeserializerBuilder" /> class.
/// </summary>
public sealed class Deserializer
{
#region Backwards compatibility
private class BackwardsCompatibleConfiguration
{
private static readonly Dictionary<string, Type> predefinedTagMappings = new Dictionary<string, Type>
{
{ "tag:yaml.org,2002:map", typeof(Dictionary<object, object>) },
{ "tag:yaml.org,2002:bool", typeof(bool) },
{ "tag:yaml.org,2002:float", typeof(double) },
{ "tag:yaml.org,2002:int", typeof(int) },
{ "tag:yaml.org,2002:str", typeof(string) },
{ "tag:yaml.org,2002:timestamp", typeof(DateTime) }
};
private readonly Dictionary<string, Type> tagMappings;
private readonly List<IYamlTypeConverter> converters;
private TypeDescriptorProxy typeDescriptor = new TypeDescriptorProxy();
public IValueDeserializer valueDeserializer;
public IList<INodeDeserializer> NodeDeserializers { get; private set; }
public IList<INodeTypeResolver> TypeResolvers { get; private set; }
private class TypeDescriptorProxy : ITypeInspector
{
public ITypeInspector TypeDescriptor;
public IEnumerable<IPropertyDescriptor> GetProperties(Type type, object container)
{
return TypeDescriptor.GetProperties(type, container);
}
public IPropertyDescriptor GetProperty(Type type, object container, string name, bool ignoreUnmatched)
{
return TypeDescriptor.GetProperty(type, container, name, ignoreUnmatched);
}
}
public BackwardsCompatibleConfiguration(
IObjectFactory objectFactory,
INamingConvention namingConvention,
bool ignoreUnmatched,
YamlAttributeOverrides overrides)
{
objectFactory = objectFactory ?? new DefaultObjectFactory();
namingConvention = namingConvention ?? new NullNamingConvention();
typeDescriptor.TypeDescriptor =
new CachedTypeInspector(
new NamingConventionTypeInspector(
new YamlAttributesTypeInspector(
new YamlAttributeOverridesInspector(
new ReadableAndWritablePropertiesTypeInspector(
new ReadablePropertiesTypeInspector(
new StaticTypeResolver()
)
),
overrides
)
),
namingConvention
)
);
converters = new List<IYamlTypeConverter>();
converters.Add(new GuidConverter(false));
NodeDeserializers = new List<INodeDeserializer>();
NodeDeserializers.Add(new YamlConvertibleNodeDeserializer(objectFactory));
NodeDeserializers.Add(new YamlSerializableNodeDeserializer(objectFactory));
NodeDeserializers.Add(new TypeConverterNodeDeserializer(converters));
NodeDeserializers.Add(new NullNodeDeserializer());
NodeDeserializers.Add(new ScalarNodeDeserializer());
NodeDeserializers.Add(new ArrayNodeDeserializer());
NodeDeserializers.Add(new DictionaryNodeDeserializer(objectFactory));
NodeDeserializers.Add(new CollectionNodeDeserializer(objectFactory));
NodeDeserializers.Add(new EnumerableNodeDeserializer());
NodeDeserializers.Add(new ObjectNodeDeserializer(objectFactory, typeDescriptor, ignoreUnmatched));
tagMappings = new Dictionary<string, Type>(predefinedTagMappings);
TypeResolvers = new List<INodeTypeResolver>();
TypeResolvers.Add(new YamlConvertibleTypeResolver());
TypeResolvers.Add(new YamlSerializableTypeResolver());
TypeResolvers.Add(new TagNodeTypeResolver(tagMappings));
TypeResolvers.Add(new TypeNameInTagNodeTypeResolver());
TypeResolvers.Add(new DefaultContainersNodeTypeResolver());
valueDeserializer =
new AliasValueDeserializer(
new NodeValueDeserializer(
NodeDeserializers,
TypeResolvers
)
);
}
public void RegisterTagMapping(string tag, Type type)
{
tagMappings.Add(tag, type);
}
public void RegisterTypeConverter(IYamlTypeConverter typeConverter)
{
converters.Insert(0, typeConverter);
}
}
private readonly BackwardsCompatibleConfiguration backwardsCompatibleConfiguration;
private void ThrowUnlessInBackwardsCompatibleMode()
{
if (backwardsCompatibleConfiguration == null)
{
throw new InvalidOperationException("This method / property exists for backwards compatibility reasons, but the Deserializer was created using the new configuration mechanism. To configure the Deserializer, use the DeserializerBuilder.");
}
}
[Obsolete("Please use DeserializerBuilder to customize the Deserializer. This property will be removed in future releases.")]
public IList<INodeDeserializer> NodeDeserializers
{
get
{
ThrowUnlessInBackwardsCompatibleMode();
return backwardsCompatibleConfiguration.NodeDeserializers;
}
}
[Obsolete("Please use DeserializerBuilder to customize the Deserializer. This property will be removed in future releases.")]
public IList<INodeTypeResolver> TypeResolvers
{
get
{
ThrowUnlessInBackwardsCompatibleMode();
return backwardsCompatibleConfiguration.TypeResolvers;
}
}
[Obsolete("Please use DeserializerBuilder to customize the Deserializer. This constructor will be removed in future releases.")]
public Deserializer(
IObjectFactory objectFactory = null,
INamingConvention namingConvention = null,
bool ignoreUnmatched = false,
YamlAttributeOverrides overrides = null)
{
backwardsCompatibleConfiguration = new BackwardsCompatibleConfiguration(objectFactory, namingConvention, ignoreUnmatched, overrides);
valueDeserializer = backwardsCompatibleConfiguration.valueDeserializer;
}
[Obsolete("Please use DeserializerBuilder to customize the Deserializer. This method will be removed in future releases.")]
public void RegisterTagMapping(string tag, Type type)
{
ThrowUnlessInBackwardsCompatibleMode();
backwardsCompatibleConfiguration.RegisterTagMapping(tag, type);
}
[Obsolete("Please use DeserializerBuilder to customize the Deserializer. This method will be removed in future releases.")]
public void RegisterTypeConverter(IYamlTypeConverter typeConverter)
{
ThrowUnlessInBackwardsCompatibleMode();
backwardsCompatibleConfiguration.RegisterTypeConverter(typeConverter);
}
#endregion
private readonly IValueDeserializer valueDeserializer;
/// <summary>
/// Initializes a new instance of <see cref="Deserializer" /> using the default configuration.
/// </summary>
/// <remarks>
/// To customize the bahavior of the deserializer, use <see cref="DeserializerBuilder" />.
/// </remarks>
public Deserializer()
// TODO: When the backwards compatibility is dropped, uncomment the following line and remove the body of this constructor.
// : this(new DeserializerBuilder().BuildValueDeserializer())
{
backwardsCompatibleConfiguration = new BackwardsCompatibleConfiguration(null, null, false, null);
valueDeserializer = backwardsCompatibleConfiguration.valueDeserializer;
}
/// <remarks>
/// This constructor is private to discourage its use.
/// To invoke it, call the <see cref="FromValueDeserializer"/> method.
/// </remarks>
private Deserializer(IValueDeserializer valueDeserializer)
{
if (valueDeserializer == null)
{
throw new ArgumentNullException("valueDeserializer");
}
this.valueDeserializer = valueDeserializer;
}
/// <summary>
/// Creates a new <see cref="Deserializer" /> that uses the specified <see cref="IValueDeserializer" />.
/// This method is available for advanced scenarios. The preferred way to customize the bahavior of the
/// deserializer is to use <see cref="DeserializerBuilder" />.
/// </summary>
public static Deserializer FromValueDeserializer(IValueDeserializer valueDeserializer)
{
return new Deserializer(valueDeserializer);
}
public T Deserialize<T>(string input)
{
using (var reader = new StringReader(input))
{
return (T)Deserialize(reader, typeof(T));
}
}
public T Deserialize<T>(TextReader input)
{
return (T)Deserialize(input, typeof(T));
}
public object Deserialize(TextReader input)
{
return Deserialize(input, typeof(object));
}
public object Deserialize(string input, Type type)
{
using (var reader = new StringReader(input))
{
return Deserialize(reader, type);
}
}
public object Deserialize(TextReader input, Type type)
{
return Deserialize(new Parser(input), type);
}
public T Deserialize<T>(IParser parser)
{
return (T)Deserialize(parser, typeof(T));
}
public object Deserialize(IParser parser)
{
return Deserialize(parser, typeof(object));
}
/// <summary>
/// Deserializes an object of the specified type.
/// </summary>
/// <param name="parser">The <see cref="IParser" /> from where to deserialize the object.</param>
/// <param name="type">The static type of the object to deserialize.</param>
/// <returns>Returns the deserialized object.</returns>
public object Deserialize(IParser parser, Type type)
{
if (parser == null)
{
throw new ArgumentNullException("reader");
}
if (type == null)
{
throw new ArgumentNullException("type");
}
var hasStreamStart = parser.Allow<StreamStart>() != null;
var hasDocumentStart = parser.Allow<DocumentStart>() != null;
object result = null;
if (!parser.Accept<DocumentEnd>() && !parser.Accept<StreamEnd>())
{
using (var state = new SerializerState())
{
result = valueDeserializer.DeserializeValue(parser, type, state, valueDeserializer);
state.OnDeserialization();
}
}
if (hasDocumentStart)
{
parser.Expect<DocumentEnd>();
}
if (hasStreamStart)
{
parser.Expect<StreamEnd>();
}
return result;
}
}
}
| |
// 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
{
public partial class Lazy<T, TMetadata> : System.Lazy<T>
{
public Lazy(TMetadata metadata) { }
public Lazy(TMetadata metadata, bool isThreadSafe) { }
public Lazy(TMetadata metadata, System.Threading.LazyThreadSafetyMode mode) { }
public Lazy(System.Func<T> valueFactory, TMetadata metadata) { }
public Lazy(System.Func<T> valueFactory, TMetadata metadata, bool isThreadSafe) { }
public Lazy(System.Func<T> valueFactory, TMetadata metadata, System.Threading.LazyThreadSafetyMode mode) { }
public TMetadata Metadata { get { throw null; } }
}
}
namespace System.ComponentModel.Composition
{
public static partial class AttributedModelServices
{
public static System.ComponentModel.Composition.Primitives.ComposablePart AddExportedValue<T>(this System.ComponentModel.Composition.Hosting.CompositionBatch batch, T exportedValue) { throw null; }
public static System.ComponentModel.Composition.Primitives.ComposablePart AddExportedValue<T>(this System.ComponentModel.Composition.Hosting.CompositionBatch batch, string contractName, T exportedValue) { throw null; }
public static System.ComponentModel.Composition.Primitives.ComposablePart AddPart(this System.ComponentModel.Composition.Hosting.CompositionBatch batch, object attributedPart) { throw null; }
public static void ComposeExportedValue<T>(this System.ComponentModel.Composition.Hosting.CompositionContainer container, T exportedValue) { }
public static void ComposeExportedValue<T>(this System.ComponentModel.Composition.Hosting.CompositionContainer container, string contractName, T exportedValue) { }
public static void ComposeParts(this System.ComponentModel.Composition.Hosting.CompositionContainer container, params object[] attributedParts) { }
public static System.ComponentModel.Composition.Primitives.ComposablePart CreatePart(System.ComponentModel.Composition.Primitives.ComposablePartDefinition partDefinition, object attributedPart) { throw null; }
public static System.ComponentModel.Composition.Primitives.ComposablePart CreatePart(object attributedPart) { throw null; }
public static System.ComponentModel.Composition.Primitives.ComposablePart CreatePart(object attributedPart, System.Reflection.ReflectionContext reflectionContext) { throw null; }
public static System.ComponentModel.Composition.Primitives.ComposablePartDefinition CreatePartDefinition(System.Type type, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; }
public static System.ComponentModel.Composition.Primitives.ComposablePartDefinition CreatePartDefinition(System.Type type, System.ComponentModel.Composition.Primitives.ICompositionElement origin, bool ensureIsDiscoverable) { throw null; }
public static bool Exports(this System.ComponentModel.Composition.Primitives.ComposablePartDefinition part, System.Type contractType) { throw null; }
public static bool Exports<T>(this System.ComponentModel.Composition.Primitives.ComposablePartDefinition part) { throw null; }
public static string GetContractName(System.Type type) { throw null; }
public static TMetadataView GetMetadataView<TMetadataView>(System.Collections.Generic.IDictionary<string, object> metadata) { throw null; }
public static string GetTypeIdentity(System.Reflection.MethodInfo method) { throw null; }
public static string GetTypeIdentity(System.Type type) { throw null; }
public static bool Imports(this System.ComponentModel.Composition.Primitives.ComposablePartDefinition part, System.Type contractType) { throw null; }
public static bool Imports(this System.ComponentModel.Composition.Primitives.ComposablePartDefinition part, System.Type contractType, System.ComponentModel.Composition.Primitives.ImportCardinality importCardinality) { throw null; }
public static bool Imports<T>(this System.ComponentModel.Composition.Primitives.ComposablePartDefinition part) { throw null; }
public static bool Imports<T>(this System.ComponentModel.Composition.Primitives.ComposablePartDefinition part, System.ComponentModel.Composition.Primitives.ImportCardinality importCardinality) { throw null; }
public static System.ComponentModel.Composition.Primitives.ComposablePart SatisfyImportsOnce(this System.ComponentModel.Composition.ICompositionService compositionService, object attributedPart) { throw null; }
public static System.ComponentModel.Composition.Primitives.ComposablePart SatisfyImportsOnce(this System.ComponentModel.Composition.ICompositionService compositionService, object attributedPart, System.Reflection.ReflectionContext reflectionContext) { throw null; }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(1), AllowMultiple=false, Inherited=true)]
public partial class CatalogReflectionContextAttribute : System.Attribute
{
public CatalogReflectionContextAttribute(System.Type reflectionContextType) { }
public System.Reflection.ReflectionContext CreateReflectionContext() { throw null; }
}
public partial class ChangeRejectedException : System.ComponentModel.Composition.CompositionException
{
public ChangeRejectedException() { }
public ChangeRejectedException(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.CompositionError> errors) { }
public ChangeRejectedException(string message) { }
public ChangeRejectedException(string message, System.Exception innerException) { }
public override string Message { get { throw null; } }
}
public partial class CompositionContractMismatchException : System.Exception
{
public CompositionContractMismatchException() { }
protected CompositionContractMismatchException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public CompositionContractMismatchException(string message) { }
public CompositionContractMismatchException(string message, System.Exception innerException) { }
}
public partial class CompositionError
{
public CompositionError(string message) { }
public CompositionError(string message, System.ComponentModel.Composition.Primitives.ICompositionElement element) { }
public CompositionError(string message, System.ComponentModel.Composition.Primitives.ICompositionElement element, System.Exception exception) { }
public CompositionError(string message, System.Exception exception) { }
public string Description { get { throw null; } }
public System.ComponentModel.Composition.Primitives.ICompositionElement Element { get { throw null; } }
public System.Exception Exception { get { throw null; } }
public override string ToString() { throw null; }
}
public partial class CompositionException : System.Exception
{
public CompositionException() { }
public CompositionException(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.CompositionError> errors) { }
public CompositionException(string message) { }
public CompositionException(string message, System.Exception innerException) { }
public System.Collections.ObjectModel.ReadOnlyCollection<System.ComponentModel.Composition.CompositionError> Errors { get { throw null; } }
public override string Message { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyCollection<System.Exception> RootCauses { get { throw null; } }
}
public enum CreationPolicy
{
Any = 0,
NonShared = 2,
Shared = 1,
}
[System.AttributeUsageAttribute((System.AttributeTargets)(452), AllowMultiple=true, Inherited=false)]
public partial class ExportAttribute : System.Attribute
{
public ExportAttribute() { }
public ExportAttribute(string contractName) { }
public ExportAttribute(string contractName, System.Type contractType) { }
public ExportAttribute(System.Type contractType) { }
public string ContractName { get { throw null; } }
public System.Type ContractType { get { throw null; } }
}
public partial class ExportFactory<T>
{
public ExportFactory(System.Func<System.Tuple<T, System.Action>> exportLifetimeContextCreator) { }
public System.ComponentModel.Composition.ExportLifetimeContext<T> CreateExport() { throw null; }
}
public partial class ExportFactory<T, TMetadata> : System.ComponentModel.Composition.ExportFactory<T>
{
public ExportFactory(System.Func<System.Tuple<T, System.Action>> exportLifetimeContextCreator, TMetadata metadata) : base (default(System.Func<System.Tuple<T, System.Action>>)) { }
public TMetadata Metadata { get { throw null; } }
}
public sealed partial class ExportLifetimeContext<T> : System.IDisposable
{
public ExportLifetimeContext(T value, System.Action disposeAction) { }
public T Value { get { throw null; } }
public void Dispose() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(1476), AllowMultiple=true, Inherited=false)]
public sealed partial class ExportMetadataAttribute : System.Attribute
{
public ExportMetadataAttribute(string name, object value) { }
public bool IsMultiple { get { throw null; } set { } }
public string Name { get { throw null; } }
public object Value { get { throw null; } }
}
public partial interface ICompositionService
{
void SatisfyImportsOnce(System.ComponentModel.Composition.Primitives.ComposablePart part);
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple=false, Inherited=false)]
public partial class ImportAttribute : System.Attribute
{
public ImportAttribute() { }
public ImportAttribute(string contractName) { }
public ImportAttribute(string contractName, System.Type contractType) { }
public ImportAttribute(System.Type contractType) { }
public bool AllowDefault { get { throw null; } set { } }
public bool AllowRecomposition { get { throw null; } set { } }
public string ContractName { get { throw null; } }
public System.Type ContractType { get { throw null; } }
public System.ComponentModel.Composition.CreationPolicy RequiredCreationPolicy { get { throw null; } set { } }
public System.ComponentModel.Composition.ImportSource Source { get { throw null; } set { } }
}
public partial class ImportCardinalityMismatchException : System.Exception
{
public ImportCardinalityMismatchException() { }
protected ImportCardinalityMismatchException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public ImportCardinalityMismatchException(string message) { }
public ImportCardinalityMismatchException(string message, System.Exception innerException) { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(32), AllowMultiple=false, Inherited=false)]
public partial class ImportingConstructorAttribute : System.Attribute
{
public ImportingConstructorAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple=false, Inherited=false)]
public partial class ImportManyAttribute : System.Attribute
{
public ImportManyAttribute() { }
public ImportManyAttribute(string contractName) { }
public ImportManyAttribute(string contractName, System.Type contractType) { }
public ImportManyAttribute(System.Type contractType) { }
public bool AllowRecomposition { get { throw null; } set { } }
public string ContractName { get { throw null; } }
public System.Type ContractType { get { throw null; } }
public System.ComponentModel.Composition.CreationPolicy RequiredCreationPolicy { get { throw null; } set { } }
public System.ComponentModel.Composition.ImportSource Source { get { throw null; } set { } }
}
public enum ImportSource
{
Any = 0,
Local = 1,
NonLocal = 2,
}
[System.AttributeUsageAttribute((System.AttributeTargets)(1028), AllowMultiple=true, Inherited=true)]
public partial class InheritedExportAttribute : System.ComponentModel.Composition.ExportAttribute
{
public InheritedExportAttribute() { }
public InheritedExportAttribute(string contractName) { }
public InheritedExportAttribute(string contractName, System.Type contractType) { }
public InheritedExportAttribute(System.Type contractType) { }
}
public partial interface IPartImportsSatisfiedNotification
{
void OnImportsSatisfied();
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=true)]
public sealed partial class MetadataAttributeAttribute : System.Attribute
{
public MetadataAttributeAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(1024), AllowMultiple=false, Inherited=false)]
public sealed partial class MetadataViewImplementationAttribute : System.Attribute
{
public MetadataViewImplementationAttribute(System.Type implementationType) { }
public System.Type ImplementationType { get { throw null; } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=false)]
public sealed partial class PartCreationPolicyAttribute : System.Attribute
{
public PartCreationPolicyAttribute(System.ComponentModel.Composition.CreationPolicy creationPolicy) { }
public System.ComponentModel.Composition.CreationPolicy CreationPolicy { get { throw null; } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=true, Inherited=false)]
public sealed partial class PartMetadataAttribute : System.Attribute
{
public PartMetadataAttribute(string name, object value) { }
public string Name { get { throw null; } }
public object Value { get { throw null; } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=false)]
public sealed partial class PartNotDiscoverableAttribute : System.Attribute
{
public PartNotDiscoverableAttribute() { }
}
}
namespace System.ComponentModel.Composition.Hosting
{
public partial class AggregateCatalog : System.ComponentModel.Composition.Primitives.ComposablePartCatalog, System.ComponentModel.Composition.Hosting.INotifyComposablePartCatalogChanged
{
public AggregateCatalog() { }
public AggregateCatalog(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePartCatalog> catalogs) { }
public AggregateCatalog(params System.ComponentModel.Composition.Primitives.ComposablePartCatalog[] catalogs) { }
public System.Collections.Generic.ICollection<System.ComponentModel.Composition.Primitives.ComposablePartCatalog> Catalogs { get { throw null; } }
public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changed { add { } remove { } }
public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changing { add { } remove { } }
protected override void Dispose(bool disposing) { }
public override System.Collections.Generic.IEnumerator<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> GetEnumerator() { throw null; }
public override System.Collections.Generic.IEnumerable<System.Tuple<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, System.ComponentModel.Composition.Primitives.ExportDefinition>> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; }
protected virtual void OnChanged(System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs e) { }
protected virtual void OnChanging(System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs e) { }
}
public partial class AggregateExportProvider : System.ComponentModel.Composition.Hosting.ExportProvider, System.IDisposable
{
public AggregateExportProvider(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Hosting.ExportProvider> providers) { }
public AggregateExportProvider(params System.ComponentModel.Composition.Hosting.ExportProvider[] providers) { }
public System.Collections.ObjectModel.ReadOnlyCollection<System.ComponentModel.Composition.Hosting.ExportProvider> Providers { get { throw null; } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
protected override System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { throw null; }
}
public partial class ApplicationCatalog : System.ComponentModel.Composition.Primitives.ComposablePartCatalog, System.ComponentModel.Composition.Primitives.ICompositionElement
{
public ApplicationCatalog() { }
public ApplicationCatalog(System.ComponentModel.Composition.Primitives.ICompositionElement definitionOrigin) { }
public ApplicationCatalog(System.Reflection.ReflectionContext reflectionContext) { }
public ApplicationCatalog(System.Reflection.ReflectionContext reflectionContext, System.ComponentModel.Composition.Primitives.ICompositionElement definitionOrigin) { }
string System.ComponentModel.Composition.Primitives.ICompositionElement.DisplayName { get { throw null; } }
System.ComponentModel.Composition.Primitives.ICompositionElement System.ComponentModel.Composition.Primitives.ICompositionElement.Origin { get { throw null; } }
protected override void Dispose(bool disposing) { }
public override System.Collections.Generic.IEnumerator<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> GetEnumerator() { throw null; }
public override System.Collections.Generic.IEnumerable<System.Tuple<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, System.ComponentModel.Composition.Primitives.ExportDefinition>> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; }
public override string ToString() { throw null; }
}
public partial class AssemblyCatalog : System.ComponentModel.Composition.Primitives.ComposablePartCatalog, System.ComponentModel.Composition.Primitives.ICompositionElement
{
public AssemblyCatalog(System.Reflection.Assembly assembly) { }
public AssemblyCatalog(System.Reflection.Assembly assembly, System.ComponentModel.Composition.Primitives.ICompositionElement definitionOrigin) { }
public AssemblyCatalog(System.Reflection.Assembly assembly, System.Reflection.ReflectionContext reflectionContext) { }
public AssemblyCatalog(System.Reflection.Assembly assembly, System.Reflection.ReflectionContext reflectionContext, System.ComponentModel.Composition.Primitives.ICompositionElement definitionOrigin) { }
public AssemblyCatalog(string codeBase) { }
public AssemblyCatalog(string codeBase, System.ComponentModel.Composition.Primitives.ICompositionElement definitionOrigin) { }
public AssemblyCatalog(string codeBase, System.Reflection.ReflectionContext reflectionContext) { }
public AssemblyCatalog(string codeBase, System.Reflection.ReflectionContext reflectionContext, System.ComponentModel.Composition.Primitives.ICompositionElement definitionOrigin) { }
public System.Reflection.Assembly Assembly { get { throw null; } }
string System.ComponentModel.Composition.Primitives.ICompositionElement.DisplayName { get { throw null; } }
System.ComponentModel.Composition.Primitives.ICompositionElement System.ComponentModel.Composition.Primitives.ICompositionElement.Origin { get { throw null; } }
protected override void Dispose(bool disposing) { }
public override System.Collections.Generic.IEnumerator<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> GetEnumerator() { throw null; }
public override System.Collections.Generic.IEnumerable<System.Tuple<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, System.ComponentModel.Composition.Primitives.ExportDefinition>> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; }
public override string ToString() { throw null; }
}
public partial class AtomicComposition : System.IDisposable
{
public AtomicComposition() { }
public AtomicComposition(System.ComponentModel.Composition.Hosting.AtomicComposition outerAtomicComposition) { }
public void AddCompleteAction(System.Action completeAction) { }
public void AddRevertAction(System.Action revertAction) { }
public void Complete() { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public void SetValue(object key, object value) { }
public bool TryGetValue<T>(object key, out T value) { value = default(T); throw null; }
public bool TryGetValue<T>(object key, bool localAtomicCompositionOnly, out T value) { value = default(T); throw null; }
}
public partial class CatalogExportProvider : System.ComponentModel.Composition.Hosting.ExportProvider, System.IDisposable
{
public CatalogExportProvider(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog) { }
public CatalogExportProvider(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, bool isThreadSafe) { }
public CatalogExportProvider(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, System.ComponentModel.Composition.Hosting.CompositionOptions compositionOptions) { }
public System.ComponentModel.Composition.Primitives.ComposablePartCatalog Catalog { get { throw null; } }
public System.ComponentModel.Composition.Hosting.ExportProvider SourceProvider { get { throw null; } set { } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
protected override System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { throw null; }
}
public static partial class CatalogExtensions
{
public static System.ComponentModel.Composition.Hosting.CompositionService CreateCompositionService(this System.ComponentModel.Composition.Primitives.ComposablePartCatalog composablePartCatalog) { throw null; }
}
public partial class ComposablePartCatalogChangeEventArgs : System.EventArgs
{
public ComposablePartCatalogChangeEventArgs(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> addedDefinitions, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> removedDefinitions, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { }
public System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> AddedDefinitions { get { throw null; } }
public System.ComponentModel.Composition.Hosting.AtomicComposition AtomicComposition { get { throw null; } }
public System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> RemovedDefinitions { get { throw null; } }
}
public partial class ComposablePartExportProvider : System.ComponentModel.Composition.Hosting.ExportProvider, System.IDisposable
{
public ComposablePartExportProvider() { }
public ComposablePartExportProvider(bool isThreadSafe) { }
public ComposablePartExportProvider(System.ComponentModel.Composition.Hosting.CompositionOptions compositionOptions) { }
public System.ComponentModel.Composition.Hosting.ExportProvider SourceProvider { get { throw null; } set { } }
public void Compose(System.ComponentModel.Composition.Hosting.CompositionBatch batch) { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
protected override System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { throw null; }
}
public partial class CompositionBatch
{
public CompositionBatch() { }
public CompositionBatch(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePart> partsToAdd, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePart> partsToRemove) { }
public System.Collections.ObjectModel.ReadOnlyCollection<System.ComponentModel.Composition.Primitives.ComposablePart> PartsToAdd { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyCollection<System.ComponentModel.Composition.Primitives.ComposablePart> PartsToRemove { get { throw null; } }
public System.ComponentModel.Composition.Primitives.ComposablePart AddExport(System.ComponentModel.Composition.Primitives.Export export) { throw null; }
public void AddPart(System.ComponentModel.Composition.Primitives.ComposablePart part) { }
public void RemovePart(System.ComponentModel.Composition.Primitives.ComposablePart part) { }
}
public static partial class CompositionConstants
{
public const string ExportTypeIdentityMetadataName = "ExportTypeIdentity";
public const string GenericContractMetadataName = "System.ComponentModel.Composition.GenericContractName";
public const string GenericParametersMetadataName = "System.ComponentModel.Composition.GenericParameters";
public const string ImportSourceMetadataName = "System.ComponentModel.Composition.ImportSource";
public const string IsGenericPartMetadataName = "System.ComponentModel.Composition.IsGenericPart";
public const string PartCreationPolicyMetadataName = "System.ComponentModel.Composition.CreationPolicy";
}
public partial class CompositionContainer : System.ComponentModel.Composition.Hosting.ExportProvider, System.ComponentModel.Composition.ICompositionService, System.IDisposable
{
public CompositionContainer() { }
public CompositionContainer(System.ComponentModel.Composition.Hosting.CompositionOptions compositionOptions, params System.ComponentModel.Composition.Hosting.ExportProvider[] providers) { }
public CompositionContainer(params System.ComponentModel.Composition.Hosting.ExportProvider[] providers) { }
public CompositionContainer(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, bool isThreadSafe, params System.ComponentModel.Composition.Hosting.ExportProvider[] providers) { }
public CompositionContainer(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, System.ComponentModel.Composition.Hosting.CompositionOptions compositionOptions, params System.ComponentModel.Composition.Hosting.ExportProvider[] providers) { }
public CompositionContainer(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, params System.ComponentModel.Composition.Hosting.ExportProvider[] providers) { }
public System.ComponentModel.Composition.Primitives.ComposablePartCatalog Catalog { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyCollection<System.ComponentModel.Composition.Hosting.ExportProvider> Providers { get { throw null; } }
public void Compose(System.ComponentModel.Composition.Hosting.CompositionBatch batch) { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
protected override System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { throw null; }
public void ReleaseExport(System.ComponentModel.Composition.Primitives.Export export) { }
public void ReleaseExport<T>(System.Lazy<T> export) { }
public void ReleaseExports(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> exports) { }
public void ReleaseExports<T>(System.Collections.Generic.IEnumerable<System.Lazy<T>> exports) { }
public void ReleaseExports<T, TMetadataView>(System.Collections.Generic.IEnumerable<System.Lazy<T, TMetadataView>> exports) { }
public void SatisfyImportsOnce(System.ComponentModel.Composition.Primitives.ComposablePart part) { }
}
[System.FlagsAttribute]
public enum CompositionOptions
{
Default = 0,
DisableSilentRejection = 1,
ExportCompositionService = 4,
IsThreadSafe = 2,
}
public partial class CompositionScopeDefinition : System.ComponentModel.Composition.Primitives.ComposablePartCatalog, System.ComponentModel.Composition.Hosting.INotifyComposablePartCatalogChanged
{
protected CompositionScopeDefinition() { }
public CompositionScopeDefinition(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Hosting.CompositionScopeDefinition> children) { }
public CompositionScopeDefinition(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Hosting.CompositionScopeDefinition> children, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> publicSurface) { }
public virtual System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Hosting.CompositionScopeDefinition> Children { get { throw null; } }
public virtual System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> PublicSurface { get { throw null; } }
public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changed { add { } remove { } }
public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changing { add { } remove { } }
protected override void Dispose(bool disposing) { }
public override System.Collections.Generic.IEnumerator<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> GetEnumerator() { throw null; }
public override System.Collections.Generic.IEnumerable<System.Tuple<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, System.ComponentModel.Composition.Primitives.ExportDefinition>> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; }
protected virtual void OnChanged(System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs e) { }
protected virtual void OnChanging(System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs e) { }
}
public partial class CompositionService : System.ComponentModel.Composition.ICompositionService, System.IDisposable
{
internal CompositionService() { }
public void Dispose() { }
public void SatisfyImportsOnce(System.ComponentModel.Composition.Primitives.ComposablePart part) { }
}
public partial class DirectoryCatalog : System.ComponentModel.Composition.Primitives.ComposablePartCatalog, System.ComponentModel.Composition.Hosting.INotifyComposablePartCatalogChanged, System.ComponentModel.Composition.Primitives.ICompositionElement
{
public DirectoryCatalog(string path) { }
public DirectoryCatalog(string path, System.ComponentModel.Composition.Primitives.ICompositionElement definitionOrigin) { }
public DirectoryCatalog(string path, System.Reflection.ReflectionContext reflectionContext) { }
public DirectoryCatalog(string path, System.Reflection.ReflectionContext reflectionContext, System.ComponentModel.Composition.Primitives.ICompositionElement definitionOrigin) { }
public DirectoryCatalog(string path, string searchPattern) { }
public DirectoryCatalog(string path, string searchPattern, System.ComponentModel.Composition.Primitives.ICompositionElement definitionOrigin) { }
public DirectoryCatalog(string path, string searchPattern, System.Reflection.ReflectionContext reflectionContext) { }
public DirectoryCatalog(string path, string searchPattern, System.Reflection.ReflectionContext reflectionContext, System.ComponentModel.Composition.Primitives.ICompositionElement definitionOrigin) { }
public string FullPath { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyCollection<string> LoadedFiles { get { throw null; } }
public string Path { get { throw null; } }
public string SearchPattern { get { throw null; } }
string System.ComponentModel.Composition.Primitives.ICompositionElement.DisplayName { get { throw null; } }
System.ComponentModel.Composition.Primitives.ICompositionElement System.ComponentModel.Composition.Primitives.ICompositionElement.Origin { get { throw null; } }
public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changed { add { } remove { } }
public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changing { add { } remove { } }
protected override void Dispose(bool disposing) { }
public override System.Collections.Generic.IEnumerator<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> GetEnumerator() { throw null; }
public override System.Collections.Generic.IEnumerable<System.Tuple<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, System.ComponentModel.Composition.Primitives.ExportDefinition>> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; }
protected virtual void OnChanged(System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs e) { }
protected virtual void OnChanging(System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs e) { }
public void Refresh() { }
public override string ToString() { throw null; }
}
public abstract partial class ExportProvider
{
protected ExportProvider() { }
public event System.EventHandler<System.ComponentModel.Composition.Hosting.ExportsChangeEventArgs> ExportsChanged { add { } remove { } }
public event System.EventHandler<System.ComponentModel.Composition.Hosting.ExportsChangeEventArgs> ExportsChanging { add { } remove { } }
public System.Lazy<T> GetExport<T>() { throw null; }
public System.Lazy<T> GetExport<T>(string contractName) { throw null; }
public System.Lazy<T, TMetadataView> GetExport<T, TMetadataView>() { throw null; }
public System.Lazy<T, TMetadataView> GetExport<T, TMetadataView>(string contractName) { throw null; }
public T GetExportedValue<T>() { throw null; }
public T GetExportedValue<T>(string contractName) { throw null; }
public T GetExportedValueOrDefault<T>() { throw null; }
public T GetExportedValueOrDefault<T>(string contractName) { throw null; }
public System.Collections.Generic.IEnumerable<T> GetExportedValues<T>() { throw null; }
public System.Collections.Generic.IEnumerable<T> GetExportedValues<T>(string contractName) { throw null; }
public System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; }
public System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { throw null; }
public System.Collections.Generic.IEnumerable<System.Lazy<object, object>> GetExports(System.Type type, System.Type metadataViewType, string contractName) { throw null; }
public System.Collections.Generic.IEnumerable<System.Lazy<T>> GetExports<T>() { throw null; }
public System.Collections.Generic.IEnumerable<System.Lazy<T>> GetExports<T>(string contractName) { throw null; }
public System.Collections.Generic.IEnumerable<System.Lazy<T, TMetadataView>> GetExports<T, TMetadataView>() { throw null; }
public System.Collections.Generic.IEnumerable<System.Lazy<T, TMetadataView>> GetExports<T, TMetadataView>(string contractName) { throw null; }
protected abstract System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition);
protected virtual void OnExportsChanged(System.ComponentModel.Composition.Hosting.ExportsChangeEventArgs e) { }
protected virtual void OnExportsChanging(System.ComponentModel.Composition.Hosting.ExportsChangeEventArgs e) { }
public bool TryGetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition, out System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> exports) { exports = default(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export>); throw null; }
}
public partial class ExportsChangeEventArgs : System.EventArgs
{
public ExportsChangeEventArgs(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> addedExports, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> removedExports, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { }
public System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> AddedExports { get { throw null; } }
public System.ComponentModel.Composition.Hosting.AtomicComposition AtomicComposition { get { throw null; } }
public System.Collections.Generic.IEnumerable<string> ChangedContractNames { get { throw null; } }
public System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> RemovedExports { get { throw null; } }
}
public partial class FilteredCatalog : System.ComponentModel.Composition.Primitives.ComposablePartCatalog, System.ComponentModel.Composition.Hosting.INotifyComposablePartCatalogChanged
{
public FilteredCatalog(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, System.Func<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, bool> filter) { }
public System.ComponentModel.Composition.Hosting.FilteredCatalog Complement { get { throw null; } }
public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changed { add { } remove { } }
public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changing { add { } remove { } }
protected override void Dispose(bool disposing) { }
public override System.Collections.Generic.IEnumerator<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> GetEnumerator() { throw null; }
public override System.Collections.Generic.IEnumerable<System.Tuple<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, System.ComponentModel.Composition.Primitives.ExportDefinition>> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; }
public System.ComponentModel.Composition.Hosting.FilteredCatalog IncludeDependencies() { throw null; }
public System.ComponentModel.Composition.Hosting.FilteredCatalog IncludeDependencies(System.Func<System.ComponentModel.Composition.Primitives.ImportDefinition, bool> importFilter) { throw null; }
public System.ComponentModel.Composition.Hosting.FilteredCatalog IncludeDependents() { throw null; }
public System.ComponentModel.Composition.Hosting.FilteredCatalog IncludeDependents(System.Func<System.ComponentModel.Composition.Primitives.ImportDefinition, bool> importFilter) { throw null; }
protected virtual void OnChanged(System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs e) { }
protected virtual void OnChanging(System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs e) { }
}
public partial class ImportEngine : System.ComponentModel.Composition.ICompositionService, System.IDisposable
{
public ImportEngine(System.ComponentModel.Composition.Hosting.ExportProvider sourceProvider) { }
public ImportEngine(System.ComponentModel.Composition.Hosting.ExportProvider sourceProvider, bool isThreadSafe) { }
public ImportEngine(System.ComponentModel.Composition.Hosting.ExportProvider sourceProvider, System.ComponentModel.Composition.Hosting.CompositionOptions compositionOptions) { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public void PreviewImports(System.ComponentModel.Composition.Primitives.ComposablePart part, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { }
public void ReleaseImports(System.ComponentModel.Composition.Primitives.ComposablePart part, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { }
public void SatisfyImports(System.ComponentModel.Composition.Primitives.ComposablePart part) { }
public void SatisfyImportsOnce(System.ComponentModel.Composition.Primitives.ComposablePart part) { }
}
public partial interface INotifyComposablePartCatalogChanged
{
event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changed;
event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changing;
}
public static partial class ScopingExtensions
{
public static bool ContainsPartMetadata<T>(this System.ComponentModel.Composition.Primitives.ComposablePartDefinition part, string key, T value) { throw null; }
public static bool ContainsPartMetadataWithKey(this System.ComponentModel.Composition.Primitives.ComposablePartDefinition part, string key) { throw null; }
public static bool Exports(this System.ComponentModel.Composition.Primitives.ComposablePartDefinition part, string contractName) { throw null; }
public static System.ComponentModel.Composition.Hosting.FilteredCatalog Filter(this System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, System.Func<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, bool> filter) { throw null; }
public static bool Imports(this System.ComponentModel.Composition.Primitives.ComposablePartDefinition part, string contractName) { throw null; }
public static bool Imports(this System.ComponentModel.Composition.Primitives.ComposablePartDefinition part, string contractName, System.ComponentModel.Composition.Primitives.ImportCardinality importCardinality) { throw null; }
}
public partial class TypeCatalog : System.ComponentModel.Composition.Primitives.ComposablePartCatalog, System.ComponentModel.Composition.Primitives.ICompositionElement
{
public TypeCatalog(System.Collections.Generic.IEnumerable<System.Type> types) { }
public TypeCatalog(System.Collections.Generic.IEnumerable<System.Type> types, System.ComponentModel.Composition.Primitives.ICompositionElement definitionOrigin) { }
public TypeCatalog(System.Collections.Generic.IEnumerable<System.Type> types, System.Reflection.ReflectionContext reflectionContext) { }
public TypeCatalog(System.Collections.Generic.IEnumerable<System.Type> types, System.Reflection.ReflectionContext reflectionContext, System.ComponentModel.Composition.Primitives.ICompositionElement definitionOrigin) { }
public TypeCatalog(params System.Type[] types) { }
string System.ComponentModel.Composition.Primitives.ICompositionElement.DisplayName { get { throw null; } }
System.ComponentModel.Composition.Primitives.ICompositionElement System.ComponentModel.Composition.Primitives.ICompositionElement.Origin { get { throw null; } }
protected override void Dispose(bool disposing) { }
public override System.Collections.Generic.IEnumerator<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> GetEnumerator() { throw null; }
public override string ToString() { throw null; }
}
}
namespace System.ComponentModel.Composition.Primitives
{
public abstract partial class ComposablePart
{
protected ComposablePart() { }
public abstract System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> ExportDefinitions { get; }
public abstract System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ImportDefinition> ImportDefinitions { get; }
public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get { throw null; } }
public virtual void Activate() { }
public abstract object GetExportedValue(System.ComponentModel.Composition.Primitives.ExportDefinition definition);
public abstract void SetImport(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> exports);
}
public abstract partial class ComposablePartCatalog : System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePartDefinition>, System.Collections.IEnumerable, System.IDisposable
{
protected ComposablePartCatalog() { }
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public virtual System.Linq.IQueryable<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> Parts { get { throw null; } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public virtual System.Collections.Generic.IEnumerator<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> GetEnumerator() { throw null; }
public virtual System.Collections.Generic.IEnumerable<System.Tuple<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, System.ComponentModel.Composition.Primitives.ExportDefinition>> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
public abstract partial class ComposablePartDefinition
{
protected ComposablePartDefinition() { }
public abstract System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> ExportDefinitions { get; }
public abstract System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ImportDefinition> ImportDefinitions { get; }
public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get { throw null; } }
public abstract System.ComponentModel.Composition.Primitives.ComposablePart CreatePart();
}
public partial class ComposablePartException : System.Exception
{
public ComposablePartException() { }
protected ComposablePartException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public ComposablePartException(string message) { }
public ComposablePartException(string message, System.ComponentModel.Composition.Primitives.ICompositionElement element) { }
public ComposablePartException(string message, System.ComponentModel.Composition.Primitives.ICompositionElement element, System.Exception innerException) { }
public ComposablePartException(string message, System.Exception innerException) { }
public System.ComponentModel.Composition.Primitives.ICompositionElement Element { get { throw null; } }
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
}
public partial class ContractBasedImportDefinition : System.ComponentModel.Composition.Primitives.ImportDefinition
{
protected ContractBasedImportDefinition() { }
public ContractBasedImportDefinition(string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy) { }
public ContractBasedImportDefinition(string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary<string, object> metadata) { }
public override System.Linq.Expressions.Expression<System.Func<System.ComponentModel.Composition.Primitives.ExportDefinition, bool>> Constraint { get { throw null; } }
public virtual System.ComponentModel.Composition.CreationPolicy RequiredCreationPolicy { get { throw null; } }
public virtual System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>> RequiredMetadata { get { throw null; } }
public virtual string RequiredTypeIdentity { get { throw null; } }
public override bool IsConstraintSatisfiedBy(System.ComponentModel.Composition.Primitives.ExportDefinition exportDefinition) { throw null; }
public override string ToString() { throw null; }
}
public partial class Export
{
protected Export() { }
public Export(System.ComponentModel.Composition.Primitives.ExportDefinition definition, System.Func<object> exportedValueGetter) { }
public Export(string contractName, System.Collections.Generic.IDictionary<string, object> metadata, System.Func<object> exportedValueGetter) { }
public Export(string contractName, System.Func<object> exportedValueGetter) { }
public virtual System.ComponentModel.Composition.Primitives.ExportDefinition Definition { get { throw null; } }
public System.Collections.Generic.IDictionary<string, object> Metadata { get { throw null; } }
public object Value { get { throw null; } }
protected virtual object GetExportedValueCore() { throw null; }
}
public partial class ExportDefinition
{
protected ExportDefinition() { }
public ExportDefinition(string contractName, System.Collections.Generic.IDictionary<string, object> metadata) { }
public virtual string ContractName { get { throw null; } }
public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get { throw null; } }
public override string ToString() { throw null; }
}
public partial class ExportedDelegate
{
protected ExportedDelegate() { }
public ExportedDelegate(object instance, System.Reflection.MethodInfo method) { }
public virtual System.Delegate CreateDelegate(System.Type delegateType) { throw null; }
}
public partial interface ICompositionElement
{
string DisplayName { get; }
System.ComponentModel.Composition.Primitives.ICompositionElement Origin { get; }
}
public enum ImportCardinality
{
ExactlyOne = 1,
ZeroOrMore = 2,
ZeroOrOne = 0,
}
public partial class ImportDefinition
{
protected ImportDefinition() { }
public ImportDefinition(System.Linq.Expressions.Expression<System.Func<System.ComponentModel.Composition.Primitives.ExportDefinition, bool>> constraint, string contractName, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite) { }
public ImportDefinition(System.Linq.Expressions.Expression<System.Func<System.ComponentModel.Composition.Primitives.ExportDefinition, bool>> constraint, string contractName, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, System.Collections.Generic.IDictionary<string, object> metadata) { }
public virtual System.ComponentModel.Composition.Primitives.ImportCardinality Cardinality { get { throw null; } }
public virtual System.Linq.Expressions.Expression<System.Func<System.ComponentModel.Composition.Primitives.ExportDefinition, bool>> Constraint { get { throw null; } }
public virtual string ContractName { get { throw null; } }
public virtual bool IsPrerequisite { get { throw null; } }
public virtual bool IsRecomposable { get { throw null; } }
public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get { throw null; } }
public virtual bool IsConstraintSatisfiedBy(System.ComponentModel.Composition.Primitives.ExportDefinition exportDefinition) { throw null; }
public override string ToString() { throw null; }
}
}
namespace System.ComponentModel.Composition.ReflectionModel
{
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct LazyMemberInfo
{
public LazyMemberInfo(System.Reflection.MemberInfo member) { throw null;}
public LazyMemberInfo(System.Reflection.MemberTypes memberType, System.Func<System.Reflection.MemberInfo[]> accessorsCreator) { throw null;}
public LazyMemberInfo(System.Reflection.MemberTypes memberType, params System.Reflection.MemberInfo[] accessors) { throw null;}
public System.Reflection.MemberTypes MemberType { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public System.Reflection.MemberInfo[] GetAccessors() { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo left, System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo right) { throw null; }
public static bool operator !=(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo left, System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo right) { throw null; }
}
public static partial class ReflectionModelServices
{
public static System.ComponentModel.Composition.Primitives.ExportDefinition CreateExportDefinition(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo exportingMember, string contractName, System.Lazy<System.Collections.Generic.IDictionary<string, object>> metadata, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; }
public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo importingMember, string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPreRequisite, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary<string, object> metadata, bool isExportFactory, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; }
public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo importingMember, string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary<string, object> metadata, bool isExportFactory, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; }
public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo importingMember, string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; }
public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.Lazy<System.Reflection.ParameterInfo> parameter, string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary<string, object> metadata, bool isExportFactory, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; }
public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.Lazy<System.Reflection.ParameterInfo> parameter, string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; }
public static System.ComponentModel.Composition.Primitives.ComposablePartDefinition CreatePartDefinition(System.Lazy<System.Type> partType, bool isDisposalRequired, System.Lazy<System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ImportDefinition>> imports, System.Lazy<System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition>> exports, System.Lazy<System.Collections.Generic.IDictionary<string, object>> metadata, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; }
public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition GetExportFactoryProductImportDefinition(System.ComponentModel.Composition.Primitives.ImportDefinition importDefinition) { throw null; }
public static System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo GetExportingMember(System.ComponentModel.Composition.Primitives.ExportDefinition exportDefinition) { throw null; }
public static System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo GetImportingMember(System.ComponentModel.Composition.Primitives.ImportDefinition importDefinition) { throw null; }
public static System.Lazy<System.Reflection.ParameterInfo> GetImportingParameter(System.ComponentModel.Composition.Primitives.ImportDefinition importDefinition) { throw null; }
public static System.Lazy<System.Type> GetPartType(System.ComponentModel.Composition.Primitives.ComposablePartDefinition partDefinition) { throw null; }
public static bool IsDisposalRequired(System.ComponentModel.Composition.Primitives.ComposablePartDefinition partDefinition) { throw null; }
public static bool IsExportFactoryImportDefinition(System.ComponentModel.Composition.Primitives.ImportDefinition importDefinition) { throw null; }
public static bool IsImportingParameter(System.ComponentModel.Composition.Primitives.ImportDefinition importDefinition) { throw null; }
public static bool TryMakeGenericPartDefinition(System.ComponentModel.Composition.Primitives.ComposablePartDefinition partDefinition, System.Collections.Generic.IEnumerable<System.Type> genericParameters, out System.ComponentModel.Composition.Primitives.ComposablePartDefinition specialization) { specialization = default(System.ComponentModel.Composition.Primitives.ComposablePartDefinition); throw null; }
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using System;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
internal class AccessibilityTests : CSharpResultProviderTestBase
{
[WorkItem(889710)]
[Fact]
public void HideNonPublicMembersBaseClass()
{
var sourceA =
@"public class A
{
public object FA0;
internal object FA1;
protected internal object FA2;
protected object FA3;
private object FA4;
public object PA0 { get { return null; } }
internal object PA1 { get { return null; } }
protected internal object PA2 { get { return null; } }
protected object PA3 { get { return null; } }
private object PA4 { get { return null; } }
public object PA5 { set { } }
public object PA6 { internal get; set; }
public object PA7 { protected internal get; set; }
public object PA8 { protected get; set; }
public object PA9 { private get; set; }
internal object PAA { private get; set; }
protected internal object PAB { internal get; set; }
protected internal object PAC { protected get; set; }
protected object PAD { private get; set; }
public static object SFA0;
internal static object SFA1;
protected static internal object SPA2 { get { return null; } }
protected static object SPA3 { get { return null; } }
public static object SPA4 { private get { return null; } set { } }
}";
var sourceB =
@"public class B : A
{
public object FB0;
internal object FB1;
protected internal object FB2;
protected object FB3;
private object FB4;
public object PB0 { get { return null; } }
internal object PB1 { get { return null; } }
protected internal object PB2 { get { return null; } }
protected object PB3 { get { return null; } }
private object PB4 { get { return null; } }
public object PB5 { set { } }
public object PB6 { internal get; set; }
public object PB7 { protected internal get; set; }
public object PB8 { protected get; set; }
public object PB9 { private get; set; }
internal object PBA { private get; set; }
protected internal object PBB { internal get; set; }
protected internal object PBC { protected get; set; }
protected object PBD { private get; set; }
public static object SPB0 { get { return null; } }
public static object SPB1 { internal get { return null; } set { } }
protected static internal object SFB2;
protected static object SFB3;
private static object SFB4;
}
class C
{
A a = new B();
}";
// Derived class in assembly with PDB,
// base class in assembly without PDB.
var compilationA = CSharpTestBase.CreateCompilationWithMscorlib(sourceA, options: TestOptions.ReleaseDll);
var bytesA = compilationA.EmitToArray();
var referenceA = MetadataReference.CreateFromImage(bytesA);
var compilationB = CSharpTestBase.CreateCompilationWithMscorlib(sourceB, options: TestOptions.DebugDll, references: new MetadataReference[] { referenceA });
var bytesB = compilationB.EmitToArray();
var assemblyA = ReflectionUtilities.Load(bytesA);
var assemblyB = ReflectionUtilities.Load(bytesB);
DkmClrValue value;
using (ReflectionUtilities.LoadAssemblies(assemblyA, assemblyB))
{
var runtime = new DkmClrRuntimeInstance(new[] { assemblyB });
var type = assemblyB.GetType("C", throwOnError: true);
value = CreateDkmClrValue(
Activator.CreateInstance(type),
runtime.GetType((TypeImpl)type));
}
var rootExpr = "new C()";
var evalResult = FormatResult(rootExpr, value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers));
Verify(evalResult,
EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("a", "{B}", "A {B}", "(new C()).a", DkmEvaluationResultFlags.Expandable));
// The native EE includes properties where the setter is accessible but the getter is not.
// We treat those properties as non-public.
children = GetChildren(children[0]);
Verify(children,
EvalResult("FA0", "null", "object", "(new C()).a.FA0"),
EvalResult("FA2", "null", "object", "(new C()).a.FA2"),
EvalResult("FA3", "null", "object", "(new C()).a.FA3"),
EvalResult("FB0", "null", "object", "((B)(new C()).a).FB0"),
EvalResult("FB1", "null", "object", "((B)(new C()).a).FB1"),
EvalResult("FB2", "null", "object", "((B)(new C()).a).FB2"),
EvalResult("FB3", "null", "object", "((B)(new C()).a).FB3"),
EvalResult("FB4", "null", "object", "((B)(new C()).a).FB4"),
EvalResult("PA0", "null", "object", "(new C()).a.PA0", DkmEvaluationResultFlags.ReadOnly),
EvalResult("PA2", "null", "object", "(new C()).a.PA2", DkmEvaluationResultFlags.ReadOnly),
EvalResult("PA3", "null", "object", "(new C()).a.PA3", DkmEvaluationResultFlags.ReadOnly),
EvalResult("PA7", "null", "object", "(new C()).a.PA7"),
EvalResult("PA8", "null", "object", "(new C()).a.PA8"),
EvalResult("PAC", "null", "object", "(new C()).a.PAC"),
EvalResult("PB0", "null", "object", "((B)(new C()).a).PB0", DkmEvaluationResultFlags.ReadOnly),
EvalResult("PB1", "null", "object", "((B)(new C()).a).PB1", DkmEvaluationResultFlags.ReadOnly),
EvalResult("PB2", "null", "object", "((B)(new C()).a).PB2", DkmEvaluationResultFlags.ReadOnly),
EvalResult("PB3", "null", "object", "((B)(new C()).a).PB3", DkmEvaluationResultFlags.ReadOnly),
EvalResult("PB4", "null", "object", "((B)(new C()).a).PB4", DkmEvaluationResultFlags.ReadOnly),
EvalResult("PB6", "null", "object", "((B)(new C()).a).PB6"),
EvalResult("PB7", "null", "object", "((B)(new C()).a).PB7"),
EvalResult("PB8", "null", "object", "((B)(new C()).a).PB8"),
EvalResult("PB9", "null", "object", "((B)(new C()).a).PB9"),
EvalResult("PBA", "null", "object", "((B)(new C()).a).PBA"),
EvalResult("PBB", "null", "object", "((B)(new C()).a).PBB"),
EvalResult("PBC", "null", "object", "((B)(new C()).a).PBC"),
EvalResult("PBD", "null", "object", "((B)(new C()).a).PBD"),
EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class),
EvalResult("Non-Public members", null, "", "(new C()).a, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
// Static members
var more = GetChildren(children[children.Length - 2]);
Verify(more,
EvalResult("SFA0", "null", "object", "A.SFA0"),
EvalResult("SFB2", "null", "object", "B.SFB2"),
EvalResult("SFB3", "null", "object", "B.SFB3"),
EvalResult("SFB4", "null", "object", "B.SFB4"),
EvalResult("SPA2", "null", "object", "A.SPA2", DkmEvaluationResultFlags.ReadOnly),
EvalResult("SPA3", "null", "object", "A.SPA3", DkmEvaluationResultFlags.ReadOnly),
EvalResult("SPB0", "null", "object", "B.SPB0", DkmEvaluationResultFlags.ReadOnly),
EvalResult("SPB1", "null", "object", "B.SPB1"),
EvalResult("Non-Public members", null, "", "B, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
// Non-Public static members
more = GetChildren(more[more.Length - 1]);
Verify(more,
EvalResult("SFA1", "null", "object", "A.SFA1"),
EvalResult("SPA4", "null", "object", "A.SPA4"));
// Non-Public members
more = GetChildren(children[children.Length - 1]);
Verify(more,
EvalResult("FA1", "null", "object", "(new C()).a.FA1"),
EvalResult("FA4", "null", "object", "(new C()).a.FA4"),
EvalResult("PA1", "null", "object", "(new C()).a.PA1", DkmEvaluationResultFlags.ReadOnly),
EvalResult("PA4", "null", "object", "(new C()).a.PA4", DkmEvaluationResultFlags.ReadOnly),
EvalResult("PA6", "null", "object", "(new C()).a.PA6"),
EvalResult("PA9", "null", "object", "(new C()).a.PA9"),
EvalResult("PAA", "null", "object", "(new C()).a.PAA"),
EvalResult("PAB", "null", "object", "(new C()).a.PAB"),
EvalResult("PAD", "null", "object", "(new C()).a.PAD"));
}
[WorkItem(889710)]
[Fact]
public void HideNonPublicMembersDerivedClass()
{
var sourceA =
@"public class A
{
public object FA0;
internal object FA1;
protected internal object FA2;
protected object FA3;
private object FA4;
public object PA0 { get { return null; } }
internal object PA1 { get { return null; } }
protected internal object PA2 { get { return null; } }
protected object PA3 { get { return null; } }
private object PA4 { get { return null; } }
public object PA5 { set { } }
public object PA6 { internal get; set; }
public object PA7 { protected internal get; set; }
public object PA8 { protected get; set; }
public object PA9 { private get; set; }
internal object PAA { private get; set; }
protected internal object PAB { internal get; set; }
protected internal object PAC { protected get; set; }
protected object PAD { private get; set; }
public static object SFA0;
internal static object SFA1;
protected static internal object SPA2 { get { return null; } }
protected static object SPA3 { get { return null; } }
public static object SPA4 { private get { return null; } set { } }
}";
var sourceB =
@"public class B : A
{
public object FB0;
internal object FB1;
protected internal object FB2;
protected object FB3;
private object FB4;
public object PB0 { get { return null; } }
internal object PB1 { get { return null; } }
protected internal object PB2 { get { return null; } }
protected object PB3 { get { return null; } }
private object PB4 { get { return null; } }
public object PB5 { set { } }
public object PB6 { internal get; set; }
public object PB7 { protected internal get; set; }
public object PB8 { protected get; set; }
public object PB9 { private get; set; }
internal object PBA { private get; set; }
protected internal object PBB { internal get; set; }
protected internal object PBC { protected get; set; }
protected object PBD { private get; set; }
public static object SPB0 { get { return null; } }
public static object SPB1 { internal get { return null; } set { } }
protected static internal object SFB2;
protected static object SFB3;
private static object SFB4;
}
class C
{
A a = new B();
}";
// Base class in assembly with PDB,
// derived class in assembly without PDB.
var compilationA = CSharpTestBase.CreateCompilationWithMscorlib(sourceA, options: TestOptions.DebugDll);
var bytesA = compilationA.EmitToArray();
var referenceA = MetadataReference.CreateFromImage(bytesA);
var compilationB = CSharpTestBase.CreateCompilationWithMscorlib(sourceB, options: TestOptions.ReleaseDll, references: new MetadataReference[] { referenceA });
var bytesB = compilationB.EmitToArray();
var assemblyA = ReflectionUtilities.Load(bytesA);
var assemblyB = ReflectionUtilities.Load(bytesB);
DkmClrValue value;
using (ReflectionUtilities.LoadAssemblies(assemblyA, assemblyB))
{
var runtime = new DkmClrRuntimeInstance(new[] { assemblyA });
var type = assemblyB.GetType("C", throwOnError: true);
value = CreateDkmClrValue(
Activator.CreateInstance(type),
runtime.GetType((TypeImpl)type));
}
var rootExpr = "new C()";
var evalResult = FormatResult(rootExpr, value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers));
Verify(evalResult,
EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("Non-Public members", null, "", "new C(), hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
children = GetChildren(children[0]);
Verify(children,
EvalResult("a", "{B}", "A {B}", "(new C()).a", DkmEvaluationResultFlags.Expandable));
// The native EE includes properties where the
// setter is accessible but the getter is not.
// We treat those properties as non-public.
children = GetChildren(children[0]);
Verify(children,
EvalResult("FA0", "null", "object", "(new C()).a.FA0"),
EvalResult("FA1", "null", "object", "(new C()).a.FA1"),
EvalResult("FA2", "null", "object", "(new C()).a.FA2"),
EvalResult("FA3", "null", "object", "(new C()).a.FA3"),
EvalResult("FA4", "null", "object", "(new C()).a.FA4"),
EvalResult("FB0", "null", "object", "((B)(new C()).a).FB0"),
EvalResult("FB2", "null", "object", "((B)(new C()).a).FB2"),
EvalResult("FB3", "null", "object", "((B)(new C()).a).FB3"),
EvalResult("PA0", "null", "object", "(new C()).a.PA0", DkmEvaluationResultFlags.ReadOnly),
EvalResult("PA1", "null", "object", "(new C()).a.PA1", DkmEvaluationResultFlags.ReadOnly),
EvalResult("PA2", "null", "object", "(new C()).a.PA2", DkmEvaluationResultFlags.ReadOnly),
EvalResult("PA3", "null", "object", "(new C()).a.PA3", DkmEvaluationResultFlags.ReadOnly),
EvalResult("PA4", "null", "object", "(new C()).a.PA4", DkmEvaluationResultFlags.ReadOnly),
EvalResult("PA6", "null", "object", "(new C()).a.PA6"),
EvalResult("PA7", "null", "object", "(new C()).a.PA7"),
EvalResult("PA8", "null", "object", "(new C()).a.PA8"),
EvalResult("PA9", "null", "object", "(new C()).a.PA9"),
EvalResult("PAA", "null", "object", "(new C()).a.PAA"),
EvalResult("PAB", "null", "object", "(new C()).a.PAB"),
EvalResult("PAC", "null", "object", "(new C()).a.PAC"),
EvalResult("PAD", "null", "object", "(new C()).a.PAD"),
EvalResult("PB0", "null", "object", "((B)(new C()).a).PB0", DkmEvaluationResultFlags.ReadOnly),
EvalResult("PB2", "null", "object", "((B)(new C()).a).PB2", DkmEvaluationResultFlags.ReadOnly),
EvalResult("PB3", "null", "object", "((B)(new C()).a).PB3", DkmEvaluationResultFlags.ReadOnly),
EvalResult("PB7", "null", "object", "((B)(new C()).a).PB7"),
EvalResult("PB8", "null", "object", "((B)(new C()).a).PB8"),
EvalResult("PBC", "null", "object", "((B)(new C()).a).PBC"),
EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class),
EvalResult("Non-Public members", null, "", "(new C()).a, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
// Static members
var more = GetChildren(children[children.Length - 2]);
Verify(more,
EvalResult("SFA0", "null", "object", "A.SFA0"),
EvalResult("SFA1", "null", "object", "A.SFA1"),
EvalResult("SFB2", "null", "object", "B.SFB2"),
EvalResult("SFB3", "null", "object", "B.SFB3"),
EvalResult("SPA2", "null", "object", "A.SPA2", DkmEvaluationResultFlags.ReadOnly),
EvalResult("SPA3", "null", "object", "A.SPA3", DkmEvaluationResultFlags.ReadOnly),
EvalResult("SPA4", "null", "object", "A.SPA4"),
EvalResult("SPB0", "null", "object", "B.SPB0", DkmEvaluationResultFlags.ReadOnly),
EvalResult("Non-Public members", null, "", "B, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
// Non-Public static members
more = GetChildren(more[more.Length - 1]);
Verify(more,
EvalResult("SFB4", "null", "object", "B.SFB4"),
EvalResult("SPB1", "null", "object", "B.SPB1"));
// Non-Public members
more = GetChildren(children[children.Length - 1]);
Verify(more,
EvalResult("FB1", "null", "object", "((B)(new C()).a).FB1"),
EvalResult("FB4", "null", "object", "((B)(new C()).a).FB4"),
EvalResult("PB1", "null", "object", "((B)(new C()).a).PB1", DkmEvaluationResultFlags.ReadOnly),
EvalResult("PB4", "null", "object", "((B)(new C()).a).PB4", DkmEvaluationResultFlags.ReadOnly),
EvalResult("PB6", "null", "object", "((B)(new C()).a).PB6"),
EvalResult("PB9", "null", "object", "((B)(new C()).a).PB9"),
EvalResult("PBA", "null", "object", "((B)(new C()).a).PBA"),
EvalResult("PBB", "null", "object", "((B)(new C()).a).PBB"),
EvalResult("PBD", "null", "object", "((B)(new C()).a).PBD"));
}
/// <summary>
/// Class in assembly with no module. (For instance,
/// an anonymous type created during debugging.)
/// </summary>
[Fact]
public void NoModule()
{
var source =
@"class C
{
object F;
}";
var assembly = GetAssembly(source);
var runtime = new DkmClrRuntimeInstance(new[] { assembly }, (r, a) => null);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
Activator.CreateInstance(type),
runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers));
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
}
}
}
| |
// 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.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Internal;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Reflection.Metadata
{
/// <summary>
/// Reads metadata as defined byte the ECMA 335 CLI specification.
/// </summary>
sealed partial class MetadataReader
{
private readonly MetadataReaderOptions options;
internal readonly MetadataStringDecoder utf8Decoder;
internal readonly NamespaceCache namespaceCache;
private Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>> lazyNestedTypesMap;
internal readonly MemoryBlock Block;
// A row id of "mscorlib" AssemblyRef in a WinMD file (each WinMD file must have such a reference).
internal readonly uint WinMDMscorlibRef;
#region Constructors
/// <summary>
/// Creates a metadata reader from the metadata stored at the given memory location.
/// </summary>
/// <remarks>
/// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>.
/// </remarks>
public unsafe MetadataReader(byte* metadata, int length)
: this(metadata, length, MetadataReaderOptions.Default, null)
{
}
/// <summary>
/// Creates a metadata reader from the metadata stored at the given memory location.
/// </summary>
/// <remarks>
/// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>.
/// Use <see cref="PEReaderExtensions.GetMetadataReader(PortableExecutable.PEReader, MetadataReaderOptions)"/> to obtain
/// metadata from a PE image.
/// </remarks>
public unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options)
: this(metadata, length, options, null)
{
}
/// <summary>
/// Creates a metadata reader from the metadata stored at the given memory location.
/// </summary>
/// <remarks>
/// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>.
/// Use <see cref="PEReaderExtensions.GetMetadataReader(PortableExecutable.PEReader, MetadataReaderOptions, MetadataStringDecoder)"/> to obtain
/// metadata from a PE image.
/// </remarks>
public unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options, MetadataStringDecoder utf8Decoder)
{
if (length <= 0)
{
throw new ArgumentOutOfRangeException("length");
}
if (metadata == null)
{
throw new ArgumentNullException("metadata");
}
if (utf8Decoder == null)
{
utf8Decoder = MetadataStringDecoder.DefaultUTF8;
}
if (!(utf8Decoder.Encoding is UTF8Encoding))
{
throw new ArgumentException(MetadataResources.MetadataStringDecoderEncodingMustBeUtf8, "utf8Decoder");
}
if (!BitConverter.IsLittleEndian)
{
throw new PlatformNotSupportedException(MetadataResources.LitteEndianArchitectureRequired);
}
this.Block = new MemoryBlock(metadata, length);
this.options = options;
this.utf8Decoder = utf8Decoder;
BlobReader memReader = new BlobReader(this.Block);
this.ReadMetadataHeader(ref memReader);
// storage header and stream headers:
MemoryBlock metadataTableStream;
var streamHeaders = this.ReadStreamHeaders(ref memReader);
this.InitializeStreamReaders(ref this.Block, streamHeaders, out metadataTableStream);
memReader = new BlobReader(metadataTableStream);
uint[] metadataTableRowCounts;
this.ReadMetadataTableHeader(ref memReader, out metadataTableRowCounts);
this.InitializeTableReaders(memReader.GetMemoryBlockAt(0, memReader.RemainingBytes), metadataTableRowCounts);
// This previously could occur in obfuscated assemblies but a check was added to prevent
// it getting to this point
DebugCorlib.Assert(this.AssemblyTable.NumberOfRows <= 1);
// Although the specification states that the module table will have exactly one row,
// the native metadata reader would successfully read files containing more than one row.
// Such files exist in the wild and may be produced by obfuscators.
if (this.ModuleTable.NumberOfRows < 1)
{
throw new BadImageFormatException(string.Format(MetadataResources.ModuleTableInvalidNumberOfRows, this.ModuleTable.NumberOfRows));
}
// read
this.namespaceCache = new NamespaceCache(this);
if (this.metadataKind != MetadataKind.Ecma335)
{
this.WinMDMscorlibRef = FindMscorlibAssemblyRefNoProjection();
}
}
#endregion
#region Metadata Headers
private MetadataHeader metadataHeader;
private MetadataKind metadataKind;
private MetadataStreamKind metadataStreamKind;
internal StringStreamReader StringStream;
internal BlobStreamReader BlobStream;
internal GuidStreamReader GuidStream;
internal UserStringStreamReader UserStringStream;
/// <summary>
/// True if the metadata stream has minimal delta format. Used for EnC.
/// </summary>
/// <remarks>
/// The metadata stream has minimal delta format if "#JTD" stream is present.
/// Minimal delta format uses large size (4B) when encoding table/heap references.
/// The heaps in minimal delta only contain data of the delta,
/// there is no padding at the beginning of the heaps that would align them
/// with the original full metadata heaps.
/// </remarks>
internal bool IsMinimalDelta;
/// <summary>
/// Looks like this function reads beginning of the header described in
/// Ecma-335 24.2.1 Metadata root
/// </summary>
private void ReadMetadataHeader(ref BlobReader memReader)
{
if (memReader.RemainingBytes < COR20Constants.MinimumSizeofMetadataHeader)
{
throw new BadImageFormatException(MetadataResources.MetadataHeaderTooSmall);
}
this.metadataHeader.Signature = memReader.ReadUInt32();
if (this.metadataHeader.Signature != COR20Constants.COR20MetadataSignature)
{
throw new BadImageFormatException(MetadataResources.MetadataSignature);
}
this.metadataHeader.MajorVersion = memReader.ReadUInt16();
this.metadataHeader.MinorVersion = memReader.ReadUInt16();
this.metadataHeader.ExtraData = memReader.ReadUInt32();
this.metadataHeader.VersionStringSize = memReader.ReadInt32();
if (memReader.RemainingBytes < this.metadataHeader.VersionStringSize)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForVersionString);
}
int numberOfBytesRead;
this.metadataHeader.VersionString = memReader.GetMemoryBlockAt(0, this.metadataHeader.VersionStringSize).PeekUtf8NullTerminated(0, null, utf8Decoder, out numberOfBytesRead, '\0');
memReader.SkipBytes(this.metadataHeader.VersionStringSize);
this.metadataKind = GetMetadataKind(metadataHeader.VersionString);
}
private MetadataKind GetMetadataKind(string versionString)
{
// Treat metadata as CLI raw metadata if the client doesn't want to see projections.
if ((options & MetadataReaderOptions.ApplyWindowsRuntimeProjections) == 0)
{
return MetadataKind.Ecma335;
}
if (!versionString.Contains("WindowsRuntime"))
{
return MetadataKind.Ecma335;
}
else if (versionString.Contains("CLR"))
{
return MetadataKind.ManagedWindowsMetadata;
}
else
{
return MetadataKind.WindowsMetadata;
}
}
/// <summary>
/// Reads stream headers described in Ecma-335 24.2.2 Stream header
/// </summary>
private StreamHeader[] ReadStreamHeaders(ref BlobReader memReader)
{
// storage header:
memReader.ReadUInt16();
int streamCount = memReader.ReadInt16();
var streamHeaders = new StreamHeader[streamCount];
for (int i = 0; i < streamHeaders.Length; i++)
{
if (memReader.RemainingBytes < COR20Constants.MinimumSizeofStreamHeader)
{
throw new BadImageFormatException(MetadataResources.StreamHeaderTooSmall);
}
streamHeaders[i].Offset = memReader.ReadUInt32();
streamHeaders[i].Size = memReader.ReadInt32();
streamHeaders[i].Name = memReader.ReadUtf8NullTerminated();
bool aligned = memReader.TryAlign(4);
if (!aligned || memReader.RemainingBytes == 0)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForStreamHeaderName);
}
}
return streamHeaders;
}
private void InitializeStreamReaders(ref MemoryBlock metadataRoot, StreamHeader[] streamHeaders, out MemoryBlock metadataTableStream)
{
metadataTableStream = default(MemoryBlock);
foreach (StreamHeader streamHeader in streamHeaders)
{
switch (streamHeader.Name)
{
case COR20Constants.StringStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForStringStream);
}
this.StringStream = new StringStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size), this.metadataKind);
break;
case COR20Constants.BlobStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForBlobStream);
}
this.BlobStream = new BlobStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size), this.metadataKind);
break;
case COR20Constants.GUIDStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForGUIDStream);
}
this.GuidStream = new GuidStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size));
break;
case COR20Constants.UserStringStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForBlobStream);
}
this.UserStringStream = new UserStringStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size));
break;
case COR20Constants.CompressedMetadataTableStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForMetadataStream);
}
this.metadataStreamKind = MetadataStreamKind.Compressed;
metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size);
break;
case COR20Constants.UncompressedMetadataTableStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForMetadataStream);
}
this.metadataStreamKind = MetadataStreamKind.Uncompressed;
metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size);
break;
case COR20Constants.MinimalDeltaMetadataTableStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForMetadataStream);
}
// the content of the stream is ignored
this.IsMinimalDelta = true;
break;
default:
// Skip unknown streams. Some obfuscators insert invalid streams.
continue;
}
}
if (IsMinimalDelta && metadataStreamKind != MetadataStreamKind.Uncompressed)
{
throw new BadImageFormatException(MetadataResources.InvalidMetadataStreamFormat);
}
}
#endregion
#region Tables and Heaps
private MetadataTableHeader MetadataTableHeader;
/// <summary>
/// A row count for each possible table. May be indexed by <see cref="TableIndex"/>.
/// </summary>
internal uint[] TableRowCounts;
internal ModuleTableReader ModuleTable;
internal TypeRefTableReader TypeRefTable;
internal TypeDefTableReader TypeDefTable;
internal FieldPtrTableReader FieldPtrTable;
internal FieldTableReader FieldTable;
internal MethodPtrTableReader MethodPtrTable;
internal MethodTableReader MethodDefTable;
internal ParamPtrTableReader ParamPtrTable;
internal ParamTableReader ParamTable;
internal InterfaceImplTableReader InterfaceImplTable;
internal MemberRefTableReader MemberRefTable;
internal ConstantTableReader ConstantTable;
internal CustomAttributeTableReader CustomAttributeTable;
internal FieldMarshalTableReader FieldMarshalTable;
internal DeclSecurityTableReader DeclSecurityTable;
internal ClassLayoutTableReader ClassLayoutTable;
internal FieldLayoutTableReader FieldLayoutTable;
internal StandAloneSigTableReader StandAloneSigTable;
internal EventMapTableReader EventMapTable;
internal EventPtrTableReader EventPtrTable;
internal EventTableReader EventTable;
internal PropertyMapTableReader PropertyMapTable;
internal PropertyPtrTableReader PropertyPtrTable;
internal PropertyTableReader PropertyTable;
internal MethodSemanticsTableReader MethodSemanticsTable;
internal MethodImplTableReader MethodImplTable;
internal ModuleRefTableReader ModuleRefTable;
internal TypeSpecTableReader TypeSpecTable;
internal ImplMapTableReader ImplMapTable;
internal FieldRVATableReader FieldRvaTable;
internal EnCLogTableReader EncLogTable;
internal EnCMapTableReader EncMapTable;
internal AssemblyTableReader AssemblyTable;
internal AssemblyProcessorTableReader AssemblyProcessorTable; // unused
internal AssemblyOSTableReader AssemblyOSTable; // unused
internal AssemblyRefTableReader AssemblyRefTable;
internal AssemblyRefProcessorTableReader AssemblyRefProcessorTable; // unused
internal AssemblyRefOSTableReader AssemblyRefOSTable; // unused
internal FileTableReader FileTable;
internal ExportedTypeTableReader ExportedTypeTable;
internal ManifestResourceTableReader ManifestResourceTable;
internal NestedClassTableReader NestedClassTable;
internal GenericParamTableReader GenericParamTable;
internal MethodSpecTableReader MethodSpecTable;
internal GenericParamConstraintTableReader GenericParamConstraintTable;
private void ReadMetadataTableHeader(ref BlobReader memReader, out uint[] metadataTableRowCounts)
{
if (memReader.RemainingBytes < MetadataStreamConstants.SizeOfMetadataTableHeader)
{
throw new BadImageFormatException(MetadataResources.MetadataTableHeaderTooSmall);
}
this.MetadataTableHeader.Reserved = memReader.ReadUInt32();
this.MetadataTableHeader.MajorVersion = memReader.ReadByte();
this.MetadataTableHeader.MinorVersion = memReader.ReadByte();
this.MetadataTableHeader.HeapSizeFlags = (HeapSizeFlag)memReader.ReadByte();
this.MetadataTableHeader.RowId = memReader.ReadByte();
this.MetadataTableHeader.ValidTables = (TableMask)memReader.ReadUInt64();
this.MetadataTableHeader.SortedTables = (TableMask)memReader.ReadUInt64();
ulong presentTables = (ulong)this.MetadataTableHeader.ValidTables;
// According to ECMA-335, MajorVersion and MinorVersion have fixed values and,
// based on recommendation in 24.1 Fixed fields: When writing these fields it
// is best that they be set to the value indicated, on reading they should be ignored.?
// we will not be checking version values. We will continue checking that the set of
// present tables is within the set we understand.
ulong validTables = (ulong)TableMask.V2_0_TablesMask;
if ((presentTables & ~validTables) != 0)
{
throw new BadImageFormatException(string.Format(MetadataResources.UnknownTables, presentTables));
}
if (this.metadataStreamKind == MetadataStreamKind.Compressed)
{
// In general Ptr tables and EnC tables are not allowed in a compressed stream.
// However when asked for a snapshot of the current metadata after an EnC change has been applied
// the CLR includes the EnCLog table into the snapshot. We need to be able to read the image,
// so we'll allow the table here but pretend it's empty later.
if ((presentTables & (ulong)(TableMask.PtrTables | TableMask.EnCMap)) != 0)
{
throw new BadImageFormatException(MetadataResources.IllegalTablesInCompressedMetadataStream);
}
}
int numberOfTables = this.MetadataTableHeader.GetNumberOfTablesPresent();
if (memReader.RemainingBytes < numberOfTables * sizeof(int))
{
throw new BadImageFormatException(MetadataResources.TableRowCountSpaceTooSmall);
}
var rowCounts = new uint[numberOfTables];
for (int i = 0; i < rowCounts.Length; i++)
{
rowCounts[i] = memReader.ReadUInt32();
}
metadataTableRowCounts = rowCounts;
}
private const int SmallIndexSize = 2;
private const int LargeIndexSize = 4;
private void InitializeTableReaders(MemoryBlock metadataTablesMemoryBlock, uint[] compressedRowCounts)
{
// Only sizes of tables present in metadata are recorded in rowCountCompressedArray.
// This array contains a slot for each possible table, not just those that are present in the metadata.
uint[] rowCounts = new uint[TableIndexExtensions.Count];
// Size of reference tags in each table.
int[] referenceSizes = new int[TableIndexExtensions.Count];
ulong validTables = (ulong)this.MetadataTableHeader.ValidTables;
int compressedRowCountIndex = 0;
for (int i = 0; i < TableIndexExtensions.Count; i++)
{
bool fitsSmall;
if ((validTables & 1UL) != 0)
{
uint rowCount = compressedRowCounts[compressedRowCountIndex++];
rowCounts[i] = rowCount;
fitsSmall = rowCount < MetadataStreamConstants.LargeTableRowCount;
}
else
{
fitsSmall = true;
}
referenceSizes[i] = (fitsSmall && !IsMinimalDelta) ? SmallIndexSize : LargeIndexSize;
validTables >>= 1;
}
this.TableRowCounts = rowCounts;
// Compute ref sizes for tables that can have pointer tables for it
int fieldRefSize = referenceSizes[(int)TableIndex.FieldPtr] > SmallIndexSize ? LargeIndexSize : referenceSizes[(int)TableIndex.Field];
int methodRefSize = referenceSizes[(int)TableIndex.MethodPtr] > SmallIndexSize ? LargeIndexSize : referenceSizes[(int)TableIndex.MethodDef];
int paramRefSize = referenceSizes[(int)TableIndex.ParamPtr] > SmallIndexSize ? LargeIndexSize : referenceSizes[(int)TableIndex.Param];
int eventRefSize = referenceSizes[(int)TableIndex.EventPtr] > SmallIndexSize ? LargeIndexSize : referenceSizes[(int)TableIndex.Event];
int propertyRefSize = referenceSizes[(int)TableIndex.PropertyPtr] > SmallIndexSize ? LargeIndexSize : referenceSizes[(int)TableIndex.Property];
// Compute the coded token ref sizes
int typeDefOrRefRefSize = ComputeCodedTokenSize(TypeDefOrRefTag.LargeRowSize, rowCounts, TypeDefOrRefTag.TablesReferenced);
int hasConstantRefSize = ComputeCodedTokenSize(HasConstantTag.LargeRowSize, rowCounts, HasConstantTag.TablesReferenced);
int hasCustomAttributeRefSize = ComputeCodedTokenSize(HasCustomAttributeTag.LargeRowSize, rowCounts, HasCustomAttributeTag.TablesReferenced);
int hasFieldMarshalRefSize = ComputeCodedTokenSize(HasFieldMarshalTag.LargeRowSize, rowCounts, HasFieldMarshalTag.TablesReferenced);
int hasDeclSecurityRefSize = ComputeCodedTokenSize(HasDeclSecurityTag.LargeRowSize, rowCounts, HasDeclSecurityTag.TablesReferenced);
int memberRefParentRefSize = ComputeCodedTokenSize(MemberRefParentTag.LargeRowSize, rowCounts, MemberRefParentTag.TablesReferenced);
int hasSemanticsRefSize = ComputeCodedTokenSize(HasSemanticsTag.LargeRowSize, rowCounts, HasSemanticsTag.TablesReferenced);
int methodDefOrRefRefSize = ComputeCodedTokenSize(MethodDefOrRefTag.LargeRowSize, rowCounts, MethodDefOrRefTag.TablesReferenced);
int memberForwardedRefSize = ComputeCodedTokenSize(MemberForwardedTag.LargeRowSize, rowCounts, MemberForwardedTag.TablesReferenced);
int implementationRefSize = ComputeCodedTokenSize(ImplementationTag.LargeRowSize, rowCounts, ImplementationTag.TablesReferenced);
int customAttributeTypeRefSize = ComputeCodedTokenSize(CustomAttributeTypeTag.LargeRowSize, rowCounts, CustomAttributeTypeTag.TablesReferenced);
int resolutionScopeRefSize = ComputeCodedTokenSize(ResolutionScopeTag.LargeRowSize, rowCounts, ResolutionScopeTag.TablesReferenced);
int typeOrMethodDefRefSize = ComputeCodedTokenSize(TypeOrMethodDefTag.LargeRowSize, rowCounts, TypeOrMethodDefTag.TablesReferenced);
// Compute HeapRef Sizes
int stringHeapRefSize = (this.MetadataTableHeader.HeapSizeFlags & HeapSizeFlag.StringHeapLarge) == HeapSizeFlag.StringHeapLarge ? LargeIndexSize : SmallIndexSize;
int guidHeapRefSize = (this.MetadataTableHeader.HeapSizeFlags & HeapSizeFlag.GuidHeapLarge) == HeapSizeFlag.GuidHeapLarge ? LargeIndexSize : SmallIndexSize;
int blobHeapRefSize = (this.MetadataTableHeader.HeapSizeFlags & HeapSizeFlag.BlobHeapLarge) == HeapSizeFlag.BlobHeapLarge ? LargeIndexSize : SmallIndexSize;
// Populate the Table blocks
int totalRequiredSize = 0;
this.ModuleTable = new ModuleTableReader(rowCounts[(int)TableIndex.Module], stringHeapRefSize, guidHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ModuleTable.Block.Length;
this.TypeRefTable = new TypeRefTableReader(rowCounts[(int)TableIndex.TypeRef], resolutionScopeRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.TypeRefTable.Block.Length;
this.TypeDefTable = new TypeDefTableReader(rowCounts[(int)TableIndex.TypeDef], fieldRefSize, methodRefSize, typeDefOrRefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.TypeDefTable.Block.Length;
this.FieldPtrTable = new FieldPtrTableReader(rowCounts[(int)TableIndex.FieldPtr], referenceSizes[(int)TableIndex.Field], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FieldPtrTable.Block.Length;
this.FieldTable = new FieldTableReader(rowCounts[(int)TableIndex.Field], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FieldTable.Block.Length;
this.MethodPtrTable = new MethodPtrTableReader(rowCounts[(int)TableIndex.MethodPtr], referenceSizes[(int)TableIndex.MethodDef], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MethodPtrTable.Block.Length;
this.MethodDefTable = new MethodTableReader(rowCounts[(int)TableIndex.MethodDef], paramRefSize, stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MethodDefTable.Block.Length;
this.ParamPtrTable = new ParamPtrTableReader(rowCounts[(int)TableIndex.ParamPtr], referenceSizes[(int)TableIndex.Param], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ParamPtrTable.Block.Length;
this.ParamTable = new ParamTableReader(rowCounts[(int)TableIndex.Param], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ParamTable.Block.Length;
this.InterfaceImplTable = new InterfaceImplTableReader(rowCounts[(int)TableIndex.InterfaceImpl], IsDeclaredSorted(TableMask.InterfaceImpl), referenceSizes[(int)TableIndex.TypeDef], typeDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.InterfaceImplTable.Block.Length;
this.MemberRefTable = new MemberRefTableReader(rowCounts[(int)TableIndex.MemberRef], memberRefParentRefSize, stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MemberRefTable.Block.Length;
this.ConstantTable = new ConstantTableReader(rowCounts[(int)TableIndex.Constant], IsDeclaredSorted(TableMask.Constant), hasConstantRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ConstantTable.Block.Length;
this.CustomAttributeTable = new CustomAttributeTableReader(rowCounts[(int)TableIndex.CustomAttribute],
IsDeclaredSorted(TableMask.CustomAttribute),
hasCustomAttributeRefSize,
customAttributeTypeRefSize,
blobHeapRefSize,
metadataTablesMemoryBlock,
totalRequiredSize);
totalRequiredSize += this.CustomAttributeTable.Block.Length;
this.FieldMarshalTable = new FieldMarshalTableReader(rowCounts[(int)TableIndex.FieldMarshal], IsDeclaredSorted(TableMask.FieldMarshal), hasFieldMarshalRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FieldMarshalTable.Block.Length;
this.DeclSecurityTable = new DeclSecurityTableReader(rowCounts[(int)TableIndex.DeclSecurity], IsDeclaredSorted(TableMask.DeclSecurity), hasDeclSecurityRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.DeclSecurityTable.Block.Length;
this.ClassLayoutTable = new ClassLayoutTableReader(rowCounts[(int)TableIndex.ClassLayout], IsDeclaredSorted(TableMask.ClassLayout), referenceSizes[(int)TableIndex.TypeDef], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ClassLayoutTable.Block.Length;
this.FieldLayoutTable = new FieldLayoutTableReader(rowCounts[(int)TableIndex.FieldLayout], IsDeclaredSorted(TableMask.FieldLayout), referenceSizes[(int)TableIndex.Field], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FieldLayoutTable.Block.Length;
this.StandAloneSigTable = new StandAloneSigTableReader(rowCounts[(int)TableIndex.StandAloneSig], blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.StandAloneSigTable.Block.Length;
this.EventMapTable = new EventMapTableReader(rowCounts[(int)TableIndex.EventMap], referenceSizes[(int)TableIndex.TypeDef], eventRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.EventMapTable.Block.Length;
this.EventPtrTable = new EventPtrTableReader(rowCounts[(int)TableIndex.EventPtr], referenceSizes[(int)TableIndex.Event], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.EventPtrTable.Block.Length;
this.EventTable = new EventTableReader(rowCounts[(int)TableIndex.Event], typeDefOrRefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.EventTable.Block.Length;
this.PropertyMapTable = new PropertyMapTableReader(rowCounts[(int)TableIndex.PropertyMap], referenceSizes[(int)TableIndex.TypeDef], propertyRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.PropertyMapTable.Block.Length;
this.PropertyPtrTable = new PropertyPtrTableReader(rowCounts[(int)TableIndex.PropertyPtr], referenceSizes[(int)TableIndex.Property], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.PropertyPtrTable.Block.Length;
this.PropertyTable = new PropertyTableReader(rowCounts[(int)TableIndex.Property], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.PropertyTable.Block.Length;
this.MethodSemanticsTable = new MethodSemanticsTableReader(rowCounts[(int)TableIndex.MethodSemantics], IsDeclaredSorted(TableMask.MethodSemantics), referenceSizes[(int)TableIndex.MethodDef], hasSemanticsRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MethodSemanticsTable.Block.Length;
this.MethodImplTable = new MethodImplTableReader(rowCounts[(int)TableIndex.MethodImpl], IsDeclaredSorted(TableMask.MethodImpl), referenceSizes[(int)TableIndex.TypeDef], methodDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MethodImplTable.Block.Length;
this.ModuleRefTable = new ModuleRefTableReader(rowCounts[(int)TableIndex.ModuleRef], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ModuleRefTable.Block.Length;
this.TypeSpecTable = new TypeSpecTableReader(rowCounts[(int)TableIndex.TypeSpec], blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.TypeSpecTable.Block.Length;
this.ImplMapTable = new ImplMapTableReader(rowCounts[(int)TableIndex.ImplMap], IsDeclaredSorted(TableMask.ImplMap), referenceSizes[(int)TableIndex.ModuleRef], memberForwardedRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ImplMapTable.Block.Length;
this.FieldRvaTable = new FieldRVATableReader(rowCounts[(int)TableIndex.FieldRva], IsDeclaredSorted(TableMask.FieldRva), referenceSizes[(int)TableIndex.Field], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FieldRvaTable.Block.Length;
this.EncLogTable = new EnCLogTableReader(rowCounts[(int)TableIndex.EncLog], metadataTablesMemoryBlock, totalRequiredSize, this.metadataStreamKind);
totalRequiredSize += this.EncLogTable.Block.Length;
this.EncMapTable = new EnCMapTableReader(rowCounts[(int)TableIndex.EncMap], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.EncMapTable.Block.Length;
this.AssemblyTable = new AssemblyTableReader(rowCounts[(int)TableIndex.Assembly], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.AssemblyTable.Block.Length;
this.AssemblyProcessorTable = new AssemblyProcessorTableReader(rowCounts[(int)TableIndex.AssemblyProcessor], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.AssemblyProcessorTable.Block.Length;
this.AssemblyOSTable = new AssemblyOSTableReader(rowCounts[(int)TableIndex.AssemblyOS], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.AssemblyOSTable.Block.Length;
this.AssemblyRefTable = new AssemblyRefTableReader((int)rowCounts[(int)TableIndex.AssemblyRef], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize, this.metadataKind);
totalRequiredSize += this.AssemblyRefTable.Block.Length;
this.AssemblyRefProcessorTable = new AssemblyRefProcessorTableReader(rowCounts[(int)TableIndex.AssemblyRefProcessor], referenceSizes[(int)TableIndex.AssemblyRef], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.AssemblyRefProcessorTable.Block.Length;
this.AssemblyRefOSTable = new AssemblyRefOSTableReader(rowCounts[(int)TableIndex.AssemblyRefOS], referenceSizes[(int)TableIndex.AssemblyRef], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.AssemblyRefOSTable.Block.Length;
this.FileTable = new FileTableReader(rowCounts[(int)TableIndex.File], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FileTable.Block.Length;
this.ExportedTypeTable = new ExportedTypeTableReader(rowCounts[(int)TableIndex.ExportedType], implementationRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ExportedTypeTable.Block.Length;
this.ManifestResourceTable = new ManifestResourceTableReader(rowCounts[(int)TableIndex.ManifestResource], implementationRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ManifestResourceTable.Block.Length;
this.NestedClassTable = new NestedClassTableReader(rowCounts[(int)TableIndex.NestedClass], IsDeclaredSorted(TableMask.NestedClass), referenceSizes[(int)TableIndex.TypeDef], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.NestedClassTable.Block.Length;
this.GenericParamTable = new GenericParamTableReader(rowCounts[(int)TableIndex.GenericParam], IsDeclaredSorted(TableMask.GenericParam), typeOrMethodDefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.GenericParamTable.Block.Length;
this.MethodSpecTable = new MethodSpecTableReader(rowCounts[(int)TableIndex.MethodSpec], methodDefOrRefRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MethodSpecTable.Block.Length;
this.GenericParamConstraintTable = new GenericParamConstraintTableReader(rowCounts[(int)TableIndex.GenericParamConstraint], IsDeclaredSorted(TableMask.GenericParamConstraint), referenceSizes[(int)TableIndex.GenericParam], typeDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.GenericParamConstraintTable.Block.Length;
if (totalRequiredSize > metadataTablesMemoryBlock.Length)
{
throw new BadImageFormatException(MetadataResources.MetadataTablesTooSmall);
}
}
private int ComputeCodedTokenSize(uint largeRowSize, uint[] rowCountArray, TableMask tablesReferenced)
{
if (IsMinimalDelta)
{
return LargeIndexSize;
}
bool isAllReferencedTablesSmall = true;
ulong tablesReferencedMask = (ulong)tablesReferenced;
for (int tableIndex = 0; tableIndex < TableIndexExtensions.Count; tableIndex++)
{
if ((tablesReferencedMask & 1UL) != 0)
{
isAllReferencedTablesSmall = isAllReferencedTablesSmall && (rowCountArray[tableIndex] < largeRowSize);
}
tablesReferencedMask >>= 1;
}
return isAllReferencedTablesSmall ? SmallIndexSize : LargeIndexSize;
}
private bool IsDeclaredSorted(TableMask index)
{
return (this.MetadataTableHeader.SortedTables & index) != 0;
}
#endregion
#region Helpers
// internal for testing
internal NamespaceCache NamespaceCache
{
get { return namespaceCache; }
}
internal bool UseFieldPtrTable
{
get { return this.FieldPtrTable.NumberOfRows > 0; }
}
internal bool UseMethodPtrTable
{
get { return this.MethodPtrTable.NumberOfRows > 0; }
}
internal bool UseParamPtrTable
{
get { return this.ParamPtrTable.NumberOfRows > 0; }
}
internal bool UseEventPtrTable
{
get { return this.EventPtrTable.NumberOfRows > 0; }
}
internal bool UsePropertyPtrTable
{
get { return this.PropertyPtrTable.NumberOfRows > 0; }
}
internal void GetFieldRange(TypeDefinitionHandle typeDef, out int firstFieldRowId, out int lastFieldRowId)
{
uint typeDefRowId = typeDef.RowId;
firstFieldRowId = (int)this.TypeDefTable.GetFieldStart(typeDefRowId);
if (firstFieldRowId == 0)
{
firstFieldRowId = 1;
lastFieldRowId = 0;
}
else if (typeDefRowId == this.TypeDefTable.NumberOfRows)
{
lastFieldRowId = (int)(this.UseFieldPtrTable ? this.FieldPtrTable.NumberOfRows : this.FieldTable.NumberOfRows);
}
else
{
lastFieldRowId = (int)this.TypeDefTable.GetFieldStart(typeDefRowId + 1) - 1;
}
}
internal void GetMethodRange(TypeDefinitionHandle typeDef, out int firstMethodRowId, out int lastMethodRowId)
{
uint typeDefRowId = typeDef.RowId;
firstMethodRowId = (int)this.TypeDefTable.GetMethodStart(typeDefRowId);
if (firstMethodRowId == 0)
{
firstMethodRowId = 1;
lastMethodRowId = 0;
}
else if (typeDefRowId == this.TypeDefTable.NumberOfRows)
{
lastMethodRowId = (int)(this.UseMethodPtrTable ? this.MethodPtrTable.NumberOfRows : this.MethodDefTable.NumberOfRows);
}
else
{
lastMethodRowId = (int)this.TypeDefTable.GetMethodStart(typeDefRowId + 1) - 1;
}
}
internal void GetEventRange(TypeDefinitionHandle typeDef, out int firstEventRowId, out int lastEventRowId)
{
uint eventMapRowId = this.EventMapTable.FindEventMapRowIdFor(typeDef);
if (eventMapRowId == 0)
{
firstEventRowId = 1;
lastEventRowId = 0;
return;
}
firstEventRowId = (int)this.EventMapTable.GetEventListStartFor(eventMapRowId);
if (eventMapRowId == this.EventMapTable.NumberOfRows)
{
lastEventRowId = (int)(this.UseEventPtrTable ? this.EventPtrTable.NumberOfRows : this.EventTable.NumberOfRows);
}
else
{
lastEventRowId = (int)this.EventMapTable.GetEventListStartFor(eventMapRowId + 1) - 1;
}
}
internal void GetPropertyRange(TypeDefinitionHandle typeDef, out int firstPropertyRowId, out int lastPropertyRowId)
{
uint propertyMapRowId = this.PropertyMapTable.FindPropertyMapRowIdFor(typeDef);
if (propertyMapRowId == 0)
{
firstPropertyRowId = 1;
lastPropertyRowId = 0;
return;
}
firstPropertyRowId = (int)this.PropertyMapTable.GetPropertyListStartFor(propertyMapRowId);
if (propertyMapRowId == this.PropertyMapTable.NumberOfRows)
{
lastPropertyRowId = (int)(this.UsePropertyPtrTable ? this.PropertyPtrTable.NumberOfRows : this.PropertyTable.NumberOfRows);
}
else
{
lastPropertyRowId = (int)this.PropertyMapTable.GetPropertyListStartFor(propertyMapRowId + 1) - 1;
}
}
internal void GetParameterRange(MethodDefinitionHandle methodDef, out int firstParamRowId, out int lastParamRowId)
{
uint rid = methodDef.RowId;
firstParamRowId = (int)this.MethodDefTable.GetParamStart(rid);
if (firstParamRowId == 0)
{
firstParamRowId = 1;
lastParamRowId = 0;
}
else if (rid == this.MethodDefTable.NumberOfRows)
{
lastParamRowId = (int)(this.UseParamPtrTable ? this.ParamPtrTable.NumberOfRows : this.ParamTable.NumberOfRows);
}
else
{
lastParamRowId = (int)this.MethodDefTable.GetParamStart(rid + 1) - 1;
}
}
// TODO: move throw helpers to common place.
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowValueArgumentNull()
{
throw new ArgumentNullException("value");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ThrowTableNotSorted(TableIndex tableIndex)
{
throw new BadImageFormatException(string.Format(MetadataResources.MetadataTableNotSorted, (int)tableIndex));
}
#endregion
#region Public APIs
public MetadataReaderOptions Options
{
get { return this.options; }
}
public string MetadataVersion
{
get { return metadataHeader.VersionString; }
}
public MetadataKind MetadataKind
{
get { return metadataKind; }
}
public MetadataStringComparer StringComparer
{
get { return new MetadataStringComparer(this); }
}
public bool IsAssembly
{
get { return this.AssemblyTable.NumberOfRows == 1; }
}
public AssemblyReferenceHandleCollection AssemblyReferences
{
get { return new AssemblyReferenceHandleCollection(this); }
}
public TypeDefinitionHandleCollection TypeDefinitions
{
get { return new TypeDefinitionHandleCollection((int)TypeDefTable.NumberOfRows); }
}
public TypeReferenceHandleCollection TypeReferences
{
get { return new TypeReferenceHandleCollection((int)TypeRefTable.NumberOfRows); }
}
public CustomAttributeHandleCollection CustomAttributes
{
get { return new CustomAttributeHandleCollection(this); }
}
public DeclarativeSecurityAttributeHandleCollection DeclarativeSecurityAttributes
{
get { return new DeclarativeSecurityAttributeHandleCollection(this); }
}
public MemberReferenceHandleCollection MemberReferences
{
get { return new MemberReferenceHandleCollection((int)MemberRefTable.NumberOfRows); }
}
public ManifestResourceHandleCollection ManifestResources
{
get { return new ManifestResourceHandleCollection((int)ManifestResourceTable.NumberOfRows); }
}
public AssemblyFileHandleCollection AssemblyFiles
{
get { return new AssemblyFileHandleCollection((int)FileTable.NumberOfRows); }
}
public ExportedTypeHandleCollection ExportedTypes
{
get { return new ExportedTypeHandleCollection((int)ExportedTypeTable.NumberOfRows); }
}
public MethodDefinitionHandleCollection MethodDefinitions
{
get { return new MethodDefinitionHandleCollection(this); }
}
public FieldDefinitionHandleCollection FieldDefinitions
{
get { return new FieldDefinitionHandleCollection(this); }
}
public EventDefinitionHandleCollection EventDefinitions
{
get { return new EventDefinitionHandleCollection(this); }
}
public PropertyDefinitionHandleCollection PropertyDefinitions
{
get { return new PropertyDefinitionHandleCollection(this); }
}
public AssemblyDefinition GetAssemblyDefinition()
{
if (!IsAssembly)
{
throw new InvalidOperationException(MetadataResources.MetadataImageDoesNotRepresentAnAssembly);
}
return new AssemblyDefinition(this);
}
public string GetString(StringHandle handle)
{
return StringStream.GetString(handle, utf8Decoder);
}
public string GetString(NamespaceDefinitionHandle handle)
{
if (handle.HasFullName)
{
return StringStream.GetString(handle.GetFullName(), utf8Decoder);
}
return namespaceCache.GetFullName(handle);
}
public byte[] GetBlobBytes(BlobHandle handle)
{
return BlobStream.GetBytes(handle);
}
public ImmutableArray<byte> GetBlobContent(BlobHandle handle)
{
// TODO: We can skip a copy for virtual blobs.
byte[] bytes = GetBlobBytes(handle);
return ImmutableArrayInterop.DangerousCreateFromUnderlyingArray(ref bytes);
}
public BlobReader GetBlobReader(BlobHandle handle)
{
return BlobStream.GetBlobReader(handle);
}
public string GetUserString(UserStringHandle handle)
{
return UserStringStream.GetString(handle);
}
public Guid GetGuid(GuidHandle handle)
{
return GuidStream.GetGuid(handle);
}
public ModuleDefinition GetModuleDefinition()
{
return new ModuleDefinition(this);
}
public AssemblyReference GetAssemblyReference(AssemblyReferenceHandle handle)
{
return new AssemblyReference(this, handle.Token & TokenTypeIds.VirtualBitAndRowIdMask);
}
public TypeDefinition GetTypeDefinition(TypeDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new TypeDefinition(this, GetTypeDefTreatmentAndRowId(handle));
}
public NamespaceDefinition GetNamespaceDefinitionRoot()
{
NamespaceData data = namespaceCache.GetRootNamespace();
return new NamespaceDefinition(data);
}
public NamespaceDefinition GetNamespaceDefinition(NamespaceDefinitionHandle handle)
{
NamespaceData data = namespaceCache.GetNamespaceData(handle);
return new NamespaceDefinition(data);
}
private uint GetTypeDefTreatmentAndRowId(TypeDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (this.metadataKind == MetadataKind.Ecma335)
{
return handle.RowId;
}
return CalculateTypeDefTreatmentAndRowId(handle);
}
public TypeReference GetTypeReference(TypeReferenceHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new TypeReference(this, GetTypeRefTreatmentAndRowId(handle));
}
private uint GetTypeRefTreatmentAndRowId(TypeReferenceHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (this.metadataKind == MetadataKind.Ecma335)
{
return handle.RowId;
}
return CalculateTypeRefTreatmentAndRowId(handle);
}
public ExportedType GetExportedType(ExportedTypeHandle handle)
{
return new ExportedType(this, handle.RowId);
}
public CustomAttributeHandleCollection GetCustomAttributes(Handle handle)
{
DebugCorlib.Assert(!handle.IsNil);
return new CustomAttributeHandleCollection(this, handle);
}
public CustomAttribute GetCustomAttribute(CustomAttributeHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new CustomAttribute(this, GetCustomAttributeTreatmentAndRowId(handle));
}
private uint GetCustomAttributeTreatmentAndRowId(CustomAttributeHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (this.metadataKind == MetadataKind.Ecma335)
{
return handle.RowId;
}
return TreatmentAndRowId((byte)CustomAttributeTreatment.WinMD, handle.RowId);
}
public DeclarativeSecurityAttribute GetDeclarativeSecurityAttribute(DeclarativeSecurityAttributeHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new DeclarativeSecurityAttribute(this, handle.RowId);
}
public Constant GetConstant(ConstantHandle handle)
{
return new Constant(this, handle.RowId);
}
public MethodDefinition GetMethodDefinition(MethodDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new MethodDefinition(this, GetMethodDefTreatmentAndRowId(handle));
}
private uint GetMethodDefTreatmentAndRowId(MethodDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (this.metadataKind == MetadataKind.Ecma335)
{
return handle.RowId;
}
return CalculateMethodDefTreatmentAndRowId(handle);
}
public FieldDefinition GetFieldDefinition(FieldDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new FieldDefinition(this, GetFieldDefTreatmentAndRowId(handle));
}
private uint GetFieldDefTreatmentAndRowId(FieldDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (this.metadataKind == MetadataKind.Ecma335)
{
return handle.RowId;
}
return CalculateFieldDefTreatmentAndRowId(handle);
}
public PropertyDefinition GetPropertyDefinition(PropertyDefinitionHandle handle)
{
return new PropertyDefinition(this, handle);
}
public EventDefinition GetEventDefinition(EventDefinitionHandle handle)
{
return new EventDefinition(this, handle);
}
public MethodImplementation GetMethodImplementation(MethodImplementationHandle handle)
{
return new MethodImplementation(this, handle);
}
public MemberReference GetMemberReference(MemberReferenceHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new MemberReference(this, GetMemberRefTreatmentAndRowId(handle));
}
private uint GetMemberRefTreatmentAndRowId(MemberReferenceHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (this.metadataKind == MetadataKind.Ecma335)
{
return handle.RowId;
}
return CalculateMemberRefTreatmentAndRowId(handle);
}
public MethodSpecification GetMethodSpecification(MethodSpecificationHandle handle)
{
return new MethodSpecification(this, handle);
}
public Parameter GetParameter(ParameterHandle handle)
{
return new Parameter(this, handle);
}
public GenericParameter GetGenericParameter(GenericParameterHandle handle)
{
return new GenericParameter(this, handle);
}
public GenericParameterConstraint GetGenericParameterConstraint(GenericParameterConstraintHandle handle)
{
return new GenericParameterConstraint(this, handle);
}
public ManifestResource GetManifestResource(ManifestResourceHandle handle)
{
return new ManifestResource(this, handle);
}
public AssemblyFile GetAssemblyFile(AssemblyFileHandle handle)
{
return new AssemblyFile(this, handle);
}
public StandaloneSignature GetStandaloneSignature(StandaloneSignatureHandle handle)
{
return new StandaloneSignature(this, handle);
}
public TypeSpecification GetTypeSpecification(TypeSpecificationHandle handle)
{
return new TypeSpecification(this, handle);
}
public ModuleReference GetModuleReference(ModuleReferenceHandle handle)
{
return new ModuleReference(this, handle);
}
public InterfaceImplementation GetInterfaceImplementation(InterfaceImplementationHandle handle)
{
return new InterfaceImplementation(this, handle);
}
internal TypeDefinitionHandle GetDeclaringType(MethodDefinitionHandle methodDef)
{
uint methodRowId;
if (UseMethodPtrTable)
{
methodRowId = MethodPtrTable.GetRowIdForMethodDefRow(methodDef.RowId);
}
else
{
methodRowId = methodDef.RowId;
}
return TypeDefTable.FindTypeContainingMethod(methodRowId, (int)MethodDefTable.NumberOfRows);
}
internal TypeDefinitionHandle GetDeclaringType(FieldDefinitionHandle fieldDef)
{
uint fieldRowId;
if (UseFieldPtrTable)
{
fieldRowId = FieldPtrTable.GetRowIdForFieldDefRow(fieldDef.RowId);
}
else
{
fieldRowId = fieldDef.RowId;
}
return TypeDefTable.FindTypeContainingField(fieldRowId, (int)FieldTable.NumberOfRows);
}
#endregion
#region Nested Types
private void InitializeNestedTypesMap()
{
var groupedNestedTypes = new Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>.Builder>();
uint numberOfNestedTypes = NestedClassTable.NumberOfRows;
ImmutableArray<TypeDefinitionHandle>.Builder builder = null;
TypeDefinitionHandle previousEnclosingClass = default(TypeDefinitionHandle);
for (uint i = 1; i <= numberOfNestedTypes; i++)
{
TypeDefinitionHandle enclosignClass = NestedClassTable.GetEnclosingClass(i);
DebugCorlib.Assert(!enclosignClass.IsNil);
if (enclosignClass != previousEnclosingClass)
{
if (!groupedNestedTypes.TryGetValue(enclosignClass, out builder))
{
builder = ImmutableArray.CreateBuilder<TypeDefinitionHandle>();
groupedNestedTypes.Add(enclosignClass, builder);
}
previousEnclosingClass = enclosignClass;
}
else
{
DebugCorlib.Assert(builder == groupedNestedTypes[enclosignClass]);
}
builder.Add(NestedClassTable.GetNestedClass(i));
}
var nestedTypesMap = new Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>>();
foreach (var group in groupedNestedTypes)
{
nestedTypesMap.Add(group.Key, group.Value.ToImmutable());
}
this.lazyNestedTypesMap = nestedTypesMap;
}
/// <summary>
/// Returns an array of types nested in the specified type.
/// </summary>
internal ImmutableArray<TypeDefinitionHandle> GetNestedTypes(TypeDefinitionHandle typeDef)
{
if (this.lazyNestedTypesMap == null)
{
InitializeNestedTypesMap();
}
ImmutableArray<TypeDefinitionHandle> nestedTypes;
if (this.lazyNestedTypesMap.TryGetValue(typeDef, out nestedTypes))
{
return nestedTypes;
}
return ImmutableArray<TypeDefinitionHandle>.Empty;
}
#endregion
}
}
| |
#region BSD License
/*
Copyright (c) 2004-2005 Matthew Holmes (matthew@wildfiregames.com), Dan Moorehead (dan05a@gmail.com)
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.
* The name of the author may not be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
#region CVS Information
/*
* $Source$
* $Author: sontek $
* $Date: 2008-04-30 23:36:53 +0000 (Wed, 30 Apr 2008) $
* $Revision: 267 $
*/
#endregion
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Xml;
using Prebuild.Core.Attributes;
using Prebuild.Core.Interfaces;
using Prebuild.Core.Utilities;
namespace Prebuild.Core.Nodes
{
/// <summary>
///
/// </summary>
[DataNode("Solution")]
[DataNode("EmbeddedSolution")]
[DebuggerDisplay("{Name}")]
public class SolutionNode : DataNode
{
#region Fields
private Guid m_Guid = Guid.NewGuid();
private string m_Name = "unknown";
private string m_Path = "";
private string m_FullPath = "";
private string m_ActiveConfig = "Debug";
private OptionsNode m_Options;
private FilesNode m_Files;
private Hashtable m_Configurations;
private Hashtable m_Projects;
private Hashtable m_DatabaseProjects;
private ArrayList m_ProjectsOrder;
private Hashtable m_Solutions;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="SolutionNode"/> class.
/// </summary>
public SolutionNode()
{
m_Configurations = new Hashtable();
m_Projects = new Hashtable();
m_ProjectsOrder = new ArrayList();
m_DatabaseProjects = new Hashtable();
m_Solutions = new Hashtable();
}
#endregion
#region Properties
public override IDataNode Parent
{
get
{
return base.Parent;
}
set
{
if (value is SolutionNode)
{
SolutionNode solution = (SolutionNode)value;
foreach (ConfigurationNode conf in solution.Configurations)
{
m_Configurations[conf.Name] = conf.Clone();
}
}
base.Parent = value;
}
}
public Guid Guid
{
get
{
return m_Guid;
}
set
{
m_Guid = value;
}
}
/// <summary>
/// Gets or sets the active config.
/// </summary>
/// <value>The active config.</value>
public string ActiveConfig
{
get
{
return m_ActiveConfig;
}
set
{
m_ActiveConfig = value;
}
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name
{
get
{
return m_Name;
}
}
/// <summary>
/// Gets the path.
/// </summary>
/// <value>The path.</value>
public string Path
{
get
{
return m_Path;
}
}
/// <summary>
/// Gets the full path.
/// </summary>
/// <value>The full path.</value>
public string FullPath
{
get
{
return m_FullPath;
}
}
/// <summary>
/// Gets the options.
/// </summary>
/// <value>The options.</value>
public OptionsNode Options
{
get
{
return m_Options;
}
}
/// <summary>
/// Gets the files.
/// </summary>
/// <value>The files.</value>
public FilesNode Files
{
get
{
return m_Files;
}
}
/// <summary>
/// Gets the configurations.
/// </summary>
/// <value>The configurations.</value>
public ICollection Configurations
{
get
{
return m_Configurations.Values;
}
}
/// <summary>
/// Gets the configurations table.
/// </summary>
/// <value>The configurations table.</value>
public Hashtable ConfigurationsTable
{
get
{
return m_Configurations;
}
}
/// <summary>
/// Gets the database projects.
/// </summary>
public ICollection DatabaseProjects
{
get
{
return m_DatabaseProjects.Values;
}
}
/// <summary>
/// Gets the nested solutions.
/// </summary>
public ICollection Solutions
{
get
{
return m_Solutions.Values;
}
}
/// <summary>
/// Gets the nested solutions hash table.
/// </summary>
public Hashtable SolutionsTable
{
get
{
return this.m_Solutions;
}
}
/// <summary>
/// Gets the projects.
/// </summary>
/// <value>The projects.</value>
public ICollection Projects
{
get
{
return m_Projects.Values;
}
}
/// <summary>
/// Gets the projects table.
/// </summary>
/// <value>The projects table.</value>
public Hashtable ProjectsTable
{
get
{
return m_Projects;
}
}
/// <summary>
/// Gets the projects table.
/// </summary>
/// <value>The projects table.</value>
public ArrayList ProjectsTableOrder
{
get
{
return m_ProjectsOrder;
}
}
#endregion
#region Public Methods
/// <summary>
/// Parses the specified node.
/// </summary>
/// <param name="node">The node.</param>
public override void Parse(XmlNode node)
{
m_Name = Helper.AttributeValue(node, "name", m_Name);
m_ActiveConfig = Helper.AttributeValue(node, "activeConfig", m_ActiveConfig);
m_Path = Helper.AttributeValue(node, "path", m_Path);
m_FullPath = m_Path;
try
{
m_FullPath = Helper.ResolvePath(m_FullPath);
}
catch
{
throw new WarningException("Could not resolve solution path: {0}", m_Path);
}
Kernel.Instance.CurrentWorkingDirectory.Push();
try
{
Helper.SetCurrentDir(m_FullPath);
if( node == null )
{
throw new ArgumentNullException("node");
}
foreach(XmlNode child in node.ChildNodes)
{
IDataNode dataNode = Kernel.Instance.ParseNode(child, this);
if(dataNode is OptionsNode)
{
m_Options = (OptionsNode)dataNode;
}
else if(dataNode is FilesNode)
{
m_Files = (FilesNode)dataNode;
}
else if(dataNode is ConfigurationNode)
{
m_Configurations[((ConfigurationNode)dataNode).Name] = dataNode;
}
else if(dataNode is ProjectNode)
{
m_Projects[((ProjectNode)dataNode).Name] = dataNode;
m_ProjectsOrder.Add(dataNode);
}
else if(dataNode is SolutionNode)
{
m_Solutions[((SolutionNode)dataNode).Name] = dataNode;
}
else if (dataNode is ProcessNode)
{
ProcessNode p = (ProcessNode)dataNode;
Kernel.Instance.ProcessFile(p, this);
}
else if (dataNode is DatabaseProjectNode)
{
m_DatabaseProjects[((DatabaseProjectNode)dataNode).Name] = dataNode;
}
}
}
finally
{
Kernel.Instance.CurrentWorkingDirectory.Pop();
}
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using log4net;
using Mono.Data.SqliteClient;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Data.SQLite
{
public class SQLiteGenericTableHandler<T> : SQLiteFramework where T: class, new()
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected Dictionary<string, FieldInfo> m_Fields =
new Dictionary<string, FieldInfo>();
protected List<string> m_ColumnNames = null;
protected string m_Realm;
protected FieldInfo m_DataField = null;
public SQLiteGenericTableHandler(string connectionString,
string realm, string storeName) : base(connectionString)
{
m_Realm = realm;
if (storeName != String.Empty)
{
Assembly assem = GetType().Assembly;
Migration m = new Migration(m_Connection, assem, storeName);
m.Update();
}
Type t = typeof(T);
FieldInfo[] fields = t.GetFields(BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
if (fields.Length == 0)
return;
foreach (FieldInfo f in fields)
{
if (f.Name != "Data")
m_Fields[f.Name] = f;
else
m_DataField = f;
}
}
private void CheckColumnNames(IDataReader reader)
{
if (m_ColumnNames != null)
return;
m_ColumnNames = new List<string>();
DataTable schemaTable = reader.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
{
if (row["ColumnName"] != null &&
(!m_Fields.ContainsKey(row["ColumnName"].ToString())))
m_ColumnNames.Add(row["ColumnName"].ToString());
}
}
public T[] Get(string field, string key)
{
return Get(new string[] { field }, new string[] { key });
}
public T[] Get(string[] fields, string[] keys)
{
if (fields.Length != keys.Length)
return new T[0];
List<string> terms = new List<string>();
SqliteCommand cmd = new SqliteCommand();
for (int i = 0 ; i < fields.Length ; i++)
{
cmd.Parameters.Add(new SqliteParameter(":" + fields[i], keys[i]));
terms.Add("`" + fields[i] + "` = :" + fields[i]);
}
string where = String.Join(" and ", terms.ToArray());
string query = String.Format("select * from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
return DoQuery(cmd);
}
protected T[] DoQuery(SqliteCommand cmd)
{
IDataReader reader = ExecuteReader(cmd);
if (reader == null)
return new T[0];
CheckColumnNames(reader);
List<T> result = new List<T>();
while (reader.Read())
{
T row = new T();
foreach (string name in m_Fields.Keys)
{
if (m_Fields[name].GetValue(row) is bool)
{
int v = Convert.ToInt32(reader[name]);
m_Fields[name].SetValue(row, v != 0 ? true : false);
}
else if (m_Fields[name].GetValue(row) is UUID)
{
UUID uuid = UUID.Zero;
UUID.TryParse(reader[name].ToString(), out uuid);
m_Fields[name].SetValue(row, uuid);
}
else if (m_Fields[name].GetValue(row) is int)
{
int v = Convert.ToInt32(reader[name]);
m_Fields[name].SetValue(row, v);
}
else
{
m_Fields[name].SetValue(row, reader[name]);
}
}
if (m_DataField != null)
{
Dictionary<string, string> data =
new Dictionary<string, string>();
foreach (string col in m_ColumnNames)
{
data[col] = reader[col].ToString();
if (data[col] == null)
data[col] = String.Empty;
}
m_DataField.SetValue(row, data);
}
result.Add(row);
}
CloseReaderCommand(cmd);
return result.ToArray();
}
public T[] Get(string where)
{
SqliteCommand cmd = new SqliteCommand();
string query = String.Format("select * from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
return DoQuery(cmd);
}
public bool Store(T row)
{
SqliteCommand cmd = new SqliteCommand();
string query = "";
List<String> names = new List<String>();
List<String> values = new List<String>();
foreach (FieldInfo fi in m_Fields.Values)
{
names.Add(fi.Name);
values.Add(":" + fi.Name);
cmd.Parameters.Add(new SqliteParameter(":" + fi.Name, fi.GetValue(row).ToString()));
}
if (m_DataField != null)
{
Dictionary<string, string> data =
(Dictionary<string, string>)m_DataField.GetValue(row);
foreach (KeyValuePair<string, string> kvp in data)
{
names.Add(kvp.Key);
values.Add(":" + kvp.Key);
cmd.Parameters.Add(new SqliteParameter(":" + kvp.Key, kvp.Value));
}
}
query = String.Format("replace into {0} (`", m_Realm) + String.Join("`,`", names.ToArray()) + "`) values (" + String.Join(",", values.ToArray()) + ")";
cmd.CommandText = query;
if (ExecuteNonQuery(cmd) > 0)
return true;
return false;
}
public bool Delete(string field, string val)
{
SqliteCommand cmd = new SqliteCommand();
cmd.CommandText = String.Format("delete from {0} where `{1}` = :{1}", m_Realm, field);
cmd.Parameters.Add(new SqliteParameter(field, val));
if (ExecuteNonQuery(cmd) > 0)
return true;
return false;
}
}
}
| |
/// <summary>
/// <para>Describes the possible UBER action values</para>
/// <para><a href="https://rawgit.com/mamund/media-types/master/uber-hypermedia.html#_reserved_strings">Format documentation</a></para>
/// </summary>
public enum UberActions
{
NotSet,
Append,
Partial,
Read,
Remove,
Replace
}
/// <summary>
/// <para>Describes the possible UBER transclude values</para>
/// <para><a href="https://rawgit.com/mamund/media-types/master/uber-hypermedia.html#_reserved_strings">Format documentation</a></para>
/// </summary>
public enum UberTransclusion
{
NotSet,
False,
True
}
/// <summary>
/// <para>Describes the UBER data element and supports conversion to XML and JSON strings.</para>
/// <para><a href="https://rawgit.com/mamund/media-types/master/uber-hypermedia.html#_the_tt_lt_data_gt_tt_element">Format documentation</a></para>
/// </summary>
public sealed class UberData
{
#region Backing Fields
private object _value;
#endregion //***** Backing Fields
#region Properties
/// <summary>
/// <para>The document-wide unique identifier for this element.</para>
/// <para><a href="https://rawgit.com/mamund/media-types/master/uber-hypermedia.html#_properties">Format documentation</a></para>
/// </summary>
public string Id { get; set; }
/// <summary>
/// <para>A document-wide non-unique identifer for this element.</para>
/// <para><a href="https://rawgit.com/mamund/media-types/master/uber-hypermedia.html#_properties">Format documentation</a></para>
/// </summary>
public string Name { get; set; }
/// <summary>
/// <para>Contains one or more link relation values.</para>
/// <para><a href="https://rawgit.com/mamund/media-types/master/uber-hypermedia.html#_properties">Format documentation</a></para>
/// </summary>
public string Rel { get; set; }
/// <summary>
/// <para>A resolvable URL associated with this element.</para>
/// <para><a href="https://rawgit.com/mamund/media-types/master/uber-hypermedia.html#_properties">Format documentation</a></para>
/// </summary>
public Uri Url { get; set; }
/// <summary>
/// <para>The network request verb associated with this element.</para>
/// <para><a href="https://rawgit.com/mamund/media-types/master/uber-hypermedia.html#_properties">Format documentation</a></para>
/// </summary>
public UberActions Action { get; set; }
/// <summary>
/// <para>Indicates whether the content that is returned from the URL should be embedded within the currently loaded document.</para>
/// <para><a href="https://rawgit.com/mamund/media-types/master/uber-hypermedia.html#_properties">Format documentation</a></para>
/// </summary>
public UberTransclusion Transclude { get; set; }
/// <summary>
/// <para>Contains a template to be used to construct URL query strings or request bodies depending on the value in the action property.</para>
/// <para><a href="https://rawgit.com/mamund/media-types/master/uber-hypermedia.html#_properties">Format documentation</a></para>
/// </summary>
public string Model { get; set; }
/// <summary>
/// <para>Contains one or more media type identifiers for use when sending request bodies.</para>
/// <para><a href="https://rawgit.com/mamund/media-types/master/uber-hypermedia.html#_properties">Format documentation</a></para>
/// </summary>
public string Sending { get; set; }
/// <summary>
/// <para>Contains one or more media type identifiers to expect when receiving request bodies.</para>
/// <para><a href="https://rawgit.com/mamund/media-types/master/uber-hypermedia.html#_properties">Format documentation</a></para>
/// </summary>
public string Accepting { get; set; }
/// <summary>
/// <para>In the XML variant of the UBER mesage format, inner text of the <data> element contains the value associated with that element. In the JSON variant there is a value property that contains the associated value. </para>
/// <para><a href="https://rawgit.com/mamund/media-types/master/uber-hypermedia.html#_properties">Format documentation</a></para>
/// </summary>
public object Value
{
get { return _value; }
set
{
//***** Test for null;
if (value == null)
{
_value = value;
return;
}
//*****
var valueAsString = value.ToString();
//***** Test for number;
double testNumber;
if (double.TryParse(valueAsString, out testNumber))
{
_value = value;
return;
}
//***** Test for bool (false/true);
bool testBool;
if (bool.TryParse(valueAsString, out testBool))
{
_value = value;
return;
}
//***** Test for string;
if (value is string)
{
_value = value;
return;
}
//***** Unknown type (TODO:Throw exception or use validation?)
_value = null;
}
}
public UberList Data;
#endregion //***** Properties
#region Constructors
public UberData()
{
Action = UberActions.NotSet;
Transclude = UberTransclusion.NotSet;
Data = new UberList();
}
#endregion //***** Constructors
#region Methods
private static string ToXmlAttribute(string name, object value)
{
if (value == null || string.IsNullOrWhiteSpace(value.ToString())) return string.Empty;
return string.Format(" {0}=\"{1}\"", name, value);
}
private static string ToJsonAttribute(string name, object value, bool first, bool array = false)
{
return string.Format("{2} \"{0}\" : {1}", name, (array ? value : string.Format("\"{0}\"", value)), first ? string.Empty : ",");
}
public string ToXmlString()
{
//*****
if (Value != null && Data.Count > 0)
throw new Exception("Value and sub-Data can't both be set for a Data element?");
//***** Begin element with attributes;
var xml = new StringBuilder();
xml.Append("<data");
if (!string.IsNullOrWhiteSpace(Id)) xml.Append(ToXmlAttribute("id", Id));
if (!string.IsNullOrWhiteSpace(Name)) xml.Append(ToXmlAttribute("name", Name));
if (!string.IsNullOrWhiteSpace(Rel)) xml.Append(ToXmlAttribute("rel", Rel));
if (Url != null && !string.IsNullOrWhiteSpace(Url.ToString())) xml.Append(ToXmlAttribute("url", Url.ToString()));
if (Action != UberActions.NotSet) xml.Append(ToXmlAttribute("action", Action.ToString().ToLower()));
if (Transclude != UberTransclusion.NotSet) xml.Append(ToXmlAttribute("transclude", Transclude.ToString().ToLower()));
if (!string.IsNullOrWhiteSpace(Model)) xml.Append(ToXmlAttribute("model", Model));
if (!string.IsNullOrWhiteSpace(Sending)) xml.Append(ToXmlAttribute("sending", Sending));
if (!string.IsNullOrWhiteSpace(Accepting)) xml.Append(ToXmlAttribute("accepting", Accepting));
//***** No Value and Data;
if (Value == null && Data.Count == 0)
{
//***** Close element;
xml.Append(" />");
return xml.ToString();
}
//***** Value;
if (Value != null)
{
//***** Close element with value;
xml.AppendFormat(">{0}</data>", Value);
return xml.ToString();
}
//***** Close element with data elements;
xml.AppendFormat(">{0}</data>", Data.ToXmlString());
return xml.ToString();
}
public string ToJsonString()
{
//*****
if (Value != null && Data.Count > 0)
throw new Exception("Value and sub-Data can't both be set for a Data element?");
//***** Begin object;
var json = new StringBuilder();
json.Append("{");
//***** Add properties;
var first = true;
if (!string.IsNullOrWhiteSpace(Id)) { json.Append(ToJsonAttribute("id", Id, first)); first = false; }
if (!string.IsNullOrWhiteSpace(Name)) { json.Append(ToJsonAttribute("name", Name, first)); first = false; }
if (!string.IsNullOrWhiteSpace(Rel)) { json.Append(ToJsonAttribute("rel", string.Format("[\"{0}\"], string.Join("\", \"", Rel.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries))), first, true)); first = false; }
if (Url != null && !string.IsNullOrWhiteSpace(Url.ToString())) { json.Append(ToJsonAttribute("url", Url.ToString(), first)); first = false; }
if (Action != UberActions.NotSet) { json.Append(ToJsonAttribute("action", Action.ToString().ToLower(), first)); first = false; }
if (Transclude != UberTransclusion.NotSet) { json.Append(ToJsonAttribute("transclude", Transclude.ToString().ToLower(), first)); first = false; }
if (!string.IsNullOrWhiteSpace(Model)) { json.Append(ToJsonAttribute("model", Model, first)); first = false; }
if (!string.IsNullOrWhiteSpace(Sending)) { json.Append(ToJsonAttribute("sending", Sending, first)); first = false; }
if (!string.IsNullOrWhiteSpace(Accepting)) { json.Append(ToJsonAttribute("accepting", Accepting, first)); first = false; }
//***** Close object, no Value and Data;
if (Value == null && Data.Count == 0)
{
//***** Close object;
json.Append("}");
return json.ToString();
}
//***** Close object with value attribute;
if (Value != null)
{
//***** Add value attribute;
json.Append(ToJsonAttribute("value", Value, first));
//***** Close object;
json.Append("}");
return json.ToString();
}
//***** Close object with data objects;
json.Append(ToJsonAttribute("data", Data.ToJsonString(), first, true));
//***** Close object;
json.Append("}");
return json.ToString();
}
#endregion //***** Methods
}
/// <summary>
/// UberData list as a specialized list for converting to XML and JSON strings.
/// </summary>
public sealed class UberList : List<UberData>
{
#region Methods
public string ToXmlString()
{
var xml = new StringBuilder();
foreach (var item in this)
xml.Append(item.ToXmlString());
return xml.ToString();
}
public string ToJsonString()
{
var json = new StringBuilder();
json.Append("[");
var first = true;
foreach (var item in this)
{
json.AppendFormat("{1} {0}", item.ToJsonString(), first ? string.Empty : ",");
first = false;
}
json.Append("]");
return json.ToString();
}
#endregion //***** Methods
}
/// <summary>
/// <para>Describes an UBER message.</para>
/// <para><a href="https://rawgit.com/mamund/media-types/master/uber-hypermedia.html">Format documentation</a></para>
/// </summary>
public sealed class UberBuilder
{
#region Properties
/// <summary>
/// <para>The main element in UBER messages.</para>
/// <para><a href="https://rawgit.com/mamund/media-types/master/uber-hypermedia.html#_the_tt_lt_data_gt_tt_element">Format documentation</a></para>
/// </summary>
public UberList Data;
/// <summary>
/// <para>The element that carries error details from the previous request.</para>
/// <para><a href="https://rawgit.com/mamund/media-types/master/uber-hypermedia.html#_the_tt_lt_error_gt_tt_element">Format documentation</a></para>
/// </summary>
public UberList Error;
#endregion //***** Properties
#region Constructors
public UberBuilder()
{
Data = new UberList();
Error = new UberList();
}
#endregion //***** Constructors
#region Methods
/// <summary>
/// <para>Outputs a XML representation of the UBER message.</para>
/// <para><a href="https://rawgit.com/mamund/media-types/master/uber-hypermedia.html#_xml_example">Example</a></para>
/// </summary>
/// <returns>XML as string</returns>
public string ToXmlString()
{
//***** Begin UBER element;
var xml = new StringBuilder();
xml.Append("<uber version=\"1.0\">");
//***** Append data;
xml.Append(Data.ToXmlString());
//***** If available, add error data;
if (Error.Count > 0)
xml.AppendFormat("<error>{0}</error>", Error.ToXmlString());
//***** Close UBER element;
xml.Append("</uber>");
return xml.ToString();
}
/// <summary>
/// <para>Outputs a JSON representation of the UBER message.</para>
/// <para><a href="https://rawgit.com/mamund/media-types/master/uber-hypermedia.html#_json_example">Example</a></para>
/// </summary>
/// <returns>JSON as string</returns>
public string ToJsonString()
{
//***** Open UBER object;
var json = new StringBuilder();
json.Append("{ \"uber\" : {");
//***** Add version attribute;
json.Append(" \"version\" : \"1.0\"");
//***** If available, add data;
if (Data.Count > 0)
json.AppendFormat(", \"data\" : {0}", Data.ToJsonString());
//***** If available, add error data;
if (Error.Count > 0)
json.AppendFormat(", \"error\" : {0}", Error.ToJsonString());
//***** Close UBER object;
json.Append("} }");
return json.ToString();
}
#endregion //***** Methods
}
| |
using System;
using System.Collections.Generic;
using Avalonia.Collections;
namespace Avalonia.Controls
{
/// <summary>
/// Holds a collection of style classes for an <see cref="IStyledElement"/>.
/// </summary>
/// <remarks>
/// Similar to CSS, each control may have any number of styling classes applied.
/// </remarks>
public class Classes : AvaloniaList<string>, IPseudoClasses
{
/// <summary>
/// Initializes a new instance of the <see cref="Classes"/> class.
/// </summary>
public Classes()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Classes"/> class.
/// </summary>
/// <param name="items">The initial items.</param>
public Classes(IEnumerable<string> items)
: base(items)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Classes"/> class.
/// </summary>
/// <param name="items">The initial items.</param>
public Classes(params string[] items)
: base(items)
{
}
/// <summary>
/// Parses a classes string.
/// </summary>
/// <param name="s">The string.</param>
/// <returns>The <see cref="Classes"/>.</returns>
public static Classes Parse(string s) => new Classes(s.Split(' '));
/// <summary>
/// Adds a style class to the collection.
/// </summary>
/// <param name="name">The class name.</param>
/// <remarks>
/// Only standard classes may be added via this method. To add pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="StyledElement.PseudoClasses"/>
/// property.
/// </remarks>
public override void Add(string name)
{
ThrowIfPseudoclass(name, "added");
if (!Contains(name))
{
base.Add(name);
}
}
/// <summary>
/// Adds a style classes to the collection.
/// </summary>
/// <param name="names">The class names.</param>
/// <remarks>
/// Only standard classes may be added via this method. To add pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="StyledElement.PseudoClasses"/>
/// property.
/// </remarks>
public override void AddRange(IEnumerable<string> names)
{
var c = new List<string>();
foreach (var name in names)
{
ThrowIfPseudoclass(name, "added");
if (!Contains(name))
{
c.Add(name);
}
}
base.AddRange(c);
}
/// <summary>
/// Remvoes all non-pseudoclasses from the collection.
/// </summary>
public override void Clear()
{
for (var i = Count - 1; i >= 0; --i)
{
if (!this[i].StartsWith(":"))
{
RemoveAt(i);
}
}
}
/// <summary>
/// Inserts a style class into the collection.
/// </summary>
/// <param name="index">The index to insert the class at.</param>
/// <param name="name">The class name.</param>
/// <remarks>
/// Only standard classes may be added via this method. To add pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="StyledElement.PseudoClasses"/>
/// property.
/// </remarks>
public override void Insert(int index, string name)
{
ThrowIfPseudoclass(name, "added");
if (!Contains(name))
{
base.Insert(index, name);
}
}
/// <summary>
/// Inserts style classes into the collection.
/// </summary>
/// <param name="index">The index to insert the class at.</param>
/// <param name="names">The class names.</param>
/// <remarks>
/// Only standard classes may be added via this method. To add pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="StyledElement.PseudoClasses"/>
/// property.
/// </remarks>
public override void InsertRange(int index, IEnumerable<string> names)
{
var c = new List<string>();
foreach (var name in names)
{
ThrowIfPseudoclass(name, "added");
if (!Contains(name))
{
c.Add(name);
}
}
base.InsertRange(index, c);
}
/// <summary>
/// Removes a style class from the collection.
/// </summary>
/// <param name="name">The class name.</param>
/// <remarks>
/// Only standard classes may be removed via this method. To remove pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="StyledElement.PseudoClasses"/>
/// property.
/// </remarks>
public override bool Remove(string name)
{
ThrowIfPseudoclass(name, "removed");
return base.Remove(name);
}
/// <summary>
/// Removes style classes from the collection.
/// </summary>
/// <param name="names">The class name.</param>
/// <remarks>
/// Only standard classes may be removed via this method. To remove pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="StyledElement.PseudoClasses"/>
/// property.
/// </remarks>
public override void RemoveAll(IEnumerable<string> names)
{
var c = new List<string>();
foreach (var name in names)
{
ThrowIfPseudoclass(name, "removed");
if (Contains(name))
{
c.Add(name);
}
}
base.RemoveAll(c);
}
/// <summary>
/// Removes a style class from the collection.
/// </summary>
/// <param name="index">The index of the class in the collection.</param>
/// <remarks>
/// Only standard classes may be removed via this method. To remove pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="StyledElement.PseudoClasses"/>
/// property.
/// </remarks>
public override void RemoveAt(int index)
{
var name = this[index];
ThrowIfPseudoclass(name, "removed");
base.RemoveAt(index);
}
/// <summary>
/// Removes style classes from the collection.
/// </summary>
/// <param name="index">The first index to remove.</param>
/// <param name="count">The number of items to remove.</param>
public override void RemoveRange(int index, int count)
{
base.RemoveRange(index, count);
}
/// <summary>
/// Removes all non-pseudoclasses in the collection and adds a new set.
/// </summary>
/// <param name="source">The new contents of the collection.</param>
public void Replace(IList<string> source)
{
var toRemove = new List<string>();
foreach (var name in source)
{
ThrowIfPseudoclass(name, "added");
}
foreach (var name in this)
{
if (!name.StartsWith(":"))
{
toRemove.Add(name);
}
}
base.RemoveAll(toRemove);
base.AddRange(source);
}
/// <inheritdoc/>
void IPseudoClasses.Add(string name)
{
if (!Contains(name))
{
base.Add(name);
}
}
/// <inheritdoc/>
bool IPseudoClasses.Remove(string name)
{
return base.Remove(name);
}
private void ThrowIfPseudoclass(string name, string operation)
{
if (name.StartsWith(":"))
{
throw new ArgumentException(
$"The pseudoclass '{name}' may only be {operation} by the control itself.");
}
}
}
}
| |
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Versioning;
using System.Threading.Tasks;
// ReSharper disable AssignNullToNotNullAttribute
namespace Thinktecture.Net.Sockets.Adapters
{
/// <summary>
/// Provides User Datagram Protocol (UDP) network services.
/// </summary>
public class UdpClientAdapter : AbstractionAdapter<UdpClient>, IUdpClient
{
/// <inheritdoc />
public int Available => Implementation.Available;
/// <inheritdoc />
public ISocket Client
{
get => Implementation.Client.ToInterface();
set => Implementation.Client = value.ToImplementation();
}
/// <inheritdoc />
public bool DontFragment
{
get => Implementation.DontFragment;
set => Implementation.DontFragment = value;
}
/// <inheritdoc />
public bool EnableBroadcast
{
get => Implementation.EnableBroadcast;
set => Implementation.EnableBroadcast = value;
}
/// <inheritdoc />
public bool ExclusiveAddressUse
{
get => Implementation.ExclusiveAddressUse;
set => Implementation.ExclusiveAddressUse = value;
}
/// <inheritdoc />
public bool MulticastLoopback
{
get => Implementation.MulticastLoopback;
set => Implementation.MulticastLoopback = value;
}
/// <inheritdoc />
public short Ttl
{
get => Implementation.Ttl;
set => Implementation.Ttl = value;
}
/// <summary>
/// Initializes a new instance of the UdpClient class.
/// </summary>
public UdpClientAdapter()
: this(new UdpClient())
{
}
/// <summary>
/// Initializes a new instance of the UdpClient class.
/// </summary>
/// <param name="hostname"></param>
/// <param name="port"></param>
public UdpClientAdapter(string hostname, int port)
: this(new UdpClient(hostname, port))
{
}
/// <summary>
/// Initializes a new instance of the UdpClient class and binds it to the local port number provided.
/// </summary>
/// <param name="port">The local port number from which you intend to communicate.</param>
public UdpClientAdapter(int port)
: this(new UdpClient(port))
{
}
/// <summary>
/// Initializes a new instance of the UdpClient class and binds it to the local port number provided.
/// </summary>
/// <param name="port">The port on which to listen for incoming connection attempts.</param>
/// <param name="family">One of the AddressFamily values that specifies the addressing scheme of the socket.</param>
public UdpClientAdapter(int port, AddressFamily family)
: this(new UdpClient(port, family))
{
}
/// <summary>
/// Initializes a new instance of the UdpClient class and binds it to the specified local endpoint.
/// </summary>
/// <param name="localEP">An IPEndPoint that respresents the local endpoint to which you bind the UDP connection.</param>
// ReSharper disable once InconsistentNaming
public UdpClientAdapter(IPEndPoint localEP)
: this(new UdpClient(localEP))
{
}
/// <summary>
/// Initializes a new instance of the UdpClient class and binds it to the specified local endpoint.
/// </summary>
/// <param name="localEP">An IPEndPoint that respresents the local endpoint to which you bind the UDP connection.</param>
// ReSharper disable once InconsistentNaming
public UdpClientAdapter(IIPEndPoint localEP)
: this(localEP.ToImplementation<IPEndPoint>())
{
}
/// <summary>
/// Initializes a new instance of the UdpClient class.
/// </summary>
/// <param name="family">One of the AddressFamily values that specifies the addressing scheme of the socket.</param>
public UdpClientAdapter(AddressFamily family)
: this(new UdpClient(family))
{
}
/// <summary>
/// Intializes new instance of <see cref="UdpClientAdapter"/>.
/// </summary>
/// <param name="client">Client to be used by the adapter.</param>
public UdpClientAdapter(UdpClient client)
: base(client)
{
}
/// <inheritdoc />
public void DropMulticastGroup(IPAddress multicastAddr)
{
Implementation.DropMulticastGroup(multicastAddr);
}
/// <inheritdoc />
public void DropMulticastGroup(IIPAddress multicastAddr)
{
Implementation.DropMulticastGroup(multicastAddr.ToImplementation());
}
/// <inheritdoc />
public void DropMulticastGroup(IPAddress multicastAddr, int ifindex)
{
Implementation.DropMulticastGroup(multicastAddr, ifindex);
}
/// <inheritdoc />
public void DropMulticastGroup(IIPAddress multicastAddr, int ifindex)
{
Implementation.DropMulticastGroup(multicastAddr.ToImplementation(), ifindex);
}
/// <inheritdoc />
public void JoinMulticastGroup(int ifindex, IPAddress multicastAddr)
{
Implementation.JoinMulticastGroup(ifindex, multicastAddr);
}
/// <inheritdoc />
public void JoinMulticastGroup(int ifindex, IIPAddress multicastAddr)
{
Implementation.JoinMulticastGroup(ifindex, multicastAddr.ToImplementation());
}
/// <inheritdoc />
public void JoinMulticastGroup(IPAddress multicastAddr)
{
Implementation.JoinMulticastGroup(multicastAddr);
}
/// <inheritdoc />
public void JoinMulticastGroup(IIPAddress multicastAddr)
{
Implementation.JoinMulticastGroup(multicastAddr.ToImplementation());
}
/// <inheritdoc />
public void JoinMulticastGroup(IPAddress multicastAddr, int timeToLive)
{
Implementation.JoinMulticastGroup(multicastAddr, timeToLive);
}
/// <inheritdoc />
public void JoinMulticastGroup(IIPAddress multicastAddr, int timeToLive)
{
Implementation.JoinMulticastGroup(multicastAddr.ToImplementation(), timeToLive);
}
/// <inheritdoc />
public void JoinMulticastGroup(IPAddress multicastAddr, IPAddress localAddress)
{
Implementation.JoinMulticastGroup(multicastAddr, localAddress);
}
/// <inheritdoc />
public void JoinMulticastGroup(IIPAddress multicastAddr, IPAddress localAddress)
{
Implementation.JoinMulticastGroup(multicastAddr.ToImplementation(), localAddress);
}
/// <inheritdoc />
public void JoinMulticastGroup(IPAddress multicastAddr, IIPAddress localAddress)
{
Implementation.JoinMulticastGroup(multicastAddr, localAddress.ToImplementation());
}
/// <inheritdoc />
public void JoinMulticastGroup(IIPAddress multicastAddr, IIPAddress localAddress)
{
Implementation.JoinMulticastGroup(multicastAddr.ToImplementation(), localAddress.ToImplementation());
}
/// <inheritdoc />
public Task<UdpReceiveResult> ReceiveAsync()
{
return Implementation.ReceiveAsync();
}
/// <inheritdoc />
public Task<int> SendAsync(byte[] datagram, int bytes, IPEndPoint? endPoint)
{
return Implementation.SendAsync(datagram, bytes, endPoint);
}
/// <inheritdoc />
public Task<int> SendAsync(byte[] datagram, int bytes, IIPEndPoint? endPoint)
{
return Implementation.SendAsync(datagram, bytes, endPoint.ToImplementation<IPEndPoint>());
}
/// <inheritdoc />
public Task<int> SendAsync(byte[] datagram, int bytes, string? hostname, int port)
{
return Implementation.SendAsync(datagram, bytes, hostname, port);
}
/// <inheritdoc />
public Task<int> SendAsync(byte[] datagram, int bytes)
{
return Implementation.SendAsync(datagram, bytes);
}
/// <inheritdoc />
#if NET5_0
[SupportedOSPlatform("windows")]
#endif
public void AllowNatTraversal(bool allowed)
{
Implementation.AllowNatTraversal(allowed);
}
/// <inheritdoc />
public void Close()
{
Implementation.Close();
}
/// <inheritdoc />
public void Connect(string hostname, int port)
{
Implementation.Connect(hostname, port);
}
/// <inheritdoc />
public void Connect(IPAddress addr, int port)
{
Implementation.Connect(addr, port);
}
/// <inheritdoc />
public void Connect(IIPAddress addr, int port)
{
Implementation.Connect(addr.ToImplementation(), port);
}
/// <inheritdoc />
public void Connect(IPEndPoint endPoint)
{
Implementation.Connect(endPoint);
}
/// <inheritdoc />
public void Connect(IIPEndPoint endPoint)
{
Implementation.Connect(endPoint.ToImplementation());
}
/// <inheritdoc />
public byte[] Receive(ref IPEndPoint remoteEp)
{
return Implementation.Receive(ref remoteEp);
}
/// <inheritdoc />
public byte[] Receive(ref IIPEndPoint remoteEp)
{
var ep = remoteEp.ToImplementation();
var bytes = Implementation.Receive(ref ep);
remoteEp = ep.ToInterface();
return bytes;
}
/// <inheritdoc />
public int Send(byte[] dgram, int bytes, IPEndPoint endPoint)
{
return Implementation.Send(dgram, bytes, endPoint);
}
/// <inheritdoc />
public int Send(byte[] dgram, int bytes, IIPEndPoint endPoint)
{
return Implementation.Send(dgram, bytes, endPoint.ToImplementation());
}
/// <inheritdoc />
public int Send(byte[] dgram, int bytes, string hostname, int port)
{
return Implementation.Send(dgram, bytes, hostname, port);
}
/// <inheritdoc />
public int Send(byte[] dgram, int bytes)
{
return Implementation.Send(dgram, bytes);
}
/// <inheritdoc />
public void Dispose()
{
((IDisposable)Implementation).Dispose();
}
}
}
| |
// 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.Text;
using System.Reflection;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.CompilerServices;
using System.Reflection.Runtime.TypeInfos;
using System.Reflection.Runtime.Assemblies;
using System.Reflection.Runtime.MethodInfos;
using DefaultBinder = System.Reflection.Runtime.BindingFlagSupport.DefaultBinder;
using IRuntimeImplementedType = Internal.Reflection.Core.NonPortable.IRuntimeImplementedType;
using Internal.LowLevelLinq;
using Internal.Runtime.Augments;
using Internal.Reflection.Core.Execution;
using Internal.Reflection.Core.NonPortable;
using Internal.Reflection.Extensions.NonPortable;
namespace System.Reflection.Runtime.General
{
internal static partial class Helpers
{
// This helper helps reduce the temptation to write "h == default(RuntimeTypeHandle)" which causes boxing.
public static bool IsNull(this RuntimeTypeHandle h)
{
return h.Equals(default(RuntimeTypeHandle));
}
// Clones a Type[] array for the purpose of returning it from an api.
public static Type[] CloneTypeArray(this Type[] types)
{
int count = types.Length;
if (count == 0)
return Array.Empty<Type>(); // Ok not to clone empty arrays - those are immutable.
Type[] clonedTypes = new Type[count];
for (int i = 0; i < count; i++)
{
clonedTypes[i] = types[i];
}
return clonedTypes;
}
public static bool IsRuntimeImplemented(this Type type)
{
return type is IRuntimeImplementedType;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Type[] GetGenericTypeParameters(this Type type)
{
Debug.Assert(type.IsGenericTypeDefinition);
return type.GetGenericArguments();
}
public static RuntimeTypeInfo[] ToRuntimeTypeInfoArray(this Type[] types)
{
int count = types.Length;
RuntimeTypeInfo[] typeInfos = new RuntimeTypeInfo[count];
for (int i = 0; i < count; i++)
{
typeInfos[i] = types[i].CastToRuntimeTypeInfo();
}
return typeInfos;
}
public static string LastResortString(this RuntimeTypeHandle typeHandle)
{
return ReflectionCoreExecution.ExecutionEnvironment.GetLastResortString(typeHandle);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static RuntimeNamedTypeInfo CastToRuntimeNamedTypeInfo(this Type type)
{
Debug.Assert(type is RuntimeNamedTypeInfo);
return (RuntimeNamedTypeInfo)type;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static RuntimeTypeInfo CastToRuntimeTypeInfo(this Type type)
{
Debug.Assert(type == null || type is RuntimeTypeInfo);
return (RuntimeTypeInfo)type;
}
public static ReadOnlyCollection<T> ToReadOnlyCollection<T>(this IEnumerable<T> enumeration)
{
return new ReadOnlyCollection<T>(enumeration.ToArray());
}
public static MethodInfo FilterAccessor(this MethodInfo accessor, bool nonPublic)
{
if (nonPublic)
return accessor;
if (accessor.IsPublic)
return accessor;
return null;
}
public static object ToRawValue(this object defaultValueOrLiteral)
{
Enum e = defaultValueOrLiteral as Enum;
if (e != null)
return RuntimeAugments.GetEnumValue(e);
return defaultValueOrLiteral;
}
public static Type GetTypeCore(this Assembly assembly, string name, bool ignoreCase)
{
RuntimeAssembly runtimeAssembly = assembly as RuntimeAssembly;
if (runtimeAssembly != null)
{
// Not a recursion - this one goes to the actual instance method on RuntimeAssembly.
return runtimeAssembly.GetTypeCore(name, ignoreCase: ignoreCase);
}
else
{
// This is a third-party Assembly object. We can emulate GetTypeCore() by calling the public GetType()
// method. This is wasteful because it'll probably reparse a type string that we've already parsed
// but it can't be helped.
string escapedName = name.EscapeTypeNameIdentifier();
return assembly.GetType(escapedName, throwOnError: false, ignoreCase: ignoreCase);
}
}
public static TypeLoadException CreateTypeLoadException(string typeName, Assembly assemblyIfAny)
{
if (assemblyIfAny == null)
throw new TypeLoadException(SR.Format(SR.TypeLoad_TypeNotFound, typeName));
else
throw Helpers.CreateTypeLoadException(typeName, assemblyIfAny.FullName);
}
public static TypeLoadException CreateTypeLoadException(string typeName, string assemblyName)
{
string message = SR.Format(SR.TypeLoad_TypeNotFoundInAssembly, typeName, assemblyName);
return ReflectionCoreNonPortable.CreateTypeLoadException(message, typeName);
}
// Escape identifiers as described in "Specifying Fully Qualified Type Names" on msdn.
// Current link is http://msdn.microsoft.com/en-us/library/yfsftwz6(v=vs.110).aspx
public static string EscapeTypeNameIdentifier(this string identifier)
{
// Some characters in a type name need to be escaped
if (identifier != null && identifier.IndexOfAny(s_charsToEscape) != -1)
{
StringBuilder sbEscapedName = new StringBuilder(identifier.Length);
foreach (char c in identifier)
{
if (c.NeedsEscapingInTypeName())
sbEscapedName.Append('\\');
sbEscapedName.Append(c);
}
identifier = sbEscapedName.ToString();
}
return identifier;
}
public static bool NeedsEscapingInTypeName(this char c)
{
return Array.IndexOf(s_charsToEscape, c) >= 0;
}
private static readonly char[] s_charsToEscape = new char[] { '\\', '[', ']', '+', '*', '&', ',' };
public static RuntimeMethodInfo GetInvokeMethod(this RuntimeTypeInfo delegateType)
{
Debug.Assert(delegateType.IsDelegate);
MethodInfo invokeMethod = delegateType.GetMethod("Invoke", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
if (invokeMethod == null)
{
// No Invoke method found. Since delegate types are compiler constructed, the most likely cause is missing metadata rather than
// a missing Invoke method.
// We're deliberating calling FullName rather than ToString() because if it's the type that's missing metadata,
// the FullName property constructs a more informative MissingMetadataException than we can.
string fullName = delegateType.FullName;
throw new MissingMetadataException(SR.Format(SR.Arg_InvokeMethodMissingMetadata, fullName)); // No invoke method found.
}
return (RuntimeMethodInfo)invokeMethod;
}
public static BinderBundle ToBinderBundle(this Binder binder, BindingFlags invokeAttr, CultureInfo cultureInfo)
{
if (binder == null || binder is DefaultBinder || ((invokeAttr & BindingFlags.ExactBinding) != 0))
return null;
return new BinderBundle(binder, cultureInfo);
}
// Helper for ICustomAttributeProvider.GetCustomAttributes(). The result of this helper is returned directly to apps
// so it must always return a newly allocated array. Unlike most of the newer custom attribute apis, the attribute type
// need not derive from System.Attribute. (In particular, it can be an interface or System.Object.)
public static object[] InstantiateAsArray(this IEnumerable<CustomAttributeData> cads, Type actualElementType)
{
LowLevelList<object> attributes = new LowLevelList<object>();
foreach (CustomAttributeData cad in cads)
{
object instantiatedAttribute = cad.Instantiate();
attributes.Add(instantiatedAttribute);
}
int count = attributes.Count;
object[] result = (object[])Array.CreateInstance(actualElementType, count);
attributes.CopyTo(result, 0);
return result;
}
}
}
| |
using System;
using System.Text;
using System.Diagnostics;
using System.Reflection;
using System.IO;
using Communication.Interface;
using System.Threading;
using System.Collections.Generic;
namespace Communication.Interface.Implementation
{
[InterfaceImplementation(Name = "Ssh", Scheme = "Ssh", ConfigPanel = typeof(Panel.SshPanel))]
public class PlinkSsh : AbsCommunicationInterface
{
private static string PLINK_PATH = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "plink_mod.exe");
private ProcessStartInfo Plink;
private Process PlinkProcess;
private StreamWriter InputStream;
private StreamReader OutputStream;
private Queue<byte> OutputBuffer;
private object OutputBufferLocker = new Object();
private const int AsyncReadBufferLength = 0x4000;
private byte[] AsyncReadBuffer;
public PlinkSsh(string IpAddress, int Port) : base()
{
OutputBuffer = new Queue<byte>();
PLINK_PATH = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "plink_mod.exe");
if(!File.Exists(PLINK_PATH))
{
PLINK_PATH = "plink_mod.exe";
}
Plink = new ProcessStartInfo()
{
FileName = PLINK_PATH,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
WindowStyle = ProcessWindowStyle.Hidden | ProcessWindowStyle.Minimized,
CreateNoWindow = true
};
Plink.Arguments = String.Format("-ssh {0} -P {1} -x -batch -auto_store_sshkey", Port, IpAddress);
}
public PlinkSsh(string ConfigString, string FriendlyName)
: base(ConfigString, FriendlyName)
{
if (FriendlyName == null || FriendlyName.Equals(string.Empty))
{
friendly_name = Config["IP"];
}
OutputBuffer = new Queue<byte>();
PLINK_PATH = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "plink_mod.exe");
if (!File.Exists(PLINK_PATH))
{
PLINK_PATH = "plink_mod.exe";
}
Plink = new ProcessStartInfo()
{
FileName = PLINK_PATH,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
WindowStyle = ProcessWindowStyle.Hidden | ProcessWindowStyle.Minimized,
CreateNoWindow = true
};
Plink.Arguments = String.Format("-ssh {0} -P {1}", Config["IP"], int.Parse(Config["Port"]));
if (Config.ContainsKey("Key") && !Config["Key"].Equals(string.Empty))
{
Plink.Arguments += String.Format(" -i {0} ", Config["Key"]);
}
if (Config.ContainsKey("Username") && !Config["Username"].Equals(string.Empty))
{
Plink.Arguments += String.Format(" -l {0}", Config["Username"]);
}
if (Config.ContainsKey("Password") && !Config["Password"].Equals(string.Empty))
{
Plink.Arguments += String.Format(" -pw {0} ", Config["Password"]);
}
Plink.Arguments += " -x -batch -auto_store_sshkey";
}
override public bool IsOpened
{
get
{
try
{
return PlinkProcess != null && !PlinkProcess.HasExited && !OutputStream.EndOfStream;
}
catch
{
return false;
}
}
}
override public void Open()
{
if (Plink != null)
{
AsyncReadBuffer = new byte[AsyncReadBufferLength];
PlinkProcess = Process.Start(Plink);
InputStream = PlinkProcess.StandardInput;
OutputStream = PlinkProcess.StandardOutput;
BeginOutputStreamRead();
}
}
override public void Close()
{
if (IsOpened)
{
if (InputStream != null)
{
InputStream.BaseStream.Close();
InputStream = null;
}
if (OutputStream != null)
{
OutputStream.BaseStream.Close();
OutputStream = null;
}
PlinkProcess.Kill();
}
}
override public void Flush()
{
InputStream.Flush();
}
override public int ReadByte()
{
int data = -1;
if (OutputBuffer != null)
{
lock (OutputBufferLocker)
{
if (OutputBuffer.Count > 0)
{
data = OutputBuffer.Dequeue();
}
}
}
return data;
}
override public void Write(byte data)
{
if (InputStream.BaseStream.CanWrite)
{
InputStream.BaseStream.WriteByte(data);
}
}
override public void Write(byte[] data)
{
if (InputStream.BaseStream.CanWrite)
{
if (ByteWriteMode)
{
foreach (byte dataByte in data)
{
Thread.Sleep((int)(ByteWriteInterval * 1000));
InputStream.BaseStream.WriteByte(dataByte);
}
}
else
{
InputStream.Write(Encoding.ASCII.GetString(data, 0, data.Length));
}
}
}
private void BeginOutputStreamRead()
{
OutputStream.BaseStream.BeginRead(AsyncReadBuffer, 0, AsyncReadBuffer.Length, new AsyncCallback(OutputStreamReadCallback), null);
}
private void OutputStreamReadCallback(IAsyncResult result)
{
if (OutputStream != null)
{
int ReadLenght = OutputStream.BaseStream.EndRead(result);
if (ReadLenght > 0)
{
OutputBufferEnqueue(ReadLenght);
BeginOutputStreamRead();
}
else if (ReadLenght < 0)
{
BeginOutputStreamRead();
}
}
}
private void OutputBufferEnqueue(int Length)
{
lock (OutputBufferLocker)
{
for (int i = 0; i < Length; i++)
{
OutputBuffer.Enqueue(AsyncReadBuffer[i]);
}
}
}
}
}
| |
using Orleans;
using Orleans.Runtime;
using Orleans.TestingHost;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.Streams.Core;
using TestExtensions;
using Xunit;
using UnitTests.GrainInterfaces;
using Orleans.TestingHost.Utils;
using UnitTests.Grains.ProgrammaticSubscribe;
namespace Tester.StreamingTests
{
public abstract class ProgrammaticSubcribeTestsRunner
{
private readonly BaseTestClusterFixture fixture;
public const string StreamProviderName = "StreamProvider1";
public const string StreamProviderName2 = "StreamProvider2";
public ProgrammaticSubcribeTestsRunner(BaseTestClusterFixture fixture)
{
this.fixture = fixture;
}
[SkippableFact]
public async Task Programmatic_Subscribe_Provider_WithExplicitPubsub_TryGetStreamSubscrptionManager()
{
var subGrain = this.fixture.HostedCluster.GrainFactory.GetGrain<ISubscribeGrain>(Guid.NewGuid());
Assert.True(await subGrain.CanGetSubscriptionManager(StreamProviderName));
}
[SkippableFact]
public async Task Programmatic_Subscribe_CanUseNullNamespace()
{
var subscriptionManager = new SubscriptionManager(this.fixture.HostedCluster);
var streamId = new FullStreamIdentity(Guid.NewGuid(), null, StreamProviderName);
await subscriptionManager.AddSubscription<IPassive_ConsumerGrain>(streamId,
Guid.NewGuid());
var subscriptions = await subscriptionManager.GetSubscriptions(streamId);
await subscriptionManager.RemoveSubscription(streamId, subscriptions.First().SubscriptionId);
}
[SkippableFact]
public async Task StreamingTests_Consumer_Producer_Subscribe()
{
var subscriptionManager = new SubscriptionManager(this.fixture.HostedCluster);
var streamId = new FullStreamIdentity(Guid.NewGuid(), "EmptySpace", StreamProviderName);
//set up subscription for 10 consumer grains
var subscriptions = await subscriptionManager.SetupStreamingSubscriptionForStream<IPassive_ConsumerGrain>(streamId, 10);
var consumers = subscriptions.Select(sub => this.fixture.HostedCluster.GrainFactory.GetGrain<IPassive_ConsumerGrain>(sub.GrainId)).ToList();
var producer = this.fixture.HostedCluster.GrainFactory.GetGrain<ITypedProducerGrainProducingApple>(Guid.NewGuid());
await producer.BecomeProducer(streamId.Guid, streamId.Namespace, streamId.ProviderName);
await producer.StartPeriodicProducing();
int numProduced = 0;
await TestingUtils.WaitUntilAsync(lastTry => ProducerHasProducedSinceLastCheck(numProduced, producer, lastTry), _timeout);
await producer.StopPeriodicProducing();
var tasks = new List<Task>();
foreach (var consumer in consumers)
{
tasks.Add(TestingUtils.WaitUntilAsync(lastTry => CheckCounters(new List<ITypedProducerGrain> { producer },
consumer, lastTry, this.fixture.Logger), _timeout));
}
await Task.WhenAll(tasks);
//clean up test
tasks.Clear();
tasks = consumers.Select(consumer => consumer.StopConsuming()).ToList();
await Task.WhenAll(tasks);
}
[SkippableFact(Skip= "https://github.com/dotnet/orleans/issues/5635")]
public async Task StreamingTests_Consumer_Producer_UnSubscribe()
{
var subscriptionManager = new SubscriptionManager(this.fixture.HostedCluster);
var streamId = new FullStreamIdentity(Guid.NewGuid(), "EmptySpace", StreamProviderName);
//set up subscription for consumer grains
var subscriptions = await subscriptionManager.SetupStreamingSubscriptionForStream<IPassive_ConsumerGrain>(streamId, 2);
var producer = this.fixture.GrainFactory.GetGrain<ITypedProducerGrainProducingApple>(Guid.NewGuid());
await producer.BecomeProducer(streamId.Guid, streamId.Namespace, streamId.ProviderName);
await producer.StartPeriodicProducing();
int numProduced = 0;
await TestingUtils.WaitUntilAsync(lastTry => ProducerHasProducedSinceLastCheck(numProduced, producer, lastTry), _timeout);
//the subscription to remove
var subscription = subscriptions[0];
// remove subscription
await subscriptionManager.RemoveSubscription(streamId, subscription.SubscriptionId);
var numProducedWhenUnSub = await producer.GetNumberProduced();
var consumerUnSub = this.fixture.GrainFactory.GetGrain<IPassive_ConsumerGrain>(subscription.GrainId);
var consumerNormal = this.fixture.GrainFactory.GetGrain<IPassive_ConsumerGrain>(subscriptions[1].GrainId);
//assert consumer grain's onAdd func got called.
Assert.True((await consumerUnSub.GetCountOfOnAddFuncCalled()) > 0);
await TestingUtils.WaitUntilAsync(lastTry => ProducerHasProducedSinceLastCheck(numProducedWhenUnSub, producer, lastTry), _timeout);
await producer.StopPeriodicProducing();
//wait for consumers to finish consuming
await Task.Delay(TimeSpan.FromMilliseconds(2000));
//assert normal consumer consumed equal to produced
await TestingUtils.WaitUntilAsync(
lastTry =>CheckCounters(new List<ITypedProducerGrain> { producer }, consumerNormal, lastTry, this.fixture.Logger), _timeout);
//asert unsubscribed consumer consumed less than produced
numProduced = await producer.GetNumberProduced();
var numConsumed = await consumerUnSub.GetNumberConsumed();
Assert.True(numConsumed <= numProducedWhenUnSub);
Assert.True(numConsumed < numProduced);
// clean up test
await consumerNormal.StopConsuming();
await consumerUnSub.StopConsuming();
}
[SkippableFact]
public async Task StreamingTests_Consumer_Producer_GetSubscriptions()
{
var subscriptionManager = new SubscriptionManager(this.fixture.HostedCluster);
var streamId = new FullStreamIdentity(Guid.NewGuid(), "EmptySpace", StreamProviderName);
//set up subscriptions
var expectedSubscriptions = await subscriptionManager.SetupStreamingSubscriptionForStream<IPassive_ConsumerGrain>(streamId, 2);
var expectedSubscriptionIds = expectedSubscriptions.Select(sub => sub.SubscriptionId).ToSet();
var subscriptions = await subscriptionManager.GetSubscriptions(streamId);
var subscriptionIds = subscriptions.Select(sub => sub.SubscriptionId).ToSet();
Assert.True(expectedSubscriptionIds.SetEquals(subscriptionIds));
//remove one subscription
await subscriptionManager.RemoveSubscription(streamId, expectedSubscriptions[0].SubscriptionId);
expectedSubscriptions = expectedSubscriptions.GetRange(1, 1);
subscriptions = await subscriptionManager.GetSubscriptions(streamId);
expectedSubscriptionIds = expectedSubscriptions.Select(sub => sub.SubscriptionId).ToSet();
subscriptionIds = subscriptions.Select(sub => sub.SubscriptionId).ToSet();
Assert.True(expectedSubscriptionIds.SetEquals(subscriptionIds));
// clean up tests
}
[SkippableFact]
public async Task StreamingTests_Consumer_Producer_ConsumerUnsubscribeOnAdd()
{
var subscriptionManager = new SubscriptionManager(this.fixture.HostedCluster);
var streamId = new FullStreamIdentity(Guid.NewGuid(), "EmptySpace", StreamProviderName);
//set up subscriptions
await subscriptionManager.SetupStreamingSubscriptionForStream<IJerk_ConsumerGrain>(streamId, 10);
//producer start producing
var producer = this.fixture.GrainFactory.GetGrain<ITypedProducerGrainProducingInt>(Guid.NewGuid());
await producer.BecomeProducer(streamId.Guid, streamId.Namespace, streamId.ProviderName);
await producer.StartPeriodicProducing();
int numProduced = 0;
await TestingUtils.WaitUntilAsync(lastTry => ProducerHasProducedSinceLastCheck(numProduced, producer, lastTry), _timeout);
await producer.StopPeriodicProducing();
//wait for consumers to react
await Task.Delay(TimeSpan.FromMilliseconds(1000));
//get subscription count now, should be all removed/unsubscribed
var subscriptions = await subscriptionManager.GetSubscriptions(streamId);
Assert.True( subscriptions.Count<Orleans.Streams.Core.StreamSubscription>()== 0);
// clean up tests
}
[SkippableFact(Skip="https://github.com/dotnet/orleans/issues/5650")]
public async Task StreamingTests_Consumer_Producer_SubscribeToTwoStream_MessageWithPolymorphism()
{
var subscriptionManager = new SubscriptionManager(this.fixture.HostedCluster);
var streamId = new FullStreamIdentity(Guid.NewGuid(), "EmptySpace", StreamProviderName);
//set up subscription for 10 consumer grains
var subscriptions = await subscriptionManager.SetupStreamingSubscriptionForStream<IPassive_ConsumerGrain>(streamId, 10);
var consumers = subscriptions.Select(sub => this.fixture.GrainFactory.GetGrain<IPassive_ConsumerGrain>(sub.GrainId)).ToList();
var producer = this.fixture.GrainFactory.GetGrain<ITypedProducerGrainProducingApple>(Guid.NewGuid());
await producer.BecomeProducer(streamId.Guid, streamId.Namespace, streamId.ProviderName);
await producer.StartPeriodicProducing();
int numProduced = 0;
await TestingUtils.WaitUntilAsync(lastTry => ProducerHasProducedSinceLastCheck(numProduced, producer, lastTry), _timeout);
// set up the new stream to subscribe, which produce strings
var streamId2 = new FullStreamIdentity(Guid.NewGuid(), "EmptySpace2", StreamProviderName);
var producer2 = this.fixture.GrainFactory.GetGrain<ITypedProducerGrainProducingApple>(Guid.NewGuid());
await producer2.BecomeProducer(streamId2.Guid, streamId2.Namespace, streamId2.ProviderName);
//register the consumer grain to second stream
var tasks = consumers.Select(consumer => subscriptionManager.AddSubscription<IPassive_ConsumerGrain>(streamId2, consumer.GetPrimaryKey())).ToList();
await Task.WhenAll(tasks);
await producer2.StartPeriodicProducing();
await TestingUtils.WaitUntilAsync(lastTry => ProducerHasProducedSinceLastCheck(numProduced, producer2, lastTry), _timeout);
await producer.StopPeriodicProducing();
await producer2.StopPeriodicProducing();
var tasks2 = new List<Task>();
foreach (var consumer in consumers)
{
tasks2.Add(TestingUtils.WaitUntilAsync(lastTry => CheckCounters(new List<ITypedProducerGrain> { producer, producer2 },
consumer, lastTry, this.fixture.Logger), _timeout));
}
await Task.WhenAll(tasks);
//clean up test
tasks2.Clear();
tasks2 = consumers.Select(consumer => consumer.StopConsuming()).ToList();
await Task.WhenAll(tasks2);
}
[SkippableFact]
public async Task StreamingTests_Consumer_Producer_SubscribeToStreamsHandledByDifferentStreamProvider()
{
var subscriptionManager = new SubscriptionManager(this.fixture.HostedCluster);
var streamId = new FullStreamIdentity(Guid.NewGuid(), "EmptySpace", StreamProviderName);
//set up subscription for 10 consumer grains
var subscriptions = await subscriptionManager.SetupStreamingSubscriptionForStream<IPassive_ConsumerGrain>(streamId, 10);
var consumers = subscriptions.Select(sub => this.fixture.GrainFactory.GetGrain<IPassive_ConsumerGrain>(sub.GrainId)).ToList();
var producer = this.fixture.GrainFactory.GetGrain<ITypedProducerGrainProducingApple>(Guid.NewGuid());
await producer.BecomeProducer(streamId.Guid, streamId.Namespace, streamId.ProviderName);
await producer.StartPeriodicProducing();
int numProduced = 0;
await TestingUtils.WaitUntilAsync(lastTry => ProducerHasProducedSinceLastCheck(numProduced, producer, lastTry), _timeout);
// set up the new stream to subscribe, which produce strings
var streamId2 = new FullStreamIdentity(Guid.NewGuid(), "EmptySpace2", StreamProviderName2);
var producer2 = this.fixture.GrainFactory.GetGrain<ITypedProducerGrainProducingApple>(Guid.NewGuid());
await producer2.BecomeProducer(streamId2.Guid, streamId2.Namespace, streamId2.ProviderName);
//register the consumer grain to second stream
var tasks = consumers.Select(consumer => subscriptionManager.AddSubscription<IPassive_ConsumerGrain>(streamId2, consumer.GetPrimaryKey())).ToList();
await Task.WhenAll(tasks);
await producer2.StartPeriodicProducing();
await TestingUtils.WaitUntilAsync(lastTry => ProducerHasProducedSinceLastCheck(numProduced, producer2, lastTry), _timeout);
await producer.StopPeriodicProducing();
await producer2.StopPeriodicProducing();
var tasks2 = new List<Task>();
foreach (var consumer in consumers)
{
tasks2.Add(TestingUtils.WaitUntilAsync(lastTry => CheckCounters(new List<ITypedProducerGrain> { producer, producer2 },
consumer, lastTry, this.fixture.Logger), _timeout));
}
await Task.WhenAll(tasks);
//clean up test
tasks2.Clear();
tasks2 = consumers.Select(consumer => consumer.StopConsuming()).ToList();
await Task.WhenAll(tasks2);
}
//test utilities and statics
private static readonly TimeSpan _timeout = TimeSpan.FromSeconds(30);
public static async Task<bool> ProducerHasProducedSinceLastCheck(int numProducedLastTime, ITypedProducerGrain producer, bool assertIsTrue)
{
var numProduced = await producer.GetNumberProduced();
if (assertIsTrue)
{
throw new OrleansException($"Producer has not produced since last check");
}
else
{
return numProduced > numProducedLastTime;
}
}
public static async Task<bool> CheckCounters(List<ITypedProducerGrain> producers, IPassive_ConsumerGrain consumer, bool assertIsTrue, ILogger logger)
{
int numProduced = 0;
foreach (var p in producers)
{
numProduced += await p.GetNumberProduced();
}
var numConsumed = await consumer.GetNumberConsumed();
logger.Info("CheckCounters: numProduced = {0}, numConsumed = {1}", numProduced, numConsumed);
if (assertIsTrue)
{
Assert.Equal(numProduced, numConsumed);
return true;
}
else
{
return numProduced == numConsumed;
}
}
}
public class SubscriptionManager
{
private IGrainFactory grainFactory;
private IServiceProvider serviceProvider;
private IStreamSubscriptionManager subManager;
public SubscriptionManager(TestCluster cluster)
{
this.grainFactory = cluster.GrainFactory;
this.serviceProvider = cluster.ServiceProvider;
this.subManager = serviceProvider.GetService<IStreamSubscriptionManagerAdmin>().GetStreamSubscriptionManager(StreamSubscriptionManagerType.ExplicitSubscribeOnly);
}
public async Task<List<StreamSubscription>> SetupStreamingSubscriptionForStream<TGrainInterface>(FullStreamIdentity streamIdentity, int grainCount)
where TGrainInterface : IGrainWithGuidKey
{
var subscriptions = new List<StreamSubscription>();
while (grainCount > 0)
{
var grainId = Guid.NewGuid();
var grainRef = this.grainFactory.GetGrain<TGrainInterface>(grainId) as GrainReference;
subscriptions.Add(await subManager.AddSubscription(streamIdentity.ProviderName, streamIdentity, grainRef));
grainCount--;
}
return subscriptions;
}
public async Task<StreamSubscription> AddSubscription<TGrainInterface>(FullStreamIdentity streamId, Guid grainId)
where TGrainInterface : IGrainWithGuidKey
{
var grainRef = this.grainFactory.GetGrain<TGrainInterface>(grainId) as GrainReference;
var sub = await this.subManager
.AddSubscription(streamId.ProviderName, streamId, grainRef);
return sub;
}
public Task<IEnumerable<StreamSubscription>> GetSubscriptions(FullStreamIdentity streamIdentity)
{
return subManager.GetSubscriptions(streamIdentity.ProviderName, streamIdentity);
}
public async Task RemoveSubscription(FullStreamIdentity streamId, Guid subscriptionId)
{
await subManager.RemoveSubscription(streamId.ProviderName, streamId, subscriptionId);
}
}
}
| |
// 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.IO;
using System.Linq;
using System.Xml.Linq;
using CoreXml.Test.XLinq;
using Microsoft.Test.ModuleCore;
namespace XLinqTests
{
public class XAttributeEnumRemove : XLinqTestCase
{
#region Fields
private EventsHelper _eHelper;
private bool _runWithEvents;
#endregion
#region Public Methods and Operators
public override void AddChildren()
{
AddChild(new TestVariation(IdAttrsMultipleDocs) { Attribute = new VariationAttribute("attributes from multiple elements") { Priority = 1 } });
AddChild(new TestVariation(IdAttrs) { Attribute = new VariationAttribute("attributes from multiple documents") { Priority = 1 } });
AddChild(new TestVariation(OneElementNonNS) { Attribute = new VariationAttribute("All non-namespace attributes in one element") { Priority = 1 } });
AddChild(new TestVariation(OneElementNS) { Attribute = new VariationAttribute("All namespace attributes in one element") { Priority = 1 } });
AddChild(new TestVariation(OneElement) { Attribute = new VariationAttribute("All attributes in one element") { Priority = 0 } });
AddChild(new TestVariation(OneDocument) { Attribute = new VariationAttribute("All attributes in one document") { Priority = 1 } });
AddChild(new TestVariation(IdAttrsNulls) { Attribute = new VariationAttribute("All attributes in one document + nulls") { Priority = 1 } });
AddChild(new TestVariation(DuplicateAttributeInside) { Attribute = new VariationAttribute("Duplicate attribute in sequence") { Priority = 3 } });
AddChild(new TestVariation(EmptySequence) { Attribute = new VariationAttribute("Empty sequence") { Priority = 1 } });
}
// From the same element
// - all attributes
// - some attributes
// From different elements - the same document
// From different documents
// Enumerable + nulls
//[Variation(Priority = 1, Desc = "attributes from multiple elements")]
//[Variation(Priority = 3, Desc = "Duplicate attribute in sequence")]
public void DuplicateAttributeInside()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D id='x' datrt='dat'/></A>");
IEnumerable<XAttribute> allAttributes = doc.Root.Attributes().Concat(doc.Root.Attributes());
try
{
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
count = allAttributes.IsEmpty() ? 0 : allAttributes.Count();
}
allAttributes.Remove(); // should throw because of snapshot logic
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
TestLog.Compare(false, "exception expected here");
}
catch (InvalidOperationException)
{
}
}
//[Variation(Priority = 1, Desc = "Empty sequence")]
public void EmptySequence()
{
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D id='x' datrt='dat'/></A>");
IEnumerable<XAttribute> noAttributes = doc.Descendants().Where(x => !x.HasAttributes).Attributes();
TestLog.Compare(noAttributes.IsEmpty(), "should be empty sequence");
var ms1 = new MemoryStream();
doc.Save(new StreamWriter(ms1));
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
}
noAttributes.Remove();
if (_runWithEvents)
{
_eHelper.Verify(0);
}
var ms2 = new MemoryStream();
doc.Save(new StreamWriter(ms2));
TestLog.Compare(ms1.ToArray().SequenceEqual(ms2.ToArray()), "Documents different");
}
public void IdAttrs()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D id='x' datrt='dat'/></A>");
XElement e = XElement.Parse(@"<X id='z'><Z xmlns='a' id='z'/></X>");
IEnumerable<XAttribute> allAttributes = doc.Descendants().Attributes().Concat(e.Descendants().Attributes()).Where(a => a.Name == "id");
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
count = doc.Descendants().Attributes().Where(a => a.Name == "id").Count();
}
VerifyDeleteAttributes(allAttributes);
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
}
public void IdAttrsMultipleDocs()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D id='x' datrt='dat'/></A>");
IEnumerable<XAttribute> allAttributes = doc.Descendants().Attributes().Where(a => a.Name == "id");
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
count = allAttributes.IsEmpty() ? 0 : allAttributes.Count();
}
VerifyDeleteAttributes(allAttributes);
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
}
public void IdAttrsNulls()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D id='x' datrt='dat'/></A>");
IEnumerable<XAttribute> allAttributes = doc.Descendants().Attributes().Where(a => a.Name == "id").InsertNulls(1);
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
// null attribute will not cause the remove event.
count = allAttributes.IsEmpty() ? 0 : allAttributes.Count() / 2;
}
VerifyDeleteAttributes(allAttributes);
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
}
public void OneDocument()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D datrt='dat'/></A>");
IEnumerable<XAttribute> allAttributes = doc.Descendants().Attributes();
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
count = allAttributes.IsEmpty() ? 0 : allAttributes.Count();
}
VerifyDeleteAttributes(allAttributes);
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
}
public void OneElement()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D datrt='dat'/></A>");
IEnumerable<XAttribute> allAttributes = doc.Root.Element("{nbs}B").Attributes();
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
count = allAttributes.IsEmpty() ? 0 : allAttributes.Count();
}
VerifyDeleteAttributes(allAttributes);
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
}
public void OneElementNS()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D datrt='dat'/></A>");
IEnumerable<XAttribute> allAttributes = doc.Root.Element("{nbs}B").Attributes().Where(a => a.IsNamespaceDeclaration);
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
count = allAttributes.IsEmpty() ? 0 : allAttributes.Count();
}
VerifyDeleteAttributes(allAttributes);
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
VerifyDeleteAttributes(allAttributes);
}
public void OneElementNonNS()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D datrt='dat'/></A>");
IEnumerable<XAttribute> allAttributes = doc.Root.Element("{nbs}B").Attributes().Where(a => !a.IsNamespaceDeclaration);
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
count = allAttributes.IsEmpty() ? 0 : allAttributes.Count();
}
VerifyDeleteAttributes(allAttributes);
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
}
#endregion
#region Methods
private void VerifyDeleteAttributes(IEnumerable<XAttribute> allAttributes)
{
// specify enum + make copy of it
IEnumerable<XAttribute> copyAllAttributes = allAttributes.ToList();
// calculate parents + make copy
IEnumerable<XElement> parents = allAttributes.Select(a => a == null ? null : a.Parent).ToList();
// calculate the expected results for the parents of the processed elements
var expectedAttrsForParent = new Dictionary<XElement, List<ExpectedValue>>();
foreach (XElement p in parents)
{
if (p != null && !expectedAttrsForParent.ContainsKey(p))
{
expectedAttrsForParent.Add(p, p.Attributes().Except(copyAllAttributes.Where(x => x != null)).Select(a => new ExpectedValue(true, a)).ToList());
}
}
// enum.Remove ()
allAttributes.Remove();
// verify properties of the deleted attrs
TestLog.Compare(allAttributes.IsEmpty(), "There should be no attributes left");
IEnumerator<XAttribute> copyAttrib = copyAllAttributes.GetEnumerator();
IEnumerator<XElement> parentsEnum = parents.GetEnumerator();
// verify on parents: deleted elements should not be found
while (copyAttrib.MoveNext() && parentsEnum.MoveNext())
{
XAttribute a = copyAttrib.Current;
if (a != null)
{
XElement parent = parentsEnum.Current;
a.Verify();
parent.Verify();
TestLog.Compare(a.Parent, null, "Parent of deleted");
TestLog.Compare(a.NextAttribute, null, "NextAttribute of deleted");
TestLog.Compare(a.PreviousAttribute, null, "PreviousAttribute of deleted");
if (parent != null)
{
TestLog.Compare(parent.Attribute(a.Name), null, "Attribute lookup");
TestLog.Compare(parent.Attributes().Where(x => x.Name == a.Name).IsEmpty(), "Attributes node");
// Compare the rest of the elements
TestLog.Compare(expectedAttrsForParent[parent].EqualAllAttributes(parent.Attributes(), Helpers.MyAttributeComparer), "The rest of the attributes");
}
}
}
}
#endregion
// Type is CoreXml.Test.XLinq.FunctionalTests+TreeManipulationTests+XAttributeEnumRemove
// Test Case
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Wallet.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/*
* Copyright (c) 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 OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Reflection;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "RemoteGridServicesConnector")]
public class RemoteGridServicesConnector : ISharedRegionModule, IGridService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled = false;
private IGridService m_LocalGridService;
private IGridService m_RemoteGridService;
private RegionInfoCache m_RegionInfoCache = new RegionInfoCache();
public RemoteGridServicesConnector()
{
}
public RemoteGridServicesConnector(IConfigSource source)
{
InitialiseServices(source);
}
#region ISharedRegionmodule
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "RemoteGridServicesConnector"; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("GridServices", "");
if (name == Name)
{
InitialiseServices(source);
m_Enabled = true;
m_log.Info("[REMOTE GRID CONNECTOR]: Remote grid enabled");
}
}
}
private void InitialiseServices(IConfigSource source)
{
IConfig gridConfig = source.Configs["GridService"];
if (gridConfig == null)
{
m_log.Error("[REMOTE GRID CONNECTOR]: GridService missing from OpenSim.ini");
return;
}
string networkConnector = gridConfig.GetString("NetworkConnector", string.Empty);
if (networkConnector == string.Empty)
{
m_log.Error("[REMOTE GRID CONNECTOR]: Please specify a network connector under [GridService]");
return;
}
Object[] args = new Object[] { source };
m_RemoteGridService = ServerUtils.LoadPlugin<IGridService>(networkConnector, args);
m_LocalGridService = new LocalGridServicesConnector(source);
}
public void PostInitialise()
{
if (m_LocalGridService != null)
((ISharedRegionModule)m_LocalGridService).PostInitialise();
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (m_Enabled)
scene.RegisterModuleInterface<IGridService>(this);
if (m_LocalGridService != null)
((ISharedRegionModule)m_LocalGridService).AddRegion(scene);
}
public void RemoveRegion(Scene scene)
{
if (m_LocalGridService != null)
((ISharedRegionModule)m_LocalGridService).RemoveRegion(scene);
}
public void RegionLoaded(Scene scene)
{
}
#endregion
#region IGridService
public string RegisterRegion(UUID scopeID, GridRegion regionInfo)
{
string msg = m_LocalGridService.RegisterRegion(scopeID, regionInfo);
if (msg == String.Empty)
return m_RemoteGridService.RegisterRegion(scopeID, regionInfo);
return msg;
}
public bool DeregisterRegion(UUID regionID)
{
if (m_LocalGridService.DeregisterRegion(regionID))
return m_RemoteGridService.DeregisterRegion(regionID);
return false;
}
public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{
return m_RemoteGridService.GetNeighbours(scopeID, regionID);
}
public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
bool inCache = false;
GridRegion rinfo = m_RegionInfoCache.Get(scopeID,regionID,out inCache);
if (inCache)
return rinfo;
rinfo = m_LocalGridService.GetRegionByUUID(scopeID, regionID);
if (rinfo == null)
rinfo = m_RemoteGridService.GetRegionByUUID(scopeID, regionID);
m_RegionInfoCache.Cache(scopeID,regionID,rinfo);
return rinfo;
}
// Get a region given its base world coordinates (in meters).
// NOTE: this is NOT 'get a region by some point in the region'. The coordinate MUST
// be the base coordinate of the region.
// The coordinates are world coords (meters), NOT region units.
public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
bool inCache = false;
GridRegion rinfo = m_RegionInfoCache.Get(scopeID, Util.RegionWorldLocToHandle((uint)x, (uint)y), out inCache);
if (inCache)
return rinfo;
rinfo = m_LocalGridService.GetRegionByPosition(scopeID, x, y);
if (rinfo == null)
rinfo = m_RemoteGridService.GetRegionByPosition(scopeID, x, y);
m_RegionInfoCache.Cache(rinfo);
return rinfo;
}
public GridRegion GetRegionByName(UUID scopeID, string regionName)
{
bool inCache = false;
GridRegion rinfo = m_RegionInfoCache.Get(scopeID,regionName, out inCache);
if (inCache)
return rinfo;
rinfo = m_LocalGridService.GetRegionByName(scopeID, regionName);
if (rinfo == null)
rinfo = m_RemoteGridService.GetRegionByName(scopeID, regionName);
// can't cache negative results for name lookups
m_RegionInfoCache.Cache(rinfo);
return rinfo;
}
public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{
List<GridRegion> rinfo = m_LocalGridService.GetRegionsByName(scopeID, name, maxNumber);
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetRegionsByName {0} found {1} regions", name, rinfo.Count);
List<GridRegion> grinfo = m_RemoteGridService.GetRegionsByName(scopeID, name, maxNumber);
if (grinfo != null)
{
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetRegionsByName {0} found {1} regions", name, grinfo.Count);
foreach (GridRegion r in grinfo)
{
m_RegionInfoCache.Cache(r);
if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null)
rinfo.Add(r);
}
}
return rinfo;
}
public virtual List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{
List<GridRegion> rinfo = m_LocalGridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax);
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetRegionRange {0} found {1} regions", name, rinfo.Count);
List<GridRegion> grinfo = m_RemoteGridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax);
if (grinfo != null)
{
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetRegionRange {0} found {1} regions", name, grinfo.Count);
foreach (GridRegion r in grinfo)
{
m_RegionInfoCache.Cache(r);
if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null)
rinfo.Add(r);
}
}
return rinfo;
}
public List<GridRegion> GetDefaultRegions(UUID scopeID)
{
List<GridRegion> rinfo = m_LocalGridService.GetDefaultRegions(scopeID);
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetDefaultRegions {0} found {1} regions", name, rinfo.Count);
List<GridRegion> grinfo = m_RemoteGridService.GetDefaultRegions(scopeID);
if (grinfo != null)
{
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetDefaultRegions {0} found {1} regions", name, grinfo.Count);
foreach (GridRegion r in grinfo)
{
m_RegionInfoCache.Cache(r);
if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null)
rinfo.Add(r);
}
}
return rinfo;
}
public List<GridRegion> GetDefaultHypergridRegions(UUID scopeID)
{
List<GridRegion> rinfo = m_LocalGridService.GetDefaultHypergridRegions(scopeID);
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetDefaultHypergridRegions {0} found {1} regions", name, rinfo.Count);
List<GridRegion> grinfo = m_RemoteGridService.GetDefaultHypergridRegions(scopeID);
if (grinfo != null)
{
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetDefaultHypergridRegions {0} found {1} regions", name, grinfo.Count);
foreach (GridRegion r in grinfo)
{
m_RegionInfoCache.Cache(r);
if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null)
rinfo.Add(r);
}
}
return rinfo;
}
public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
{
List<GridRegion> rinfo = m_LocalGridService.GetFallbackRegions(scopeID, x, y);
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetFallbackRegions {0} found {1} regions", name, rinfo.Count);
List<GridRegion> grinfo = m_RemoteGridService.GetFallbackRegions(scopeID, x, y);
if (grinfo != null)
{
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetFallbackRegions {0} found {1} regions", name, grinfo.Count);
foreach (GridRegion r in grinfo)
{
m_RegionInfoCache.Cache(r);
if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null)
rinfo.Add(r);
}
}
return rinfo;
}
public List<GridRegion> GetHyperlinks(UUID scopeID)
{
List<GridRegion> rinfo = m_LocalGridService.GetHyperlinks(scopeID);
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetHyperlinks {0} found {1} regions", name, rinfo.Count);
List<GridRegion> grinfo = m_RemoteGridService.GetHyperlinks(scopeID);
if (grinfo != null)
{
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetHyperlinks {0} found {1} regions", name, grinfo.Count);
foreach (GridRegion r in grinfo)
{
m_RegionInfoCache.Cache(r);
if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null)
rinfo.Add(r);
}
}
return rinfo;
}
public int GetRegionFlags(UUID scopeID, UUID regionID)
{
int flags = m_LocalGridService.GetRegionFlags(scopeID, regionID);
if (flags == -1)
flags = m_RemoteGridService.GetRegionFlags(scopeID, regionID);
return flags;
}
public Dictionary<string, object> GetExtraFeatures()
{
Dictionary<string, object> extraFeatures;
extraFeatures = m_LocalGridService.GetExtraFeatures();
if (extraFeatures.Count == 0)
extraFeatures = m_RemoteGridService.GetExtraFeatures();
return extraFeatures;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.CommandLine;
using System.Runtime.InteropServices;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
using Internal.CommandLine;
namespace ILCompiler
{
internal class Program
{
private Dictionary<string, string> _inputFilePaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private Dictionary<string, string> _referenceFilePaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private string _outputFilePath;
private bool _isCppCodegen;
private bool _isVerbose;
private string _dgmlLogFileName;
private bool _generateFullDgmlLog;
private TargetArchitecture _targetArchitecture;
private string _targetArchitectureStr;
private TargetOS _targetOS;
private string _targetOSStr;
private OptimizationMode _optimizationMode;
private bool _enableDebugInfo;
private string _systemModuleName = "System.Private.CoreLib";
private bool _multiFile;
private bool _useSharedGenerics;
private string _mapFileName;
private string _metadataLogFileName;
private string _singleMethodTypeName;
private string _singleMethodName;
private IReadOnlyList<string> _singleMethodGenericArgs;
private IReadOnlyList<string> _codegenOptions = Array.Empty<string>();
private IReadOnlyList<string> _rdXmlFilePaths = Array.Empty<string>();
private bool _help;
private Program()
{
}
private void Help(string helpText)
{
Console.WriteLine();
Console.Write("Microsoft (R) .NET Native IL Compiler");
Console.Write(" ");
Console.Write(typeof(Program).GetTypeInfo().Assembly.GetName().Version);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine(helpText);
}
private void InitializeDefaultOptions()
{
#if FXCORE
// We could offer this as a command line option, but then we also need to
// load a different RyuJIT, so this is a future nice to have...
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
_targetOS = TargetOS.Windows;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
_targetOS = TargetOS.Linux;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
_targetOS = TargetOS.OSX;
else
throw new NotImplementedException();
switch (RuntimeInformation.ProcessArchitecture)
{
case Architecture.X86:
_targetArchitecture = TargetArchitecture.X86;
break;
case Architecture.X64:
_targetArchitecture = TargetArchitecture.X64;
break;
case Architecture.Arm:
_targetArchitecture = TargetArchitecture.ARM;
break;
case Architecture.Arm64:
_targetArchitecture = TargetArchitecture.ARM64;
break;
default:
throw new NotImplementedException();
}
#else
_targetOS = TargetOS.Windows;
_targetArchitecture = TargetArchitecture.X64;
#endif
}
private ArgumentSyntax ParseCommandLine(string[] args)
{
IReadOnlyList<string> inputFiles = Array.Empty<string>();
IReadOnlyList<string> referenceFiles = Array.Empty<string>();
bool optimize = false;
bool waitForDebugger = false;
AssemblyName name = typeof(Program).GetTypeInfo().Assembly.GetName();
ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax =>
{
syntax.ApplicationName = name.Name.ToString();
// HandleHelp writes to error, fails fast with crash dialog and lacks custom formatting.
syntax.HandleHelp = false;
syntax.HandleErrors = true;
syntax.DefineOption("h|help", ref _help, "Help message for ILC");
syntax.DefineOptionList("r|reference", ref referenceFiles, "Reference file(s) for compilation");
syntax.DefineOption("o|out", ref _outputFilePath, "Output file path");
syntax.DefineOption("O", ref optimize, "Enable optimizations");
syntax.DefineOption("g", ref _enableDebugInfo, "Emit debugging information");
syntax.DefineOption("cpp", ref _isCppCodegen, "Compile for C++ code-generation");
syntax.DefineOption("dgmllog", ref _dgmlLogFileName, "Save result of dependency analysis as DGML");
syntax.DefineOption("fulllog", ref _generateFullDgmlLog, "Save detailed log of dependency analysis");
syntax.DefineOption("verbose", ref _isVerbose, "Enable verbose logging");
syntax.DefineOption("systemmodule", ref _systemModuleName, "System module name (default: System.Private.CoreLib)");
syntax.DefineOption("multifile", ref _multiFile, "Compile only input files (do not compile referenced assemblies)");
syntax.DefineOption("waitfordebugger", ref waitForDebugger, "Pause to give opportunity to attach debugger");
syntax.DefineOption("usesharedgenerics", ref _useSharedGenerics, "Enable shared generics");
syntax.DefineOptionList("codegenopt", ref _codegenOptions, "Define a codegen option");
syntax.DefineOptionList("rdxml", ref _rdXmlFilePaths, "RD.XML file(s) for compilation");
syntax.DefineOption("map", ref _mapFileName, "Generate a map file");
syntax.DefineOption("metadatalog", ref _metadataLogFileName, "Generate a metadata log file");
syntax.DefineOption("targetarch", ref _targetArchitectureStr, "Target architecture for cross compilation");
syntax.DefineOption("targetos", ref _targetOSStr, "Target OS for cross compilation");
syntax.DefineOption("singlemethodtypename", ref _singleMethodTypeName, "Single method compilation: name of the owning type");
syntax.DefineOption("singlemethodname", ref _singleMethodName, "Single method compilation: name of the method");
syntax.DefineOptionList("singlemethodgenericarg", ref _singleMethodGenericArgs, "Single method compilation: generic arguments to the method");
syntax.DefineParameterList("in", ref inputFiles, "Input file(s) to compile");
});
if (waitForDebugger)
{
Console.WriteLine("Waiting for debugger to attach. Press ENTER to continue");
Console.ReadLine();
}
_optimizationMode = optimize ? OptimizationMode.Blended : OptimizationMode.None;
foreach (var input in inputFiles)
Helpers.AppendExpandedPaths(_inputFilePaths, input, true);
foreach (var reference in referenceFiles)
Helpers.AppendExpandedPaths(_referenceFilePaths, reference, false);
return argSyntax;
}
private int Run(string[] args)
{
InitializeDefaultOptions();
ArgumentSyntax syntax = ParseCommandLine(args);
if (_help)
{
Help(syntax.GetHelpText());
return 1;
}
if (_outputFilePath == null)
throw new CommandLineException("Output filename must be specified (/out <file>)");
//
// Set target Architecture and OS
//
if (_targetArchitectureStr != null)
{
if (_targetArchitectureStr.Equals("x86", StringComparison.OrdinalIgnoreCase))
_targetArchitecture = TargetArchitecture.X86;
else if (_targetArchitectureStr.Equals("x64", StringComparison.OrdinalIgnoreCase))
_targetArchitecture = TargetArchitecture.X64;
else if (_targetArchitectureStr.Equals("arm", StringComparison.OrdinalIgnoreCase))
_targetArchitecture = TargetArchitecture.ARM;
else if (_targetArchitectureStr.Equals("armel", StringComparison.OrdinalIgnoreCase))
_targetArchitecture = TargetArchitecture.ARMEL;
else if (_targetArchitectureStr.Equals("arm64", StringComparison.OrdinalIgnoreCase))
_targetArchitecture = TargetArchitecture.ARM64;
else
throw new CommandLineException("Target architecture is not supported");
}
if (_targetOSStr != null)
{
if (_targetOSStr.Equals("windows", StringComparison.OrdinalIgnoreCase))
_targetOS = TargetOS.Windows;
else if (_targetOSStr.Equals("linux", StringComparison.OrdinalIgnoreCase))
_targetOS = TargetOS.Linux;
else if (_targetOSStr.Equals("osx", StringComparison.OrdinalIgnoreCase))
_targetOS = TargetOS.OSX;
else
throw new CommandLineException("Target OS is not supported");
}
//
// Initialize type system context
//
SharedGenericsMode genericsMode = _useSharedGenerics || !_isCppCodegen ?
SharedGenericsMode.CanonicalReferenceTypes : SharedGenericsMode.Disabled;
var typeSystemContext = new CompilerTypeSystemContext(new TargetDetails(_targetArchitecture, _targetOS, TargetAbi.CoreRT), genericsMode);
//
// TODO: To support our pre-compiled test tree, allow input files that aren't managed assemblies since
// some tests contain a mixture of both managed and native binaries.
//
// See: https://github.com/dotnet/corert/issues/2785
//
// When we undo this this hack, replace this foreach with
// typeSystemContext.InputFilePaths = _inputFilePaths;
//
Dictionary<string, string> inputFilePaths = new Dictionary<string, string>();
foreach (var inputFile in _inputFilePaths)
{
try
{
var module = typeSystemContext.GetModuleFromPath(inputFile.Value);
inputFilePaths.Add(inputFile.Key, inputFile.Value);
}
catch (TypeSystemException.BadImageFormatException)
{
// Keep calm and carry on.
}
}
typeSystemContext.InputFilePaths = inputFilePaths;
typeSystemContext.ReferenceFilePaths = _referenceFilePaths;
typeSystemContext.SetSystemModule(typeSystemContext.GetModuleForSimpleName(_systemModuleName));
if (typeSystemContext.InputFilePaths.Count == 0)
throw new CommandLineException("No input files specified");
//
// Initialize compilation group and compilation roots
//
// Single method mode?
MethodDesc singleMethod = CheckAndParseSingleMethodModeArguments(typeSystemContext);
CompilationModuleGroup compilationGroup;
List<ICompilationRootProvider> compilationRoots = new List<ICompilationRootProvider>();
if (singleMethod != null)
{
// Compiling just a single method
compilationGroup = new SingleMethodCompilationModuleGroup(singleMethod);
compilationRoots.Add(new SingleMethodRootProvider(singleMethod));
}
else
{
// Either single file, or multifile library, or multifile consumption.
EcmaModule entrypointModule = null;
foreach (var inputFile in typeSystemContext.InputFilePaths)
{
EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value);
if (module.PEReader.PEHeaders.IsExe)
{
if (entrypointModule != null)
throw new Exception("Multiple EXE modules");
entrypointModule = module;
}
compilationRoots.Add(new ExportedMethodsRootProvider(module));
}
if (entrypointModule != null)
{
LibraryInitializers libraryInitializers =
new LibraryInitializers(typeSystemContext, _isCppCodegen);
compilationRoots.Add(new MainMethodRootProvider(entrypointModule, libraryInitializers.LibraryInitializerMethods));
}
if (_multiFile)
{
List<EcmaModule> inputModules = new List<EcmaModule>();
foreach (var inputFile in typeSystemContext.InputFilePaths)
{
EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value);
if (entrypointModule == null)
{
// This is a multifile production build - we need to root all methods
compilationRoots.Add(new LibraryRootProvider(module));
}
inputModules.Add(module);
}
compilationGroup = new MultiFileSharedCompilationModuleGroup(typeSystemContext, inputModules);
}
else
{
if (entrypointModule == null)
throw new Exception("No entrypoint module");
compilationRoots.Add(new ExportedMethodsRootProvider((EcmaModule)typeSystemContext.SystemModule));
compilationGroup = new SingleFileCompilationModuleGroup(typeSystemContext);
}
foreach (var rdXmlFilePath in _rdXmlFilePaths)
{
compilationRoots.Add(new RdXmlRootProvider(typeSystemContext, rdXmlFilePath));
}
}
//
// Compile
//
CompilationBuilder builder;
if (_isCppCodegen)
builder = new CppCodegenCompilationBuilder(typeSystemContext, compilationGroup);
else
builder = new RyuJitCompilationBuilder(typeSystemContext, compilationGroup);
var logger = _isVerbose ? new Logger(Console.Out, true) : Logger.Null;
DependencyTrackingLevel trackingLevel = _dgmlLogFileName == null ?
DependencyTrackingLevel.None : (_generateFullDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First);
ICompilation compilation = builder
.UseBackendOptions(_codegenOptions)
.UseLogger(logger)
.UseDependencyTracking(trackingLevel)
.UseCompilationRoots(compilationRoots)
.UseOptimizationMode(_optimizationMode)
.UseDebugInfo(_enableDebugInfo)
.UseMetadataLogFile(_metadataLogFileName)
.ToCompilation();
ObjectDumper dumper = _mapFileName != null ? new ObjectDumper(_mapFileName) : null;
compilation.Compile(_outputFilePath, dumper);
if (_dgmlLogFileName != null)
compilation.WriteDependencyLog(_dgmlLogFileName);
return 0;
}
private TypeDesc FindType(CompilerTypeSystemContext context, string typeName)
{
ModuleDesc systemModule = context.SystemModule;
TypeDesc foundType = systemModule.GetTypeByCustomAttributeTypeName(typeName);
if (foundType == null)
throw new CommandLineException($"Type '{typeName}' not found");
TypeDesc classLibCanon = systemModule.GetType("System", "__Canon", false);
TypeDesc classLibUniCanon = systemModule.GetType("System", "__UniversalCanon", false);
return foundType.ReplaceTypesInConstructionOfType(
new TypeDesc[] { classLibCanon, classLibUniCanon },
new TypeDesc[] { context.CanonType, context.UniversalCanonType });
}
private MethodDesc CheckAndParseSingleMethodModeArguments(CompilerTypeSystemContext context)
{
if (_singleMethodName == null && _singleMethodTypeName == null && _singleMethodGenericArgs == null)
return null;
if (_singleMethodName == null || _singleMethodTypeName == null)
throw new CommandLineException("Both method name and type name are required parameters for single method mode");
TypeDesc owningType = FindType(context, _singleMethodTypeName);
// TODO: allow specifying signature to distinguish overloads
MethodDesc method = owningType.GetMethod(_singleMethodName, null);
if (method == null)
throw new CommandLineException($"Method '{_singleMethodName}' not found in '{_singleMethodTypeName}'");
if (method.HasInstantiation != (_singleMethodGenericArgs != null) ||
(method.HasInstantiation && (method.Instantiation.Length != _singleMethodGenericArgs.Count)))
{
throw new CommandLineException(
$"Expected {method.Instantiation.Length} generic arguments for method '{_singleMethodName}' on type '{_singleMethodTypeName}'");
}
if (method.HasInstantiation)
{
List<TypeDesc> genericArguments = new List<TypeDesc>();
foreach (var argString in _singleMethodGenericArgs)
genericArguments.Add(FindType(context, argString));
method = method.MakeInstantiatedMethod(genericArguments.ToArray());
}
return method;
}
private static int Main(string[] args)
{
#if DEBUG
return new Program().Run(args);
#else
try
{
return new Program().Run(args);
}
catch (Exception e)
{
Console.Error.WriteLine("Error: " + e.Message);
Console.Error.WriteLine(e.ToString());
return 1;
}
#endif
}
}
}
| |
//
// 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
//
// 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 Microsoft.PackageManagement.Internal.Implementation {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Api;
using PackageManagement.Packaging;
using Utility.Extensions;
using Utility.Platform;
using Utility.Plugin;
using Process = System.Diagnostics.Process;
internal class ProviderServicesImpl : IProviderServices {
internal static IProviderServices Instance = new ProviderServicesImpl();
private static readonly Regex _canonicalPackageRegex = new Regex(@"([^:]*?):([^/\#]*)/?([^#]*)\#?(.*)");
private PackageManagementService PackageManagementService {
get {
return PackageManager.Instance as PackageManagementService;
}
}
public bool IsElevated {
get {
return AdminPrivilege.IsElevated;
}
}
public IEnumerable<SoftwareIdentity> FindPackageByCanonicalId(string canonicalId, IRequest requestObject) {
if (requestObject == null) {
throw new ArgumentNullException("requestObject");
}
return PackageManagementService.FindPackageByCanonicalId(canonicalId, requestObject);
}
public string GetCanonicalPackageId(string providerName, string packageName, string version, string source) {
return SoftwareIdentity.CreateCanonicalId(providerName, packageName, version, source);
}
public string ParseProviderName(string canonicalPackageId) {
return _canonicalPackageRegex.Match(canonicalPackageId).Groups[1].Value;
}
public string ParsePackageName(string canonicalPackageId) {
return _canonicalPackageRegex.Match(canonicalPackageId).Groups[2].Value;
}
public string ParsePackageVersion(string canonicalPackageId) {
return _canonicalPackageRegex.Match(canonicalPackageId).Groups[3].Value;
}
public string ParsePackageSource(string canonicalPackageId) {
return _canonicalPackageRegex.Match(canonicalPackageId).Groups[4].Value;
}
public bool IsSupportedArchive(string localFilename, IRequest request) {
if (request == null) {
throw new ArgumentNullException("request");
}
if (!request.IsCanceled) {
return PackageManagementService.Archivers.Values.Any(archiver => archiver.IsSupportedFile(localFilename));
}
return false;
}
public string DownloadFile(Uri remoteLocation, string localFilename, IRequest request) {
return DownloadFile(remoteLocation, localFilename, -1, true, request);
}
public string DownloadFile(Uri remoteLocation, string localFilename, int timeoutMilliseconds, bool showProgress, IRequest request) {
if (request == null) {
throw new ArgumentNullException("request");
}
if (!request.IsCanceled) {
// check the Uri type, see if we have anyone who can handle that
// if so, call that provider's download file
if (remoteLocation == null) {
throw new ArgumentNullException("remoteLocation");
}
foreach (var downloader in PackageManagementService.Downloaders.Values) {
if (downloader.SupportedUriSchemes.Contains(remoteLocation.Scheme, StringComparer.OrdinalIgnoreCase)) {
return downloader.DownloadFile(remoteLocation, localFilename,timeoutMilliseconds, showProgress, request);
}
}
Error(request, ErrorCategory.NotImplemented, remoteLocation.Scheme, Constants.Messages.ProtocolNotSupported, remoteLocation.Scheme);
}
return null;
}
public IEnumerable<string> UnpackArchive(string localFilename, string destinationFolder, IRequest request) {
if (request == null) {
throw new ArgumentNullException("request");
}
if (!request.IsCanceled) {
// check who supports the archive type
// and call that provider.
if (request == null) {
throw new ArgumentNullException("request");
}
foreach (var archiver in PackageManagementService.Archivers.Values) {
if (archiver.IsSupportedFile(localFilename)) {
return archiver.UnpackArchive(localFilename, destinationFolder, request);
}
}
Error(request, ErrorCategory.NotImplemented, localFilename, Constants.Messages.UnsupportedArchive);
}
return Enumerable.Empty<string>();
}
public bool Install(string fileName, string additionalArgs, IRequest request) {
if (request == null) {
throw new ArgumentNullException("request");
}
if (!request.IsCanceled) {
if (String.IsNullOrWhiteSpace(fileName)) {
return false;
}
// high-level api for simply installing a file
// returns false if unsuccessful.
foreach (var provider in PackageManager.Instance.PackageProviders) {
var packages = provider.FindPackageByFile(fileName, request).ToArray();
if (packages.Length > 0) {
// found a provider that can handle this package.
// install with this provider
// ToDo: @FutureGarrett -- we need to be able to handle priorities and who wins...
foreach (var package in packages) {
foreach (var installedPackage in provider.InstallPackage(package, request.Extend<IRequest>(new {
GetOptionValues = new Func<string, IEnumerable<string>>(key => {
if (key.EqualsIgnoreCase("additionalArguments")) {
return new[] {additionalArgs};
}
return request.GetOptionValues(key);
})
}))) {
Debug(request, "Installed internal package {0}", installedPackage.Name);
}
}
return true;
}
}
}
return false;
}
public bool IsSignedAndTrusted(string filename, IRequest request) {
if (request == null) {
throw new ArgumentNullException("request");
}
if (!request.IsCanceled) {
if (String.IsNullOrWhiteSpace(filename) || !filename.FileExists()) {
return false;
}
Debug(request, "Calling 'ProviderService::IsSignedAndTrusted, '{0}'", filename);
// we are not using this function anywhere
#if !UNIX
var wtd = new WinTrustData(filename);
var result = NativeMethods.WinVerifyTrust(new IntPtr(-1), new Guid("{00AAC56B-CD44-11d0-8CC2-00C04FC295EE}"), wtd);
return result == WinVerifyTrustResult.Success;
#endif
}
return false;
}
public int StartProcess(string filename, string arguments, bool requiresElevation, out string standardOutput, IRequest requestObject) {
Process p = new Process();
#if !CORECLR
if (requiresElevation)
{
p.StartInfo.UseShellExecute = true;
}
else
#endif
{
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
}
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = filename;
if (!String.IsNullOrEmpty(arguments)) {
p.StartInfo.Arguments = arguments;
}
p.Start();
if (p.StartInfo.RedirectStandardOutput) {
standardOutput = p.StandardOutput.ReadToEnd();
} else {
standardOutput = String.Empty;
}
p.WaitForExit();
return p.ExitCode;
}
public bool Error(IRequest request, ErrorCategory category, string targetObjectValue, string messageText, params object[] args) {
return request.Error(messageText, category.ToString(), targetObjectValue, request.FormatMessageString(messageText, args));
}
public bool Warning(IRequest request, string messageText, params object[] args) {
return request.Warning(request.FormatMessageString(messageText, args));
}
public bool Message(IRequest request, string messageText, params object[] args) {
return request.Message(request.FormatMessageString(messageText, args));
}
public bool Verbose(IRequest request, string messageText, params object[] args) {
return request.Verbose(request.FormatMessageString(messageText, args));
}
public bool Debug(IRequest request, string messageText, params object[] args) {
return request.Debug(request.FormatMessageString(messageText, args));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace CppSharp
{
public enum NewLineKind
{
Never,
Always,
BeforeNextBlock,
IfNotEmpty
}
public enum BlockKind
{
Unknown,
BlockComment,
InlineComment,
Header,
Footer,
Usings,
Namespace,
Enum,
EnumItem,
Typedef,
Class,
InternalsClass,
InternalsClassMethod,
InternalsClassField,
Functions,
Function,
Method,
Event,
Variable,
Property,
Field,
VTableDelegate,
Region,
Interface,
Finalizer,
Includes,
IncludesForwardReferences,
ForwardReferences,
MethodBody,
FunctionsClass,
Template,
Destructor,
AccessSpecifier,
Fields,
}
[DebuggerDisplay("{BlockKind} | {Object}")]
public class Block : ITextGenerator
{
public TextGenerator Text { get; set; }
public BlockKind Kind { get; set; }
public NewLineKind NewLineKind { get; set; }
public object Object { get; set; }
public Block Parent { get; set; }
public List<Block> Blocks { get; set; }
private bool hasIndentChanged;
private bool isSubBlock;
public Func<bool> CheckGenerate;
public Block() : this(BlockKind.Unknown)
{
}
public Block(BlockKind kind)
{
Kind = kind;
Blocks = new List<Block>();
Text = new TextGenerator();
hasIndentChanged = false;
isSubBlock = false;
}
public void AddBlock(Block block)
{
if (Text.StringBuilder.Length != 0 || hasIndentChanged)
{
hasIndentChanged = false;
var newBlock = new Block { Text = Text.Clone(), isSubBlock = true };
Text.StringBuilder.Clear();
AddBlock(newBlock);
}
block.Parent = this;
Blocks.Add(block);
}
public IEnumerable<Block> FindBlocks(BlockKind kind)
{
foreach (var block in Blocks)
{
if (block.Kind == kind)
yield return block;
foreach (var childBlock in block.FindBlocks(kind))
yield return childBlock;
}
}
public virtual string Generate()
{
if (CheckGenerate != null && !CheckGenerate())
return "";
if (Blocks.Count == 0)
return Text.ToString();
var builder = new StringBuilder();
uint totalIndent = 0;
Block previousBlock = null;
var blockIndex = 0;
foreach (var childBlock in Blocks)
{
var childText = childBlock.Generate();
var nextBlock = (++blockIndex < Blocks.Count)
? Blocks[blockIndex]
: null;
var skipBlock = false;
if (nextBlock != null)
{
var nextText = nextBlock.Generate();
if (string.IsNullOrEmpty(nextText) &&
childBlock.NewLineKind == NewLineKind.IfNotEmpty)
skipBlock = true;
}
if (skipBlock)
continue;
if (string.IsNullOrEmpty(childText))
continue;
var lines = childText.SplitAndKeep(Environment.NewLine).ToList();
if (previousBlock != null &&
previousBlock.NewLineKind == NewLineKind.BeforeNextBlock)
builder.AppendLine();
if (childBlock.isSubBlock)
totalIndent = 0;
foreach (var line in lines)
{
if (string.IsNullOrEmpty(line))
continue;
if (!string.IsNullOrWhiteSpace(line))
builder.Append(new string(' ', (int)totalIndent));
builder.Append(line);
if (!line.EndsWith(Environment.NewLine, StringComparison.Ordinal))
builder.AppendLine();
}
if (childBlock.NewLineKind == NewLineKind.Always)
builder.AppendLine();
totalIndent += childBlock.Text.Indent;
previousBlock = childBlock;
}
if (Text.StringBuilder.Length != 0)
builder.Append(Text.StringBuilder);
return builder.ToString();
}
public StringBuilder GenerateUnformatted()
{
if (CheckGenerate != null && !CheckGenerate())
return new StringBuilder(0);
if (Blocks.Count == 0)
return Text.StringBuilder;
var builder = new StringBuilder();
Block previousBlock = null;
var blockIndex = 0;
foreach (var childBlock in Blocks)
{
var childText = childBlock.GenerateUnformatted();
var nextBlock = (++blockIndex < Blocks.Count)
? Blocks[blockIndex]
: null;
if (nextBlock != null)
{
var nextText = nextBlock.GenerateUnformatted();
if (nextText.Length == 0 &&
childBlock.NewLineKind == NewLineKind.IfNotEmpty)
continue;
}
if (childText.Length == 0)
continue;
if (previousBlock != null &&
previousBlock.NewLineKind == NewLineKind.BeforeNextBlock)
builder.AppendLine();
builder.Append(childText);
if (childBlock.NewLineKind == NewLineKind.Always)
builder.AppendLine();
previousBlock = childBlock;
}
if (Text.StringBuilder.Length != 0)
builder.Append(Text.StringBuilder);
return builder;
}
public bool IsEmpty
{
get
{
if (Blocks.Any(block => !block.IsEmpty))
return false;
return string.IsNullOrEmpty(Text.ToString());
}
}
#region ITextGenerator implementation
public uint Indent { get { return Text.Indent; } }
public void Write(string msg, params object[] args)
{
Text.Write(msg, args);
}
public void WriteLine(string msg, params object[] args)
{
Text.WriteLine(msg, args);
}
public void WriteLineIndent(string msg, params object[] args)
{
Text.WriteLineIndent(msg, args);
}
public void NewLine()
{
Text.NewLine();
}
public void NewLineIfNeeded()
{
Text.NewLineIfNeeded();
}
public void NeedNewLine()
{
Text.NeedNewLine();
}
public void ResetNewLine()
{
Text.ResetNewLine();
}
public void PushIndent(uint indent = 4u)
{
hasIndentChanged = true;
Text.PushIndent(indent);
}
public void PopIndent()
{
hasIndentChanged = true;
Text.PopIndent();
}
public void WriteStartBraceIndent()
{
Text.WriteStartBraceIndent();
}
public void WriteCloseBraceIndent()
{
Text.WriteCloseBraceIndent();
}
#endregion
}
public abstract class BlockGenerator : ITextGenerator
{
public Block RootBlock { get; private set; }
public Block ActiveBlock { get; private set; }
protected BlockGenerator()
{
RootBlock = new Block();
ActiveBlock = RootBlock;
}
public virtual string Generate()
{
return RootBlock.Generate();
}
public string GenerateUnformatted()
{
return RootBlock.GenerateUnformatted().ToString();
}
#region Block helpers
public void AddBlock(Block block)
{
ActiveBlock.AddBlock(block);
}
public void PushBlock(BlockKind kind = BlockKind.Unknown, object obj = null)
{
var block = new Block { Kind = kind, Object = obj };
PushBlock(block);
}
public void PushBlock(Block block)
{
block.Parent = ActiveBlock;
ActiveBlock.AddBlock(block);
ActiveBlock = block;
}
public Block PopBlock(NewLineKind newLineKind = NewLineKind.Never)
{
var block = ActiveBlock;
ActiveBlock.NewLineKind = newLineKind;
ActiveBlock = ActiveBlock.Parent;
return block;
}
public IEnumerable<Block> FindBlocks(BlockKind kind)
{
return RootBlock.FindBlocks(kind);
}
public Block FindBlock(BlockKind kind)
{
return FindBlocks(kind).SingleOrDefault();
}
#endregion
#region ITextGenerator implementation
public uint Indent { get { return ActiveBlock.Indent; } }
public void Write(string msg, params object[] args)
{
ActiveBlock.Write(msg, args);
}
public void WriteLine(string msg, params object[] args)
{
ActiveBlock.WriteLine(msg, args);
}
public void WriteLineIndent(string msg, params object[] args)
{
ActiveBlock.WriteLineIndent(msg, args);
}
public void NewLine()
{
ActiveBlock.NewLine();
}
public void NewLineIfNeeded()
{
ActiveBlock.NewLineIfNeeded();
}
public void NeedNewLine()
{
ActiveBlock.NeedNewLine();
}
public void ResetNewLine()
{
ActiveBlock.ResetNewLine();
}
public void PushIndent(uint indent = 4u)
{
ActiveBlock.PushIndent(indent);
}
public void PopIndent()
{
ActiveBlock.PopIndent();
}
public void WriteStartBraceIndent()
{
ActiveBlock.WriteStartBraceIndent();
}
public void WriteCloseBraceIndent()
{
ActiveBlock.WriteCloseBraceIndent();
}
#endregion
}
}
| |
/*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter;
namespace Org.OpenAPITools.Model
{
/// <summary>
/// PipelinelatestRun
/// </summary>
[DataContract(Name = "PipelinelatestRun")]
public partial class PipelinelatestRun : IEquatable<PipelinelatestRun>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="PipelinelatestRun" /> class.
/// </summary>
/// <param name="artifacts">artifacts.</param>
/// <param name="durationInMillis">durationInMillis.</param>
/// <param name="estimatedDurationInMillis">estimatedDurationInMillis.</param>
/// <param name="enQueueTime">enQueueTime.</param>
/// <param name="endTime">endTime.</param>
/// <param name="id">id.</param>
/// <param name="organization">organization.</param>
/// <param name="pipeline">pipeline.</param>
/// <param name="result">result.</param>
/// <param name="runSummary">runSummary.</param>
/// <param name="startTime">startTime.</param>
/// <param name="state">state.</param>
/// <param name="type">type.</param>
/// <param name="commitId">commitId.</param>
/// <param name="_class">_class.</param>
public PipelinelatestRun(List<PipelinelatestRunartifacts> artifacts = default(List<PipelinelatestRunartifacts>), int durationInMillis = default(int), int estimatedDurationInMillis = default(int), string enQueueTime = default(string), string endTime = default(string), string id = default(string), string organization = default(string), string pipeline = default(string), string result = default(string), string runSummary = default(string), string startTime = default(string), string state = default(string), string type = default(string), string commitId = default(string), string _class = default(string))
{
this.Artifacts = artifacts;
this.DurationInMillis = durationInMillis;
this.EstimatedDurationInMillis = estimatedDurationInMillis;
this.EnQueueTime = enQueueTime;
this.EndTime = endTime;
this.Id = id;
this.Organization = organization;
this.Pipeline = pipeline;
this.Result = result;
this.RunSummary = runSummary;
this.StartTime = startTime;
this.State = state;
this.Type = type;
this.CommitId = commitId;
this.Class = _class;
}
/// <summary>
/// Gets or Sets Artifacts
/// </summary>
[DataMember(Name = "artifacts", EmitDefaultValue = false)]
public List<PipelinelatestRunartifacts> Artifacts { get; set; }
/// <summary>
/// Gets or Sets DurationInMillis
/// </summary>
[DataMember(Name = "durationInMillis", EmitDefaultValue = false)]
public int DurationInMillis { get; set; }
/// <summary>
/// Gets or Sets EstimatedDurationInMillis
/// </summary>
[DataMember(Name = "estimatedDurationInMillis", EmitDefaultValue = false)]
public int EstimatedDurationInMillis { get; set; }
/// <summary>
/// Gets or Sets EnQueueTime
/// </summary>
[DataMember(Name = "enQueueTime", EmitDefaultValue = false)]
public string EnQueueTime { get; set; }
/// <summary>
/// Gets or Sets EndTime
/// </summary>
[DataMember(Name = "endTime", EmitDefaultValue = false)]
public string EndTime { get; set; }
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name = "id", EmitDefaultValue = false)]
public string Id { get; set; }
/// <summary>
/// Gets or Sets Organization
/// </summary>
[DataMember(Name = "organization", EmitDefaultValue = false)]
public string Organization { get; set; }
/// <summary>
/// Gets or Sets Pipeline
/// </summary>
[DataMember(Name = "pipeline", EmitDefaultValue = false)]
public string Pipeline { get; set; }
/// <summary>
/// Gets or Sets Result
/// </summary>
[DataMember(Name = "result", EmitDefaultValue = false)]
public string Result { get; set; }
/// <summary>
/// Gets or Sets RunSummary
/// </summary>
[DataMember(Name = "runSummary", EmitDefaultValue = false)]
public string RunSummary { get; set; }
/// <summary>
/// Gets or Sets StartTime
/// </summary>
[DataMember(Name = "startTime", EmitDefaultValue = false)]
public string StartTime { get; set; }
/// <summary>
/// Gets or Sets State
/// </summary>
[DataMember(Name = "state", EmitDefaultValue = false)]
public string State { get; set; }
/// <summary>
/// Gets or Sets Type
/// </summary>
[DataMember(Name = "type", EmitDefaultValue = false)]
public string Type { get; set; }
/// <summary>
/// Gets or Sets CommitId
/// </summary>
[DataMember(Name = "commitId", EmitDefaultValue = false)]
public string CommitId { get; set; }
/// <summary>
/// Gets or Sets Class
/// </summary>
[DataMember(Name = "_class", EmitDefaultValue = false)]
public string Class { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("class PipelinelatestRun {\n");
sb.Append(" Artifacts: ").Append(Artifacts).Append("\n");
sb.Append(" DurationInMillis: ").Append(DurationInMillis).Append("\n");
sb.Append(" EstimatedDurationInMillis: ").Append(EstimatedDurationInMillis).Append("\n");
sb.Append(" EnQueueTime: ").Append(EnQueueTime).Append("\n");
sb.Append(" EndTime: ").Append(EndTime).Append("\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Organization: ").Append(Organization).Append("\n");
sb.Append(" Pipeline: ").Append(Pipeline).Append("\n");
sb.Append(" Result: ").Append(Result).Append("\n");
sb.Append(" RunSummary: ").Append(RunSummary).Append("\n");
sb.Append(" StartTime: ").Append(StartTime).Append("\n");
sb.Append(" State: ").Append(State).Append("\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append(" CommitId: ").Append(CommitId).Append("\n");
sb.Append(" Class: ").Append(Class).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as PipelinelatestRun);
}
/// <summary>
/// Returns true if PipelinelatestRun instances are equal
/// </summary>
/// <param name="input">Instance of PipelinelatestRun to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PipelinelatestRun input)
{
if (input == null)
{
return false;
}
return
(
this.Artifacts == input.Artifacts ||
this.Artifacts != null &&
input.Artifacts != null &&
this.Artifacts.SequenceEqual(input.Artifacts)
) &&
(
this.DurationInMillis == input.DurationInMillis ||
this.DurationInMillis.Equals(input.DurationInMillis)
) &&
(
this.EstimatedDurationInMillis == input.EstimatedDurationInMillis ||
this.EstimatedDurationInMillis.Equals(input.EstimatedDurationInMillis)
) &&
(
this.EnQueueTime == input.EnQueueTime ||
(this.EnQueueTime != null &&
this.EnQueueTime.Equals(input.EnQueueTime))
) &&
(
this.EndTime == input.EndTime ||
(this.EndTime != null &&
this.EndTime.Equals(input.EndTime))
) &&
(
this.Id == input.Id ||
(this.Id != null &&
this.Id.Equals(input.Id))
) &&
(
this.Organization == input.Organization ||
(this.Organization != null &&
this.Organization.Equals(input.Organization))
) &&
(
this.Pipeline == input.Pipeline ||
(this.Pipeline != null &&
this.Pipeline.Equals(input.Pipeline))
) &&
(
this.Result == input.Result ||
(this.Result != null &&
this.Result.Equals(input.Result))
) &&
(
this.RunSummary == input.RunSummary ||
(this.RunSummary != null &&
this.RunSummary.Equals(input.RunSummary))
) &&
(
this.StartTime == input.StartTime ||
(this.StartTime != null &&
this.StartTime.Equals(input.StartTime))
) &&
(
this.State == input.State ||
(this.State != null &&
this.State.Equals(input.State))
) &&
(
this.Type == input.Type ||
(this.Type != null &&
this.Type.Equals(input.Type))
) &&
(
this.CommitId == input.CommitId ||
(this.CommitId != null &&
this.CommitId.Equals(input.CommitId))
) &&
(
this.Class == input.Class ||
(this.Class != null &&
this.Class.Equals(input.Class))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Artifacts != null)
{
hashCode = (hashCode * 59) + this.Artifacts.GetHashCode();
}
hashCode = (hashCode * 59) + this.DurationInMillis.GetHashCode();
hashCode = (hashCode * 59) + this.EstimatedDurationInMillis.GetHashCode();
if (this.EnQueueTime != null)
{
hashCode = (hashCode * 59) + this.EnQueueTime.GetHashCode();
}
if (this.EndTime != null)
{
hashCode = (hashCode * 59) + this.EndTime.GetHashCode();
}
if (this.Id != null)
{
hashCode = (hashCode * 59) + this.Id.GetHashCode();
}
if (this.Organization != null)
{
hashCode = (hashCode * 59) + this.Organization.GetHashCode();
}
if (this.Pipeline != null)
{
hashCode = (hashCode * 59) + this.Pipeline.GetHashCode();
}
if (this.Result != null)
{
hashCode = (hashCode * 59) + this.Result.GetHashCode();
}
if (this.RunSummary != null)
{
hashCode = (hashCode * 59) + this.RunSummary.GetHashCode();
}
if (this.StartTime != null)
{
hashCode = (hashCode * 59) + this.StartTime.GetHashCode();
}
if (this.State != null)
{
hashCode = (hashCode * 59) + this.State.GetHashCode();
}
if (this.Type != null)
{
hashCode = (hashCode * 59) + this.Type.GetHashCode();
}
if (this.CommitId != null)
{
hashCode = (hashCode * 59) + this.CommitId.GetHashCode();
}
if (this.Class != null)
{
hashCode = (hashCode * 59) + this.Class.GetHashCode();
}
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
//---------------------------------------------------------------------------
// File: ProgressBar.cs
//
// Description:
// Implementation of ProgressBar control.
//
// History:
// 06/28/2004 - t-sergin - Created
//
// Copyright (C) 2004 by Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using System;
using System.Collections.Specialized;
using System.Threading;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Media.Animation;
using MS.Internal;
using System.Windows.Shapes;
using MS.Internal.KnownBoxes;
namespace System.Windows.Controls
{
/// <summary>
/// The ProgressBar class
/// </summary>
/// <seealso cref="RangeBase" />
[TemplatePart(Name = "PART_Track", Type = typeof(FrameworkElement))]
[TemplatePart(Name = "PART_Indicator", Type = typeof(FrameworkElement))]
[TemplatePart(Name = "PART_GlowRect", Type = typeof(FrameworkElement))]
public class ProgressBar : RangeBase
{
#region Constructors
static ProgressBar()
{
FocusableProperty.OverrideMetadata(typeof(ProgressBar), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox));
DefaultStyleKeyProperty.OverrideMetadata(typeof(ProgressBar), new FrameworkPropertyMetadata(typeof(ProgressBar)));
_dType = DependencyObjectType.FromSystemTypeInternal(typeof(ProgressBar));
// Set default to 100.0
RangeBase.MaximumProperty.OverrideMetadata(typeof(ProgressBar), new FrameworkPropertyMetadata(100.0));
ForegroundProperty.OverrideMetadata(typeof(ProgressBar), new FrameworkPropertyMetadata(OnForegroundChanged));
}
/// <summary>
/// Instantiates a new instance of Progressbar without Dispatcher.
/// </summary>
public ProgressBar() : base()
{
// Hook a change handler for IsVisible so we can start/stop animating.
// Ideally we would do this by overriding metadata, but it's a read-only
// property so we can't.
IsVisibleChanged += (s, e) => { UpdateAnimation(); };
}
#endregion Constructors
#region Properties
/// <summary>
/// The DependencyProperty for the IsIndeterminate property.
/// Flags: none
/// DefaultValue: false
/// </summary>
public static readonly DependencyProperty IsIndeterminateProperty =
DependencyProperty.Register(
"IsIndeterminate",
typeof(bool),
typeof(ProgressBar),
new FrameworkPropertyMetadata(
false,
new PropertyChangedCallback(OnIsIndeterminateChanged)));
/// <summary>
/// Determines if ProgressBar shows actual values (false)
/// or generic, continuous progress feedback (true).
/// </summary>
/// <value></value>
public bool IsIndeterminate
{
get { return (bool) GetValue(IsIndeterminateProperty); }
set { SetValue(IsIndeterminateProperty, value); }
}
/// <summary>
/// Called when IsIndeterminateProperty is changed on "d".
/// </summary>
private static void OnIsIndeterminateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ProgressBar progressBar = (ProgressBar)d;
// Invalidate automation peer
ProgressBarAutomationPeer peer = UIElementAutomationPeer.FromElement(progressBar) as ProgressBarAutomationPeer;
if (peer != null)
{
peer.InvalidatePeer();
}
progressBar.SetProgressBarGlowElementBrush();
progressBar.SetProgressBarIndicatorLength();
progressBar.UpdateVisualState();
}
private static void OnForegroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ProgressBar progressBar = (ProgressBar)d;
progressBar.SetProgressBarGlowElementBrush();
}
/// <summary>
/// DependencyProperty for <see cref="Orientation" /> property.
/// </summary>
public static readonly DependencyProperty OrientationProperty =
DependencyProperty.Register(
"Orientation",
typeof(Orientation),
typeof(ProgressBar),
new FrameworkPropertyMetadata(
Orientation.Horizontal,
FrameworkPropertyMetadataOptions.AffectsMeasure,
new PropertyChangedCallback(OnOrientationChanged)),
new ValidateValueCallback(IsValidOrientation));
/// <summary>
/// Specifies orientation of the ProgressBar.
/// </summary>
public Orientation Orientation
{
get { return (Orientation) GetValue(OrientationProperty); }
set { SetValue(OrientationProperty, value); }
}
internal static bool IsValidOrientation(object o)
{
Orientation value = (Orientation)o;
return value == Orientation.Horizontal
|| value == Orientation.Vertical;
}
private static void OnOrientationChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ProgressBar progressBar = (ProgressBar)d;
progressBar.SetProgressBarIndicatorLength();
}
#endregion Properties
#region Event Handler
// Set the width/height of the contract parts
private void SetProgressBarIndicatorLength()
{
if (_track != null && _indicator != null)
{
double min = Minimum;
double max = Maximum;
double val = Value;
// When indeterminate or maximum == minimum, have the indicator stretch the
// whole length of track
double percent = IsIndeterminate || max <= min ? 1.0 : (val - min) / (max - min);
_indicator.Width = percent * _track.ActualWidth;
UpdateAnimation();
}
}
// This is used to set the correct brush/opacity mask on the indicator.
private void SetProgressBarGlowElementBrush()
{
if (_glow == null)
return;
_glow.InvalidateProperty(UIElement.OpacityMaskProperty);
_glow.InvalidateProperty(Shape.FillProperty);
if (this.IsIndeterminate)
{
if (this.Foreground is SolidColorBrush)
{
Color color = ((SolidColorBrush)this.Foreground).Color;
//Create the gradient
LinearGradientBrush b = new LinearGradientBrush();
b.StartPoint = new Point(0,0);
b.EndPoint = new Point(1,0);
b.GradientStops.Add(new GradientStop(Colors.Transparent, 0.0));
b.GradientStops.Add(new GradientStop(color, 0.4));
b.GradientStops.Add(new GradientStop(color, 0.6));
b.GradientStops.Add(new GradientStop(Colors.Transparent, 1.0));
_glow.SetCurrentValue(Shape.FillProperty, b);
}
else
{
// This is not a solid color brush so we will need an opacity mask.
LinearGradientBrush mask= new LinearGradientBrush();
mask.StartPoint = new Point(0,0);
mask.EndPoint = new Point(1,0);
mask.GradientStops.Add(new GradientStop(Colors.Transparent, 0.0));
mask.GradientStops.Add(new GradientStop(Colors.Black, 0.4));
mask.GradientStops.Add(new GradientStop(Colors.Black, 0.6));
mask.GradientStops.Add(new GradientStop(Colors.Transparent, 1.0));
_glow.SetCurrentValue(UIElement.OpacityMaskProperty, mask);
_glow.SetCurrentValue(Shape.FillProperty, this.Foreground);
}
}
}
//This creates the repeating animation
private void UpdateAnimation()
{
if (_glow != null)
{
if(IsVisible && (_glow.Width > 0) && (_indicator.Width > 0 ))
{
//Set up the animation
double endPos = _indicator.Width + _glow.Width;
double startPos = -1 * _glow.Width;
TimeSpan translateTime = TimeSpan.FromSeconds(((int)(endPos - startPos) / 200.0)); // travel at 200px /second
TimeSpan pauseTime = TimeSpan.FromSeconds(1.0); // pause 1 second between animations
TimeSpan startTime;
//Is the animation currenly running (with one pixel fudge factor)
if (DoubleUtil.GreaterThan( _glow.Margin.Left,startPos) && ( DoubleUtil.LessThan(_glow.Margin.Left, endPos-1)))
{
// make it appear that the timer already started.
// To do this find out how many pixels the glow has moved and divide by the speed to get time.
startTime = TimeSpan.FromSeconds(-1*(_glow.Margin.Left-startPos)/200.0);
}
else
{
startTime = TimeSpan.Zero;
}
ThicknessAnimationUsingKeyFrames animation = new ThicknessAnimationUsingKeyFrames();
animation.BeginTime = startTime;
animation.Duration = new Duration(translateTime + pauseTime);
animation.RepeatBehavior = RepeatBehavior.Forever;
//Start with the glow hidden on the left.
animation.KeyFrames.Add(new LinearThicknessKeyFrame(new Thickness(startPos,0,0,0), TimeSpan.FromSeconds(0)));
//Move to the glow hidden on the right.
animation.KeyFrames.Add(new LinearThicknessKeyFrame(new Thickness(endPos,0,0,0), translateTime));
//There is a pause after the glow is off screen
_glow.BeginAnimation(FrameworkElement.MarginProperty, animation);
}
else
{
_glow.BeginAnimation(FrameworkElement.MarginProperty, null);
}
}
}
#endregion
#region Method Overrides
internal override void ChangeVisualState(bool useTransitions)
{
if (!IsIndeterminate)
{
VisualStateManager.GoToState(this, VisualStates.StateDeterminate, useTransitions);
}
else
{
VisualStateManager.GoToState(this, VisualStates.StateIndeterminate, useTransitions);
}
// Dont call base.ChangeVisualState because we dont want to pick up those state changes (SL compat).
ChangeValidationVisualState(useTransitions);
}
/// <summary>
/// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>)
/// </summary>
protected override AutomationPeer OnCreateAutomationPeer()
{
return new ProgressBarAutomationPeer(this);
}
/// <summary>
/// This method is invoked when the Minimum property changes.
/// </summary>
/// <param name="oldMinimum">The old value of the Minimum property.</param>
/// <param name="newMinimum">The new value of the Minimum property.</param>
protected override void OnMinimumChanged(double oldMinimum, double newMinimum)
{
base.OnMinimumChanged(oldMinimum, newMinimum);
SetProgressBarIndicatorLength();
}
/// <summary>
/// This method is invoked when the Maximum property changes.
/// </summary>
/// <param name="oldMaximum">The old value of the Maximum property.</param>
/// <param name="newMaximum">The new value of the Maximum property.</param>
protected override void OnMaximumChanged(double oldMaximum, double newMaximum)
{
base.OnMaximumChanged(oldMaximum, newMaximum);
SetProgressBarIndicatorLength();
}
/// <summary>
/// This method is invoked when the Value property changes.
/// ProgressBar updates its style parts when Value changes.
/// </summary>
/// <param name="oldValue">The old value of the Value property.</param>
/// <param name="newValue">The new value of the Value property.</param>
protected override void OnValueChanged(double oldValue, double newValue)
{
base.OnValueChanged(oldValue, newValue);
SetProgressBarIndicatorLength();
}
/// <summary>
/// Called when the Template's tree has been generated
/// </summary>
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
if (_track != null)
{
_track.SizeChanged -= OnTrackSizeChanged;
}
_track = GetTemplateChild(TrackTemplateName) as FrameworkElement;
_indicator = GetTemplateChild(IndicatorTemplateName) as FrameworkElement;
_glow = GetTemplateChild(GlowingRectTemplateName) as FrameworkElement;
if (_track != null)
{
_track.SizeChanged += OnTrackSizeChanged;
}
if (this.IsIndeterminate)
SetProgressBarGlowElementBrush();
}
private void OnTrackSizeChanged(object sender, SizeChangedEventArgs e)
{
SetProgressBarIndicatorLength();
}
#endregion
#region Data
private const string TrackTemplateName = "PART_Track";
private const string IndicatorTemplateName = "PART_Indicator";
private const string GlowingRectTemplateName = "PART_GlowRect";
private FrameworkElement _track;
private FrameworkElement _indicator;
private FrameworkElement _glow;
#endregion Data
#region DTypeThemeStyleKey
// Returns the DependencyObjectType for the registered ThemeStyleKey's default
// value. Controls will override this method to return approriate types.
internal override DependencyObjectType DTypeThemeStyleKey
{
get { return _dType; }
}
private static DependencyObjectType _dType;
#endregion DTypeThemeStyleKey
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Margins.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Drawing.Printing {
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization;
using System.Diagnostics;
using System;
using System.Runtime.InteropServices;
using System.Drawing;
using Microsoft.Win32;
using System.ComponentModel;
using System.Globalization;
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins"]/*' />
/// <devdoc>
/// <para>
/// Specifies the margins of a printed page.
/// </para>
/// </devdoc>
[
Serializable,
TypeConverterAttribute(typeof(MarginsConverter))
]
public class Margins : ICloneable {
private int left;
private int right;
private int top;
private int bottom;
[OptionalField]
private double doubleLeft;
[OptionalField]
private double doubleRight;
[OptionalField]
private double doubleTop;
[OptionalField]
private double doubleBottom;
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.Margins"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of a the <see cref='System.Drawing.Printing.Margins'/> class with one-inch margins.
/// </para>
/// </devdoc>
public Margins() : this(100, 100, 100, 100) {
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.Margins1"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of a the <see cref='System.Drawing.Printing.Margins'/> class with the specified left, right, top, and bottom
/// margins.
/// </para>
/// </devdoc>
public Margins(int left, int right, int top, int bottom) {
CheckMargin(left, "left");
CheckMargin(right, "right");
CheckMargin(top, "top");
CheckMargin(bottom, "bottom");
this.left = left;
this.right = right;
this.top = top;
this.bottom = bottom;
this.doubleLeft = (double)left;
this.doubleRight = (double)right;
this.doubleTop = (double)top;
this.doubleBottom = (double)bottom;
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.Left"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the left margin, in hundredths of an inch.
/// </para>
/// </devdoc>
public int Left {
get { return left;}
set {
CheckMargin(value, "Left");
left = value;
this.doubleLeft = (double)value;
}
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.Right"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the right margin, in hundredths of an inch.
/// </para>
/// </devdoc>
public int Right {
get { return right;}
set {
CheckMargin(value, "Right");
right = value;
this.doubleRight = (double)value;
}
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.Top"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the top margin, in hundredths of an inch.
/// </para>
/// </devdoc>
public int Top {
get { return top;}
set {
CheckMargin(value, "Top");
top = value;
this.doubleTop = (double)value;
}
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.Bottom"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the bottom margin, in hundredths of an inch.
/// </para>
/// </devdoc>
public int Bottom {
get { return bottom;}
set {
CheckMargin(value, "Bottom");
bottom = value;
this.doubleBottom = (double)value;
}
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.DoubleLeft"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the left margin with double value, in hundredths of an inch.
/// When use the setter, the ranger of setting double value should between
/// 0 to Int.MaxValue;
/// </para>
/// </devdoc>
internal double DoubleLeft {
get { return doubleLeft; }
set {
this.Left = (int)Math.Round(value);
doubleLeft = value;
}
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.DoubleRight"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the right margin with double value, in hundredths of an inch.
/// When use the setter, the ranger of setting double value should between
/// 0 to Int.MaxValue;
/// </para>
/// </devdoc>
internal double DoubleRight {
get { return doubleRight; }
set {
this.Right = (int)Math.Round(value);
doubleRight = value;
}
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.DoubleTop"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the top margin with double value, in hundredths of an inch.
/// When use the setter, the ranger of setting double value should between
/// 0 to Int.MaxValue;
/// </para>
/// </devdoc>
internal double DoubleTop {
get { return doubleTop; }
set {
this.Top = (int)Math.Round(value);
doubleTop = value;
}
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.DoubleBottom"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the bottom margin with double value, in hundredths of an inch.
/// When use the setter, the ranger of setting double value should between
/// 0 to Int.MaxValue;
/// </para>
/// </devdoc>
internal double DoubleBottom {
get { return doubleBottom; }
set {
this.Bottom = (int)Math.Round(value);
doubleBottom = value;
}
}
[OnDeserialized()]
private void OnDeserializedMethod(StreamingContext context) {
if (doubleLeft == 0 && left != 0) {
doubleLeft = (double)left;
}
if (doubleRight == 0 && right != 0) {
doubleRight = (double)right;
}
if (doubleTop == 0 && top != 0) {
doubleTop = (double)top;
}
if (doubleBottom == 0 && bottom != 0) {
doubleBottom = (double)bottom;
}
}
private void CheckMargin(int margin, string name) {
if (margin < 0)
throw new ArgumentException(SR.GetString(SR.InvalidLowBoundArgumentEx, name, margin, "0"));
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.Clone"]/*' />
/// <devdoc>
/// <para>
/// Retrieves a duplicate of this object, member by member.
/// </para>
/// </devdoc>
public object Clone() {
return MemberwiseClone();
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.Equals"]/*' />
/// <devdoc>
/// <para>
/// Compares this <see cref='System.Drawing.Printing.Margins'/> to a specified <see cref='System.Drawing.Printing.Margins'/> to see whether they
/// are equal.
/// </para>
/// </devdoc>
public override bool Equals(object obj) {
Margins margins = obj as Margins;
if (margins == this) return true;
if (margins == null) return false;
return margins.Left == this.Left
&& margins.Right == this.Right
&& margins.Top == this.Top
&& margins.Bottom == this.Bottom;
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.GetHashCode"]/*' />
/// <devdoc>
/// <para>
/// Calculates and retrieves a hash code based on the left, right, top, and bottom
/// margins.
/// </para>
/// </devdoc>
public override int GetHashCode() {
// return HashCodes.Combine(left, right, top, bottom);
uint left = (uint) this.Left;
uint right = (uint) this.Right;
uint top = (uint) this.Top;
uint bottom = (uint) this.Bottom;
uint result = left ^
((right << 13) | (right >> 19)) ^
((top << 26) | (top >> 6)) ^
((bottom << 7) | (bottom >> 25));
return unchecked((int) result);
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.operator=="]/*' />
/// <devdoc>
/// Tests whether two <see cref='System.Drawing.Printing.Margins'/> objects
/// are identical.
/// </devdoc>
public static bool operator ==(Margins m1, Margins m2) {
if (object.ReferenceEquals(m1, null) != object.ReferenceEquals(m2, null)) {
return false;
}
if (!object.ReferenceEquals(m1, null)) {
return m1.Left == m2.Left && m1.Top == m2.Top && m1.Right == m2.Right && m1.Bottom == m2.Bottom;
}
return true;
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.operator!="]/*' />
/// <devdoc>
/// <para>
/// Tests whether two <see cref='System.Drawing.Printing.Margins'/> objects are different.
/// </para>
/// </devdoc>
public static bool operator !=(Margins m1, Margins m2) {
return !(m1 == m2);
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.ToString"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Provides some interesting information for the Margins in
/// String form.
/// </para>
/// </devdoc>
public override string ToString() {
return "[Margins"
+ " Left=" + Left.ToString(CultureInfo.InvariantCulture)
+ " Right=" + Right.ToString(CultureInfo.InvariantCulture)
+ " Top=" + Top.ToString(CultureInfo.InvariantCulture)
+ " Bottom=" + Bottom.ToString(CultureInfo.InvariantCulture)
+ "]";
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Controls.AccessText.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Controls
{
public partial class AccessText : System.Windows.FrameworkElement, System.Windows.Markup.IAddChild
{
#region Methods and constructors
public AccessText()
{
}
protected sealed override System.Windows.Size ArrangeOverride(System.Windows.Size arrangeSize)
{
return default(System.Windows.Size);
}
protected override System.Windows.Media.Visual GetVisualChild(int index)
{
return default(System.Windows.Media.Visual);
}
protected sealed override System.Windows.Size MeasureOverride(System.Windows.Size constraint)
{
return default(System.Windows.Size);
}
void System.Windows.Markup.IAddChild.AddChild(Object value)
{
}
void System.Windows.Markup.IAddChild.AddText(string text)
{
}
#endregion
#region Properties and indexers
public char AccessKey
{
get
{
return default(char);
}
}
public System.Windows.Media.Brush Background
{
get
{
return default(System.Windows.Media.Brush);
}
set
{
}
}
public double BaselineOffset
{
get
{
return default(double);
}
set
{
}
}
public System.Windows.Media.FontFamily FontFamily
{
get
{
return default(System.Windows.Media.FontFamily);
}
set
{
}
}
public double FontSize
{
get
{
return default(double);
}
set
{
}
}
public System.Windows.FontStretch FontStretch
{
get
{
return default(System.Windows.FontStretch);
}
set
{
}
}
public System.Windows.FontStyle FontStyle
{
get
{
return default(System.Windows.FontStyle);
}
set
{
}
}
public System.Windows.FontWeight FontWeight
{
get
{
return default(System.Windows.FontWeight);
}
set
{
}
}
public System.Windows.Media.Brush Foreground
{
get
{
return default(System.Windows.Media.Brush);
}
set
{
}
}
public double LineHeight
{
get
{
return default(double);
}
set
{
}
}
public System.Windows.LineStackingStrategy LineStackingStrategy
{
get
{
return default(System.Windows.LineStackingStrategy);
}
set
{
}
}
internal protected override System.Collections.IEnumerator LogicalChildren
{
get
{
return default(System.Collections.IEnumerator);
}
}
public string Text
{
get
{
return default(string);
}
set
{
}
}
public System.Windows.TextAlignment TextAlignment
{
get
{
return default(System.Windows.TextAlignment);
}
set
{
}
}
public System.Windows.TextDecorationCollection TextDecorations
{
get
{
return default(System.Windows.TextDecorationCollection);
}
set
{
}
}
public System.Windows.Media.TextEffectCollection TextEffects
{
get
{
return default(System.Windows.Media.TextEffectCollection);
}
set
{
}
}
public System.Windows.TextTrimming TextTrimming
{
get
{
return default(System.Windows.TextTrimming);
}
set
{
}
}
public System.Windows.TextWrapping TextWrapping
{
get
{
return default(System.Windows.TextWrapping);
}
set
{
}
}
protected override int VisualChildrenCount
{
get
{
return default(int);
}
}
#endregion
#region Fields
public readonly static System.Windows.DependencyProperty BackgroundProperty;
public readonly static System.Windows.DependencyProperty BaselineOffsetProperty;
public readonly static System.Windows.DependencyProperty FontFamilyProperty;
public readonly static System.Windows.DependencyProperty FontSizeProperty;
public readonly static System.Windows.DependencyProperty FontStretchProperty;
public readonly static System.Windows.DependencyProperty FontStyleProperty;
public readonly static System.Windows.DependencyProperty FontWeightProperty;
public readonly static System.Windows.DependencyProperty ForegroundProperty;
public readonly static System.Windows.DependencyProperty LineHeightProperty;
public readonly static System.Windows.DependencyProperty LineStackingStrategyProperty;
public readonly static System.Windows.DependencyProperty TextAlignmentProperty;
public readonly static System.Windows.DependencyProperty TextDecorationsProperty;
public readonly static System.Windows.DependencyProperty TextEffectsProperty;
public readonly static System.Windows.DependencyProperty TextProperty;
public readonly static System.Windows.DependencyProperty TextTrimmingProperty;
public readonly static System.Windows.DependencyProperty TextWrappingProperty;
#endregion
}
}
| |
// 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 AutoGen;
// We were receiving an assert on IA64 because the code we were using to determine if a range
// check statically fails was invalid.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50606.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace AutoGen
{
public struct VType1
{
public sbyte f0;
public sbyte f1;
public VType1(int v)
{
f0 = ((sbyte)(v));
f1 = ((sbyte)(v));
}
}
public struct VType2
{
public long f0;
public long f1;
public VType2(int v)
{
f0 = ((long)(v));
f1 = ((long)(v));
}
}
public class Program
{
private int[] _callDepthTable;
private int[] _paramValueTable;
public Program()
{
_callDepthTable = new int[6];
_paramValueTable = new int[12];
int i;
for (i = 0; (i < _callDepthTable.Length); i = (i + 1))
{
_callDepthTable[i] = i;
}
for (i = 0; (i < _paramValueTable.Length); i = (i + 1))
{
_paramValueTable[i] = i;
}
}
public virtual VType1 Func1(VType1 p0, long p1, uint p2, VType2 p3)
{
if ((_callDepthTable[0] < 5))
{
_callDepthTable[0] = (_callDepthTable[0] + 1);
}
else
{
return p0;
}
int acc2 = 0;
int i2 = 0;
int[] arr02 = new int[5];
int[] arr12 = new int[5];
int[] arr22 = new int[5];
int[] arr32 = new int[5];
int[] arr42 = new int[5];
int[] arr52 = new int[5];
for (i2 = 0; (i2 < 5); i2 = (i2 + 1))
{
arr02[i2] = i2;
arr12[i2] = arr02[i2];
arr22[i2] = arr12[i2];
arr32[i2] = arr22[i2];
arr42[i2] = arr32[i2];
arr52[i2] = arr42[i2];
}
i2 = 0;
acc2 = 0;
for (; i2 < 5; i2++)
{
acc2 = (acc2 + arr02[i2]);
}
if ((acc2 == 0))
{
acc2 = arr02[10];
}
if ((acc2 == 1))
{
acc2 = arr12[10];
}
if ((acc2 == 2))
{
acc2 = arr22[10];
}
if ((acc2 == 3))
{
acc2 = arr32[10];
}
if ((acc2 == 4))
{
acc2 = arr42[10];
}
if ((acc2 == 5))
{
acc2 = arr52[10];
}
if ((acc2 == 6))
{
acc2 = arr02[10];
}
if ((acc2 == 7))
{
acc2 = arr12[10];
}
if ((acc2 == 8))
{
acc2 = arr22[10];
}
if ((acc2 == 9))
{
acc2 = arr32[10];
}
int i4 = 0;
int[] arr04 = new int[7];
int[] arr14 = new int[7];
int[] arr24 = new int[7];
int[] arr34 = new int[7];
int[] arr44 = new int[7];
for (i4 = 0; (i4 < 7); i4 = (i4 + 1))
{
arr04[i4] = i4;
arr14[i4] = arr04[i4];
arr24[i4] = arr14[i4];
arr34[i4] = arr24[i4];
arr44[i4] = arr34[i4];
}
int acc5 = 0;
int i5 = 0;
int[] arr05 = new int[3];
int[] arr15 = new int[3];
int[] arr25 = new int[3];
int[] arr35 = new int[3];
int[] arr45 = new int[3];
int[] arr55 = new int[3];
for (i5 = 0; (i5 < 3); i5 = (i5 + 1))
{
arr05[i5] = i5;
arr15[i5] = arr05[i5];
arr25[i5] = arr15[i5];
arr35[i5] = arr25[i5];
arr45[i5] = arr35[i5];
arr55[i5] = arr45[i5];
}
i5 = 0;
acc5 = 0;
for (; (i5 < 3); i5 = (i5 + 1))
{
acc5 = (acc5 + arr05[i5]);
for (; (i5 < 3); i5 = (i5 + 1))
{
acc5 = (acc5 + arr15[i5]);
for (; (i5 < 3); i5 = (i5 + 1))
{
acc5 = (acc5 + arr25[i5]);
for (; (i5 < 3); i5 = (i5 + 1))
{
acc5 = (acc5 + arr35[i5]);
for (; (i5 < 3); i5 = (i5 + 1))
{
acc5 = (acc5 + arr45[i5]);
for (; (i5 < 3); i5 = (i5 + 1))
{
acc5 = (acc5 + arr55[i5]);
}
}
}
}
}
}
if ((acc5 == 0))
{
acc5 = arr05[3];
}
if ((acc5 == 1))
{
acc5 = arr15[3];
}
if ((acc5 == 2))
{
acc5 = arr25[3];
}
if ((arr05.Length < 0))
{
goto L2;
}
acc5 = 0;
bool stop2 = (arr05.Length > 0);
for (i5 = 0; (stop2
&& (i5 <= arr05[i5])); i5 = (i5 + 1))
{
arr05[i5] = i5;
acc5 = (acc5 + arr05[i5]);
for (i5 = 0; (stop2
&& (i5 <= arr15[i5])); i5 = (i5 + 1))
{
acc5 = (acc5 + arr15[i5]);
i5 = arr15[i5];
for (i5 = 0; (stop2
&& (i5 <= arr25[i5])); i5 = (i5 + 1))
{
acc5 = (acc5 + arr25[i5]);
for (i5 = 0; (stop2
&& (i5 <= arr35[i5])); i5 = (i5 + 1))
{
acc5 = (acc5 + arr35[i5]);
for (i5 = 0; (stop2
&& (i5 <= arr45[i5])); i5 = (i5 + 1))
{
acc5 = (acc5 + arr45[i5]);
for (i5 = 0; (stop2
&& (i5 <= arr55[i5])); i5 = (i5 + 1))
{
acc5 = (acc5 + arr55[i5]);
i5 = arr55[i5];
stop2 = (i5 < 2);
}
stop2 = (i5 < 2);
}
stop2 = (i5 < 2);
}
stop2 = (i5 < 2);
}
stop2 = (i5 < 2);
}
stop2 = (i5 < 2);
}
L2:
i5 = 0;
int acc6 = 0;
int i6 = 0;
int[] arr6 = new int[4];
for (i6 = 0; i6 < 4; i6++)
{
arr6[i6] = i6;
}
i6 = 0;
acc6 = 0;
for (; i6 < 4; i6++)
{
acc6 = (acc6 + arr6[i6]);
}
if ((acc6 == 0))
{
acc6 = arr6[6];
}
return p0;
}
public virtual int Run()
{
try
{
this.Func1(new VType1(_paramValueTable[10]), ((long)(_paramValueTable[6])), ((uint)(_paramValueTable[5])), new VType2(_paramValueTable[11]));
}
catch (System.Exception exp)
{
System.Console.WriteLine("Application Check Failed!");
System.Console.WriteLine(exp);
return 1;
}
return 100;
}
public static int Main()
{
Program prog = new Program();
int rc = prog.Run();
System.Console.WriteLine("rc = {0}", rc);
return rc;
}
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.VisualStudio.LanguageServices.CSharp.Debugging;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Debugging
{
public class LocationInfoGetterTests
{
private async Task TestAsync(string markup, string expectedName, int expectedLineOffset, CSharpParseOptions parseOptions = null)
{
using (var workspace = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(new[] { markup }, parseOptions))
{
var testDocument = workspace.Documents.Single();
var position = testDocument.CursorPosition.Value;
var locationInfo = await LocationInfoGetter.GetInfoAsync(
workspace.CurrentSolution.Projects.Single().Documents.Single(),
position,
CancellationToken.None);
Assert.Equal(expectedName, locationInfo.Name);
Assert.Equal(expectedLineOffset, locationInfo.LineOffset);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestClass()
{
await TestAsync("class F$$oo { }", "Foo", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668), WorkItem(538415)]
public async Task TestMethod()
{
await TestAsync(
@"class Class
{
public static void Meth$$od()
{
}
}
", "Class.Method()", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668)]
public async Task TestNamespace()
{
await TestAsync(
@"namespace Namespace
{
class Class
{
void Method()
{
}$$
}
}", "Namespace.Class.Method()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668)]
public async Task TestDottedNamespace()
{
await TestAsync(
@"namespace Namespace.Another
{
class Class
{
void Method()
{
}$$
}
}", "Namespace.Another.Class.Method()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestNestedNamespace()
{
await TestAsync(
@"namespace Namespace
{
namespace Another
{
class Class
{
void Method()
{
}$$
}
}
}", "Namespace.Another.Class.Method()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668)]
public async Task TestNestedType()
{
await TestAsync(
@"class Outer
{
class Inner
{
void Quux()
{$$
}
}
}", "Outer.Inner.Quux()", 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668)]
public async Task TestPropertyGetter()
{
await TestAsync(
@"class Class
{
string Property
{
get
{
return null;$$
}
}
}", "Class.Property", 4);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668)]
public async Task TestPropertySetter()
{
await TestAsync(
@"class Class
{
string Property
{
get
{
return null;
}
set
{
string s = $$value;
}
}
}", "Class.Property", 9);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(538415)]
public async Task TestField()
{
await TestAsync(
@"class Class
{
int fi$$eld;
}", "Class.field", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(543494)]
public async Task TestLambdaInFieldInitializer()
{
await TestAsync(
@"class Class
{
Action<int> a = b => { in$$t c; };
}", "Class.a", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(543494)]
public async Task TestMultipleFields()
{
await TestAsync(
@"class Class
{
int a1, a$$2;
}", "Class.a2", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestConstructor()
{
await TestAsync(
@"class C1
{
C1()
{
$$}
}
", "C1.C1()", 3);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestDestructor()
{
await TestAsync(
@"class C1
{
~C1()
{
$$}
}
", "C1.~C1()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestOperator()
{
await TestAsync(
@"namespace N1
{
class C1
{
public static int operator +(C1 x, C1 y)
{
$$return 42;
}
}
}
", "N1.C1.+(C1 x, C1 y)", 2); // Old implementation reports "operator +" (rather than "+")...
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestConversionOperator()
{
await TestAsync(
@"namespace N1
{
class C1
{
public static explicit operator N1.C2(N1.C1 x)
{
$$return null;
}
}
class C2
{
}
}
", "N1.C1.N1.C2(N1.C1 x)", 2); // Old implementation reports "explicit operator N1.C2" (rather than "N1.C2")...
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestEvent()
{
await TestAsync(
@"class C1
{
delegate void D1();
event D1 e1$$;
}
", "C1.e1", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TextExplicitInterfaceImplementation()
{
await TestAsync(
@"interface I1
{
void M1();
}
class C1
{
void I1.M1()
{
$$}
}
", "C1.M1()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TextIndexer()
{
await TestAsync(
@"class C1
{
C1 this[int x]
{
get
{
$$return null;
}
}
}
", "C1.this[int x]", 4);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestParamsParameter()
{
await TestAsync(
@"class C1
{
void M1(params int[] x) { $$ }
}
", "C1.M1(params int[] x)", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestArglistParameter()
{
await TestAsync(
@"class C1
{
void M1(__arglist) { $$ }
}
", "C1.M1(__arglist)", 0); // Old implementation does not show "__arglist"...
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestRefAndOutParameters()
{
await TestAsync(
@"class C1
{
void M1( ref int x, out int y )
{
$$y = x;
}
}
", "C1.M1( ref int x, out int y )", 2); // Old implementation did not show extra spaces around the parameters...
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestOptionalParameters()
{
await TestAsync(
@"class C1
{
void M1(int x =1)
{
$$y = x;
}
}
", "C1.M1(int x =1)", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestExtensionMethod()
{
await TestAsync(
@"static class C1
{
static void M1(this int x)
{
}$$
}
", "C1.M1(this int x)", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestGenericType()
{
await TestAsync(
@"class C1<T, U>
{
static void M1() { $$ }
}
", "C1.M1()", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestGenericMethod()
{
await TestAsync(
@"class C1<T, U>
{
static void M1<V>() { $$ }
}
", "C1.M1()", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestGenericParameters()
{
await TestAsync(
@"class C1<T, U>
{
static void M1<V>(C1<int, V> x, V y) { $$ }
}
", "C1.M1(C1<int, V> x, V y)", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestMissingNamespace()
{
await TestAsync(
@"{
class Class
{
int a1, a$$2;
}
}", "Class.a2", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestMissingNamespaceName()
{
await TestAsync(
@"namespace
{
class C1
{
int M1()
$${
}
}
}", "?.C1.M1()", 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestMissingClassName()
{
await TestAsync(
@"namespace N1
class
{
int M1()
$${
}
}
}", "N1.M1()", 1); // Old implementation displayed "N1.?.M1", but we don't see a class declaration in the syntax tree...
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestMissingMethodName()
{
await TestAsync(
@"namespace N1
{
class C1
{
static void (int x)
{
$$}
}
}", "N1.C1", 4);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestMissingParameterList()
{
await TestAsync(
@"namespace N1
{
class C1
{
static void M1
{
$$}
}
}", "N1.C1.M1", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TopLevelField()
{
await TestAsync(
@"$$int f1;
", "f1", 0, new CSharpParseOptions(kind: SourceCodeKind.Script));
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TopLevelMethod()
{
await TestAsync(
@"int M1(int x)
{
$$}
", "M1(int x)", 2, new CSharpParseOptions(kind: SourceCodeKind.Script));
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TopLevelStatement()
{
await TestAsync(
@"
$$System.Console.WriteLine(""Hello"")
", null, 0, new CSharpParseOptions(kind: SourceCodeKind.Script));
}
}
}
| |
// 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.IO;
using CultureInfo = System.Globalization.CultureInfo;
using SuppressMessageAttribute = System.Diagnostics.CodeAnalysis.SuppressMessageAttribute;
namespace System.Xml.Linq
{
/// <summary>
/// Represents an XML attribute.
/// </summary>
/// <remarks>
/// An XML attribute is a name/value pair associated with an XML element.
/// </remarks>
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Reviewed.")]
public class XAttribute : XObject
{
static IEnumerable<XAttribute> emptySequence;
/// <summary>
/// Gets an empty collection of attributes.
/// </summary>
public static IEnumerable<XAttribute> EmptySequence
{
get
{
if (emptySequence == null) emptySequence = new XAttribute[0];
return emptySequence;
}
}
internal XAttribute next;
internal XName name;
internal string value;
/// <overloads>
/// Initializes a new instance of the <see cref="XAttribute"/> class.
/// </overloads>
/// <summary>
/// Initializes a new instance of the <see cref="XAttribute"/> class from
/// the specified name and value.
/// </summary>
/// <param name="name">
/// The name of the attribute.
/// </param>
/// <param name="value">
/// The value of the attribute.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown if the passed in name or value are null.
/// </exception>
public XAttribute(XName name, object value)
{
if (name == null) throw new ArgumentNullException("name");
if (value == null) throw new ArgumentNullException("value");
string s = XContainer.GetStringValue(value);
ValidateAttribute(name, s);
this.name = name;
this.value = s;
}
/// <summary>
/// Initializes an instance of the XAttribute class
/// from another XAttribute object.
/// </summary>
/// <param name="other"><see cref="XAttribute"/> object to copy from.</param>
/// <exception cref="ArgumentNullException">
/// Thrown if the specified <see cref="XAttribute"/> is null.
/// </exception>
public XAttribute(XAttribute other)
{
if (other == null) throw new ArgumentNullException("other");
name = other.name;
value = other.value;
}
/// <summary>
/// Gets a value indicating if this attribute is a namespace declaration.
/// </summary>
public bool IsNamespaceDeclaration
{
get
{
string namespaceName = name.NamespaceName;
if (namespaceName.Length == 0)
{
return name.LocalName == "xmlns";
}
return (object)namespaceName == (object)XNamespace.xmlnsPrefixNamespace;
}
}
/// <summary>
/// Gets the name of this attribute.
/// </summary>
public XName Name
{
get { return name; }
}
/// <summary>
/// Gets the next attribute of the parent element.
/// </summary>
/// <remarks>
/// If this attribute does not have a parent, or if there is no next attribute,
/// then this property returns null.
/// </remarks>
public XAttribute NextAttribute
{
get { return parent != null && ((XElement)parent).lastAttr != this ? next : null; }
}
/// <summary>
/// Gets the node type for this node.
/// </summary>
/// <remarks>
/// This property will always return XmlNodeType.Attribute.
/// </remarks>
public override XmlNodeType NodeType
{
get
{
return XmlNodeType.Attribute;
}
}
/// <summary>
/// Gets the previous attribute of the parent element.
/// </summary>
/// <remarks>
/// If this attribute does not have a parent, or if there is no previous attribute,
/// then this property returns null.
/// </remarks>
public XAttribute PreviousAttribute
{
get
{
if (parent == null) return null;
XAttribute a = ((XElement)parent).lastAttr;
while (a.next != this)
{
a = a.next;
}
return a != ((XElement)parent).lastAttr ? a : null;
}
}
/// <summary>
/// Gets or sets the value of this attribute.
/// </summary>
/// <exception cref="ArgumentNullException">
/// Thrown if the value set is null.
/// </exception>
public string Value
{
get
{
return value;
}
set
{
if (value == null) throw new ArgumentNullException("value");
ValidateAttribute(name, value);
bool notify = NotifyChanging(this, XObjectChangeEventArgs.Value);
this.value = value;
if (notify) NotifyChanged(this, XObjectChangeEventArgs.Value);
}
}
/// <summary>
/// Deletes this XAttribute.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if the parent element is null.
/// </exception>
public void Remove()
{
if (parent == null) throw new InvalidOperationException(SR.InvalidOperation_MissingParent);
((XElement)parent).RemoveAttribute(this);
}
/// <summary>
/// Sets the value of this <see cref="XAttribute"/>.
/// <seealso cref="XElement.SetValue"/>
/// <seealso cref="XElement.SetAttributeValue"/>
/// <seealso cref="XElement.SetElementValue"/>
/// </summary>
/// <param name="value">
/// The value to assign to this attribute. The value is converted to its string
/// representation and assigned to the <see cref="Value"/> property.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown if the specified value is null.
/// </exception>
public void SetValue(object value)
{
if (value == null) throw new ArgumentNullException("value");
Value = XContainer.GetStringValue(value);
}
/// <summary>
/// Override for <see cref="ToString()"/> on <see cref="XAttribute"/>
/// </summary>
/// <returns>XML text representation of an attribute and its value</returns>
public override string ToString()
{
using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
{
XmlWriterSettings ws = new XmlWriterSettings();
ws.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlWriter w = XmlWriter.Create(sw, ws))
{
w.WriteAttributeString(GetPrefixOfNamespace(name.Namespace), name.LocalName, name.NamespaceName, value);
}
return sw.ToString().Trim();
}
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to a <see cref="string"/>.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="string"/>.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as a <see cref="string"/>.
/// </returns>
[CLSCompliant(false)]
public static explicit operator string (XAttribute attribute)
{
if (attribute == null) return null;
return attribute.value;
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to a <see cref="bool"/>.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="bool"/>.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as a <see cref="bool"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown if the specified attribute is null.
/// </exception>
[CLSCompliant(false)]
public static explicit operator bool (XAttribute attribute)
{
if (attribute == null) throw new ArgumentNullException("attribute");
return XmlConvert.ToBoolean(XHelper.ToLower_InvariantCulture(attribute.value));
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to a <see cref="bool"/>?.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="bool"/>?. Can be null.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as a <see cref="bool"/>?.
/// </returns>
[CLSCompliant(false)]
public static explicit operator bool? (XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToBoolean(XHelper.ToLower_InvariantCulture(attribute.value));
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to an <see cref="int"/>.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="int"/>.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as an <see cref="int"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown if the specified attribute is null.
/// </exception>
[CLSCompliant(false)]
public static explicit operator int (XAttribute attribute)
{
if (attribute == null) throw new ArgumentNullException("attribute");
return XmlConvert.ToInt32(attribute.value);
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to an <see cref="int"/>?.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="int"/>?. Can be null.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as an <see cref="int"/>?.
/// </returns>
[CLSCompliant(false)]
public static explicit operator int? (XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToInt32(attribute.value);
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to an <see cref="uint"/>.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="uint"/>.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as an <see cref="uint"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown if the specified attribute is null.
/// </exception>
[CLSCompliant(false)]
public static explicit operator uint (XAttribute attribute)
{
if (attribute == null) throw new ArgumentNullException("attribute");
return XmlConvert.ToUInt32(attribute.value);
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to an <see cref="uint"/>?.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="uint"/>?. Can be null.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as an <see cref="uint"/>?.
/// </returns>
[CLSCompliant(false)]
public static explicit operator uint? (XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToUInt32(attribute.value);
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to a <see cref="long"/>.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="long"/>.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as a <see cref="long"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown if the specified attribute is null.
/// </exception>
[CLSCompliant(false)]
public static explicit operator long (XAttribute attribute)
{
if (attribute == null) throw new ArgumentNullException("attribute");
return XmlConvert.ToInt64(attribute.value);
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to a <see cref="long"/>?.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="long"/>?. Can be null.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as a <see cref="long"/>?.
/// </returns>
[CLSCompliant(false)]
public static explicit operator long? (XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToInt64(attribute.value);
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to an <see cref="ulong"/>.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="ulong"/>.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as an <see cref="ulong"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown if the specified attribute is null.
/// </exception>
[CLSCompliant(false)]
public static explicit operator ulong (XAttribute attribute)
{
if (attribute == null) throw new ArgumentNullException("attribute");
return XmlConvert.ToUInt64(attribute.value);
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to an <see cref="ulong"/>?.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="ulong"/>?. Can be null.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as an <see cref="ulong"/>?.
/// </returns>
[CLSCompliant(false)]
public static explicit operator ulong? (XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToUInt64(attribute.value);
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to a <see cref="float"/>.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="float"/>.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as a <see cref="float"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown if the specified attribute is null.
/// </exception>
[CLSCompliant(false)]
public static explicit operator float (XAttribute attribute)
{
if (attribute == null) throw new ArgumentNullException("attribute");
return XmlConvert.ToSingle(attribute.value);
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to a <see cref="float"/>?.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="float"/>?. Can be null.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as a <see cref="float"/>?.
/// </returns>
[CLSCompliant(false)]
public static explicit operator float? (XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToSingle(attribute.value);
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to a <see cref="double"/>.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="double"/>.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as a <see cref="double"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown if the specified attribute is null.
/// </exception>
[CLSCompliant(false)]
public static explicit operator double (XAttribute attribute)
{
if (attribute == null) throw new ArgumentNullException("attribute");
return XmlConvert.ToDouble(attribute.value);
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to a <see cref="double"/>?.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="double"/>?. Can be null.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as a <see cref="double"/>?.
/// </returns>
[CLSCompliant(false)]
public static explicit operator double? (XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToDouble(attribute.value);
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to a <see cref="decimal"/>.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="decimal"/>.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as a <see cref="decimal"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown if the specified attribute is null.
/// </exception>
[CLSCompliant(false)]
public static explicit operator decimal (XAttribute attribute)
{
if (attribute == null) throw new ArgumentNullException("attribute");
return XmlConvert.ToDecimal(attribute.value);
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to a <see cref="decimal"/>?.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="decimal"/>?. Can be null.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as a <see cref="decimal"/>?.
/// </returns>
[CLSCompliant(false)]
public static explicit operator decimal? (XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToDecimal(attribute.value);
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to a <see cref="DateTime"/>.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="DateTime"/>.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as a <see cref="DateTime"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown if the specified attribute is null.
/// </exception>
[CLSCompliant(false)]
public static explicit operator DateTime(XAttribute attribute)
{
if (attribute == null) throw new ArgumentNullException("attribute");
return DateTime.Parse(attribute.value, CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind);
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to a <see cref="DateTime"/>?.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="DateTime"/>?. Can be null.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as a <see cref="DateTime"/>?.
/// </returns>
[CLSCompliant(false)]
public static explicit operator DateTime? (XAttribute attribute)
{
if (attribute == null) return null;
return DateTime.Parse(attribute.value, CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind);
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to a <see cref="DateTimeOffset"/>.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="DateTimeOffset"/>.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as a <see cref="DateTimeOffset"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown if the specified attribute is null.
/// </exception>
[CLSCompliant(false)]
public static explicit operator DateTimeOffset(XAttribute attribute)
{
if (attribute == null) throw new ArgumentNullException("attribute");
return XmlConvert.ToDateTimeOffset(attribute.value);
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to a <see cref="DateTimeOffset"/>?.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="DateTimeOffset"/>?. Can be null.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as a <see cref="DateTimeOffset"/>?.
/// </returns>
[CLSCompliant(false)]
public static explicit operator DateTimeOffset? (XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToDateTimeOffset(attribute.value);
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to a <see cref="TimeSpan"/>.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="TimeSpan"/>.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as a <see cref="TimeSpan"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown if the specified attribute is null.
/// </exception>
[CLSCompliant(false)]
public static explicit operator TimeSpan(XAttribute attribute)
{
if (attribute == null) throw new ArgumentNullException("attribute");
return XmlConvert.ToTimeSpan(attribute.value);
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to a <see cref="TimeSpan"/>?.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="TimeSpan"/>?. Can be null.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as a <see cref="TimeSpan"/>?.
/// </returns>
[CLSCompliant(false)]
public static explicit operator TimeSpan? (XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToTimeSpan(attribute.value);
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to a <see cref="Guid"/>.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="Guid"/>.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as a <see cref="Guid"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown if the specified attribute is null.
/// </exception>
[CLSCompliant(false)]
public static explicit operator Guid(XAttribute attribute)
{
if (attribute == null) throw new ArgumentNullException("attribute");
return XmlConvert.ToGuid(attribute.value);
}
/// <summary>
/// Cast the value of this <see cref="XAttribute"/> to a <see cref="Guid"/>?.
/// </summary>
/// <param name="attribute">
/// The <see cref="XAttribute"/> to cast to <see cref="Guid"/>?. Can be null.
/// </param>
/// <returns>
/// The content of this <see cref="XAttribute"/> as a <see cref="Guid"/>?.
/// </returns>
[CLSCompliant(false)]
public static explicit operator Guid? (XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToGuid(attribute.value);
}
internal int GetDeepHashCode()
{
return name.GetHashCode() ^ value.GetHashCode();
}
internal string GetPrefixOfNamespace(XNamespace ns)
{
string namespaceName = ns.NamespaceName;
if (namespaceName.Length == 0) return string.Empty;
if (parent != null) return ((XElement)parent).GetPrefixOfNamespace(ns);
if ((object)namespaceName == (object)XNamespace.xmlPrefixNamespace) return "xml";
if ((object)namespaceName == (object)XNamespace.xmlnsPrefixNamespace) return "xmlns";
return null;
}
static void ValidateAttribute(XName name, string value)
{
// The following constraints apply for namespace declarations:
string namespaceName = name.NamespaceName;
if ((object)namespaceName == (object)XNamespace.xmlnsPrefixNamespace)
{
if (value.Length == 0)
{
// The empty namespace name can only be declared by
// the default namespace declaration
throw new ArgumentException(SR.Format(SR.Argument_NamespaceDeclarationPrefixed, name.LocalName));
}
else if (value == XNamespace.xmlPrefixNamespace)
{
// 'http://www.w3.org/XML/1998/namespace' can only
// be declared by the 'xml' prefix namespace declaration.
if (name.LocalName != "xml") throw new ArgumentException(SR.Argument_NamespaceDeclarationXml);
}
else if (value == XNamespace.xmlnsPrefixNamespace)
{
// 'http://www.w3.org/2000/xmlns/' must not be declared
// by any namespace declaration.
throw new ArgumentException(SR.Argument_NamespaceDeclarationXmlns);
}
else
{
string localName = name.LocalName;
if (localName == "xml")
{
// No other namespace name can be declared by the 'xml'
// prefix namespace declaration.
throw new ArgumentException(SR.Argument_NamespaceDeclarationXml);
}
else if (localName == "xmlns")
{
// The 'xmlns' prefix must not be declared.
throw new ArgumentException(SR.Argument_NamespaceDeclarationXmlns);
}
}
}
else if (namespaceName.Length == 0 && name.LocalName == "xmlns")
{
if (value == XNamespace.xmlPrefixNamespace)
{
// 'http://www.w3.org/XML/1998/namespace' can only
// be declared by the 'xml' prefix namespace declaration.
throw new ArgumentException(SR.Argument_NamespaceDeclarationXml);
}
else if (value == XNamespace.xmlnsPrefixNamespace)
{
// 'http://www.w3.org/2000/xmlns/' must not be declared
// by any namespace declaration.
throw new ArgumentException(SR.Argument_NamespaceDeclarationXmlns);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AdminSite.Models;
using AdminSite.Utilities;
using InsurgenceData;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace AdminSite.Database
{
internal static class DbTradelog
{
public static async Task<List<Trade>> GetUserTradeLog(uint userId)
{
using var conn = new OpenConnection();
if (conn.IsConnected)
{
const string com =
"SELECT * FROM newtradelog WHERE @parameter IN (user1_id, user2_id) ORDER BY i DESC LIMIT 0, 100";
var m = new MySqlCommand(com, conn.Connection);
m.Parameters.AddWithValue("parameter", userId);
var l = new List<Trade>();
using (var r = await m.ExecuteReaderAsync())
{
while (await r.ReadAsync())
{
var t = new Trade {Id = (int) r["i"]};
var u1 = (uint)r["user1_id"];
if (u1 == userId)
{
t.User1 = (string)r["user1"];
t.User2 = (string)r["user2"];
t.Pokemon1 = Deserializer.DeserializePokemon((string)r["pokemon1"]);
t.Pokemon2 = Deserializer.DeserializePokemon((string)r["pokemon2"]);
}
else
{
t.User2 = (string)r["user1"];
t.User1 = (string)r["user2"];
t.Pokemon2 = Deserializer.DeserializePokemon((string)r["pokemon1"]);
t.Pokemon1 = Deserializer.DeserializePokemon((string)r["pokemon2"]);
}
l.Add(t);
}
}
conn.Close();
return l;
}
conn.Close();
return new List<Trade>();
}
public static async Task<List<WonderTrade>> GetUserWonderTradeLog(string username, uint userId)
{
using var conn = new OpenConnection();
if (conn.IsConnected)
{
const string com =
"SELECT * FROM wondertradelog WHERE user_id = @parameter ORDER BY id DESC LIMIT 0, 100";
var m = new MySqlCommand(com, conn.Connection);
m.Parameters.AddWithValue("parameter", userId);
var l = new List<WonderTrade>();
using (var r = await m.ExecuteReaderAsync())
{
while (await r.ReadAsync())
{
var t = new WonderTrade
{
Id = (uint) r["id"],
Pokemon = Deserializer.DeserializePokemon((string) r["pokemon"]),
User = username,
Date = (DateTime) r["time"]
};
l.Add(t);
}
}
conn.Close();
return l;
}
conn.Close();
return new List<WonderTrade>();
}
public static async Task<List<Trade>> GetTradeLog(uint startIndex)
{
using var conn = new OpenConnection();
if (conn.IsConnected)
{
const string c = "SELECT * FROM newtradelog ORDER BY i DESC LIMIT @val, 100";
var m = new MySqlCommand(c, conn.Connection);
m.Parameters.AddWithValue("val", startIndex);
var l = new List<Trade>();
using (var r = await m.ExecuteReaderAsync())
{
while (await r.ReadAsync())
{
var t = new Trade
{
Id = (int) r["i"],
Date = (DateTime) r["time"],
User1 = (string) r["user1"],
User2 = (string) r["user2"],
Pokemon1 = Deserializer.DeserializePokemon((string) r["pokemon1"]),
Pokemon2 = Deserializer.DeserializePokemon((string) r["pokemon2"]),
};
l.Add(t);
}
}
conn.Close();
return l;
}
conn.Close();
return new List<Trade>();
}
public static void HandleDeserializationError(object sender, ErrorEventArgs errorArgs)
{
var currentError = errorArgs.ErrorContext.Error.Message;
Console.WriteLine(currentError);
errorArgs.ErrorContext.Handled = true;
}
public static async Task<List<WonderTrade>> GetWonderTradeLog(uint startIndex)
{
using var conn = new OpenConnection();
if (!conn.IsConnected)
{
conn.Close();
return new List<WonderTrade>();
}
const string command = "SELECT * FROM wondertradelog ORDER BY id DESC LIMIT @val, 100";
var m = new MySqlCommand(command, conn.Connection);
m.Parameters.AddWithValue("val", startIndex);
var l = new List<WonderTrade>();
using (var r = await m.ExecuteReaderAsync())
{
while (r.Read())
{
var t = new WonderTrade
{
Id = (uint)r["id"],
Date = (DateTime) r["time"],
User = (string) r["username"],
Pokemon = Deserializer.DeserializePokemon((string) r["pokemon"])
};
l.Add(t);
}
}
conn.Close();
return l;
}
public static async Task<Trade> GetTrade(uint i)
{
using var conn = new OpenConnection();
if (!conn.IsConnected)
{
conn.Close();
return new Trade();
}
const string c = "SELECT * FROM newtradelog WHERE i = @index";
var m = new MySqlCommand(c, conn.Connection);
m.Parameters.AddWithValue("index", i);
var t = new Trade();
using (var r = await m.ExecuteReaderAsync())
{
while (r.Read())
{
t.Id = (int)r["i"];
t.User1 = (string)r["user1"];
t.User2 = (string)r["user2"];
t.Pokemon1 = Deserializer.DeserializePokemon((string)r["pokemon1"]);
t.Pokemon2 = Deserializer.DeserializePokemon((string)r["pokemon2"]);
t.Date = (DateTime) r["time"];
}
}
conn.Close();
return t;
}
public static async Task<WonderTrade> GetWonderTrade(uint i)
{
using var conn = new OpenConnection();
if (!conn.IsConnected)
{
conn.Close();
return new WonderTrade();
}
const string c = "SELECT * FROM wondertradelog WHERE id = @index";
var m = new MySqlCommand(c, conn.Connection);
m.Parameters.AddWithValue("index", i);
var t = new WonderTrade();
using (var r = await m.ExecuteReaderAsync())
{
while (r.Read())
{
t.Id = (uint)r["id"];
t.User = (string)r["username"];
t.Pokemon = Deserializer.DeserializePokemon((string)r["pokemon"]);
t.Date = (DateTime) r["time"];
}
}
conn.Close();
return t;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net
{
internal sealed unsafe class HttpRequestStream : Stream
{
private readonly HttpListenerContext _httpContext;
private uint _dataChunkOffset;
private int _dataChunkIndex;
private bool _closed;
internal const int MaxReadSize = 0x20000; //http.sys recommends we limit reads to 128k
private bool _inOpaqueMode;
internal HttpRequestStream(HttpListenerContext httpContext)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"httpContextt:{httpContext}");
_httpContext = httpContext;
}
public override bool CanSeek
{
get
{
return false;
}
}
public override bool CanWrite
{
get
{
return false;
}
}
public override bool CanRead
{
get
{
return true;
}
}
internal bool Closed
{
get
{
return _closed;
}
}
internal bool BufferedDataChunksAvailable
{
get
{
return _dataChunkIndex > -1;
}
}
// This low level API should only be consumed if the caller can make sure that the state is not corrupted
// WebSocketHttpListenerDuplexStream (a duplex wrapper around HttpRequestStream/HttpResponseStream)
// is currenlty the only consumer of this API
internal HttpListenerContext InternalHttpContext
{
get
{
return _httpContext;
}
}
public override void Flush()
{
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
public override long Length
{
get
{
throw new NotSupportedException(SR.net_noseek);
}
}
public override long Position
{
get
{
throw new NotSupportedException(SR.net_noseek);
}
set
{
throw new NotSupportedException(SR.net_noseek);
}
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException(SR.net_noseek);
}
public override void SetLength(long value)
{
throw new NotSupportedException(SR.net_noseek);
}
public override int Read(byte[] buffer, int offset, int size)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this);
NetEventSource.Info(this, "size:" + size + " offset:" + offset);
}
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (size < 0 || size > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
if (size == 0 || _closed)
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, "dataRead:0");
return 0;
}
uint dataRead = 0;
if (_dataChunkIndex != -1)
{
dataRead = Interop.HttpApi.GetChunks(_httpContext.Request.RequestBuffer, _httpContext.Request.OriginalBlobAddress, ref _dataChunkIndex, ref _dataChunkOffset, buffer, offset, size);
}
if (_dataChunkIndex == -1 && dataRead < size)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "size:" + size + " offset:" + offset);
uint statusCode = 0;
uint extraDataRead = 0;
offset += (int)dataRead;
size -= (int)dataRead;
//the http.sys team recommends that we limit the size to 128kb
if (size > MaxReadSize)
{
size = MaxReadSize;
}
fixed (byte* pBuffer = buffer)
{
// issue unmanaged blocking call
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Calling Interop.HttpApi.HttpReceiveRequestEntityBody");
uint flags = 0;
if (!_inOpaqueMode)
{
flags = (uint)Interop.HttpApi.HTTP_FLAGS.HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY;
}
statusCode =
Interop.HttpApi.HttpReceiveRequestEntityBody(
_httpContext.RequestQueueHandle,
_httpContext.RequestId,
flags,
(void*)(pBuffer + offset),
(uint)size,
out extraDataRead,
null);
dataRead += extraDataRead;
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Call to Interop.HttpApi.HttpReceiveRequestEntityBody returned:" + statusCode + " dataRead:" + dataRead);
}
if (statusCode != Interop.HttpApi.ERROR_SUCCESS && statusCode != Interop.HttpApi.ERROR_HANDLE_EOF)
{
Exception exception = new HttpListenerException((int)statusCode);
if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception.ToString());
throw exception;
}
UpdateAfterRead(statusCode, dataRead);
}
if (NetEventSource.IsEnabled)
{
NetEventSource.DumpBuffer(this, buffer, offset, (int)dataRead);
NetEventSource.Info(this, "returning dataRead:" + dataRead);
NetEventSource.Exit(this, "dataRead:" + dataRead);
}
return (int)dataRead;
}
private void UpdateAfterRead(uint statusCode, uint dataRead)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "statusCode:" + statusCode + " _closed:" + _closed);
if (statusCode == Interop.HttpApi.ERROR_HANDLE_EOF || dataRead == 0)
{
Close();
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "statusCode:" + statusCode + " _closed:" + _closed);
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "buffer.Length:" + buffer.Length + " size:" + size + " offset:" + offset);
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (size < 0 || size > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
if (size == 0 || _closed)
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
HttpRequestStreamAsyncResult result = new HttpRequestStreamAsyncResult(this, state, callback);
result.InvokeCallback((uint)0);
return result;
}
HttpRequestStreamAsyncResult asyncResult = null;
uint dataRead = 0;
if (_dataChunkIndex != -1)
{
dataRead = Interop.HttpApi.GetChunks(_httpContext.Request.RequestBuffer, _httpContext.Request.OriginalBlobAddress, ref _dataChunkIndex, ref _dataChunkOffset, buffer, offset, size);
if (_dataChunkIndex != -1 && dataRead == size)
{
asyncResult = new HttpRequestStreamAsyncResult(_httpContext.RequestQueueBoundHandle, this, state, callback, buffer, offset, (uint)size, 0);
asyncResult.InvokeCallback(dataRead);
}
}
if (_dataChunkIndex == -1 && dataRead < size)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "size:" + size + " offset:" + offset);
uint statusCode = 0;
offset += (int)dataRead;
size -= (int)dataRead;
//the http.sys team recommends that we limit the size to 128kb
if (size > MaxReadSize)
{
size = MaxReadSize;
}
asyncResult = new HttpRequestStreamAsyncResult(_httpContext.RequestQueueBoundHandle, this, state, callback, buffer, offset, (uint)size, dataRead);
uint bytesReturned;
try
{
fixed (byte* pBuffer = buffer)
{
// issue unmanaged blocking call
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Calling Interop.HttpApi.HttpReceiveRequestEntityBody");
uint flags = 0;
if (!_inOpaqueMode)
{
flags = (uint)Interop.HttpApi.HTTP_FLAGS.HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY;
}
statusCode =
Interop.HttpApi.HttpReceiveRequestEntityBody(
_httpContext.RequestQueueHandle,
_httpContext.RequestId,
flags,
asyncResult._pPinnedBuffer,
(uint)size,
out bytesReturned,
asyncResult._pOverlapped);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Call to Interop.HttpApi.HttpReceiveRequestEntityBody returned:" + statusCode + " dataRead:" + dataRead);
}
}
catch (Exception e)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, e.ToString());
asyncResult.InternalCleanup();
throw;
}
if (statusCode != Interop.HttpApi.ERROR_SUCCESS && statusCode != Interop.HttpApi.ERROR_IO_PENDING)
{
asyncResult.InternalCleanup();
if (statusCode == Interop.HttpApi.ERROR_HANDLE_EOF)
{
asyncResult = new HttpRequestStreamAsyncResult(this, state, callback, dataRead);
asyncResult.InvokeCallback((uint)0);
}
else
{
Exception exception = new HttpListenerException((int)statusCode);
if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception.ToString());
asyncResult.InternalCleanup();
throw exception;
}
}
else if (statusCode == Interop.HttpApi.ERROR_SUCCESS &&
HttpListener.SkipIOCPCallbackOnSuccess)
{
// IO operation completed synchronously - callback won't be called to signal completion.
asyncResult.IOCompleted(statusCode, bytesReturned);
}
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
return asyncResult;
}
public override int EndRead(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this);
NetEventSource.Info(this, $"asyncResult: {asyncResult}");
}
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
HttpRequestStreamAsyncResult castedAsyncResult = asyncResult as HttpRequestStreamAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (castedAsyncResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndRead)));
}
castedAsyncResult.EndCalled = true;
// wait & then check for errors
object returnValue = castedAsyncResult.InternalWaitForCompletion();
Exception exception = returnValue as Exception;
if (exception != null)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Info(this, "Rethrowing exception:" + exception);
NetEventSource.Error(this, exception.ToString());
}
throw exception;
}
uint dataRead = (uint)returnValue;
UpdateAfterRead((uint)castedAsyncResult.ErrorCode, dataRead);
if (NetEventSource.IsEnabled)
{
NetEventSource.Info(this, $"returnValue:{returnValue}");
NetEventSource.Exit(this);
}
return (int)dataRead + (int)castedAsyncResult._dataAlreadyRead;
}
public override void Write(byte[] buffer, int offset, int size)
{
throw new InvalidOperationException(SR.net_readonlystream);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
{
throw new InvalidOperationException(SR.net_readonlystream);
}
public override void EndWrite(IAsyncResult asyncResult)
{
throw new InvalidOperationException(SR.net_readonlystream);
}
protected override void Dispose(bool disposing)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "_closed:" + _closed);
_closed = true;
}
finally
{
base.Dispose(disposing);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
internal void SwitchToOpaqueMode()
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this);
_inOpaqueMode = true;
}
// This low level API should only be consumed if the caller can make sure that the state is not corrupted
// WebSocketHttpListenerDuplexStream (a duplex wrapper around HttpRequestStream/HttpResponseStream)
// is currenlty the only consumer of this API
internal uint GetChunks(byte[] buffer, int offset, int size)
{
return Interop.HttpApi.GetChunks(_httpContext.Request.RequestBuffer,
_httpContext.Request.OriginalBlobAddress,
ref _dataChunkIndex,
ref _dataChunkOffset,
buffer,
offset,
size);
}
private sealed unsafe class HttpRequestStreamAsyncResult : LazyAsyncResult
{
private ThreadPoolBoundHandle _boundHandle;
internal NativeOverlapped* _pOverlapped;
internal void* _pPinnedBuffer;
internal uint _dataAlreadyRead = 0;
private static readonly IOCompletionCallback s_IOCallback = new IOCompletionCallback(Callback);
internal HttpRequestStreamAsyncResult(object asyncObject, object userState, AsyncCallback callback) : base(asyncObject, userState, callback)
{
}
internal HttpRequestStreamAsyncResult(object asyncObject, object userState, AsyncCallback callback, uint dataAlreadyRead) : base(asyncObject, userState, callback)
{
_dataAlreadyRead = dataAlreadyRead;
}
internal HttpRequestStreamAsyncResult(ThreadPoolBoundHandle boundHandle, object asyncObject, object userState, AsyncCallback callback, byte[] buffer, int offset, uint size, uint dataAlreadyRead) : base(asyncObject, userState, callback)
{
_dataAlreadyRead = dataAlreadyRead;
_boundHandle = boundHandle;
_pOverlapped = boundHandle.AllocateNativeOverlapped(s_IOCallback, state: this, pinData: buffer);
_pPinnedBuffer = (void*)(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset));
}
internal void IOCompleted(uint errorCode, uint numBytes)
{
IOCompleted(this, errorCode, numBytes);
}
private static void IOCompleted(HttpRequestStreamAsyncResult asyncResult, uint errorCode, uint numBytes)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"asyncResult: {asyncResult} errorCode:0x {errorCode.ToString("x8")} numBytes: {numBytes}");
object result = null;
try
{
if (errorCode != Interop.HttpApi.ERROR_SUCCESS && errorCode != Interop.HttpApi.ERROR_HANDLE_EOF)
{
asyncResult.ErrorCode = (int)errorCode;
result = new HttpListenerException((int)errorCode);
}
else
{
result = numBytes;
if (NetEventSource.IsEnabled) NetEventSource.DumpBuffer(asyncResult, (IntPtr)asyncResult._pPinnedBuffer, (int)numBytes);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"asyncResult: {asyncResult} calling Complete()");
}
catch (Exception e)
{
result = e;
}
asyncResult.InvokeCallback(result);
}
private static unsafe void Callback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped)
{
HttpRequestStreamAsyncResult asyncResult = (HttpRequestStreamAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped);
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"asyncResult: {asyncResult} errorCode:0x {errorCode.ToString("x8")} numBytes: {numBytes} nativeOverlapped:0x {((IntPtr)nativeOverlapped).ToString("x8")}");
IOCompleted(asyncResult, errorCode, numBytes);
}
// Will be called from the base class upon InvokeCallback()
protected override void Cleanup()
{
base.Cleanup();
if (_pOverlapped != null)
{
_boundHandle.FreeNativeOverlapped(_pOverlapped);
}
}
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type DirectoryRoleRequest.
/// </summary>
public partial class DirectoryRoleRequest : BaseRequest, IDirectoryRoleRequest
{
/// <summary>
/// Constructs a new DirectoryRoleRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public DirectoryRoleRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified DirectoryRole using POST.
/// </summary>
/// <param name="directoryRoleToCreate">The DirectoryRole to create.</param>
/// <returns>The created DirectoryRole.</returns>
public System.Threading.Tasks.Task<DirectoryRole> CreateAsync(DirectoryRole directoryRoleToCreate)
{
return this.CreateAsync(directoryRoleToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified DirectoryRole using POST.
/// </summary>
/// <param name="directoryRoleToCreate">The DirectoryRole to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created DirectoryRole.</returns>
public async System.Threading.Tasks.Task<DirectoryRole> CreateAsync(DirectoryRole directoryRoleToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<DirectoryRole>(directoryRoleToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified DirectoryRole.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified DirectoryRole.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<DirectoryRole>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified DirectoryRole.
/// </summary>
/// <returns>The DirectoryRole.</returns>
public System.Threading.Tasks.Task<DirectoryRole> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified DirectoryRole.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The DirectoryRole.</returns>
public async System.Threading.Tasks.Task<DirectoryRole> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<DirectoryRole>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified DirectoryRole using PATCH.
/// </summary>
/// <param name="directoryRoleToUpdate">The DirectoryRole to update.</param>
/// <returns>The updated DirectoryRole.</returns>
public System.Threading.Tasks.Task<DirectoryRole> UpdateAsync(DirectoryRole directoryRoleToUpdate)
{
return this.UpdateAsync(directoryRoleToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified DirectoryRole using PATCH.
/// </summary>
/// <param name="directoryRoleToUpdate">The DirectoryRole to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated DirectoryRole.</returns>
public async System.Threading.Tasks.Task<DirectoryRole> UpdateAsync(DirectoryRole directoryRoleToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<DirectoryRole>(directoryRoleToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IDirectoryRoleRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IDirectoryRoleRequest Expand(Expression<Func<DirectoryRole, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IDirectoryRoleRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IDirectoryRoleRequest Select(Expression<Func<DirectoryRole, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="directoryRoleToInitialize">The <see cref="DirectoryRole"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(DirectoryRole directoryRoleToInitialize)
{
if (directoryRoleToInitialize != null && directoryRoleToInitialize.AdditionalData != null)
{
if (directoryRoleToInitialize.Members != null && directoryRoleToInitialize.Members.CurrentPage != null)
{
directoryRoleToInitialize.Members.AdditionalData = directoryRoleToInitialize.AdditionalData;
object nextPageLink;
directoryRoleToInitialize.AdditionalData.TryGetValue("members@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
directoryRoleToInitialize.Members.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
}
}
}
}
| |
// 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 Xunit;
namespace System.Net.Primitives.Functional.Tests
{
public static class CookieTest
{
[Fact]
public static void Ctor_Empty_Success()
{
Cookie c = new Cookie();
}
[Fact]
public static void Ctor_NameValue_Success()
{
Cookie c = new Cookie("hello", "goodbye");
Assert.Equal("hello", c.Name);
Assert.Equal("goodbye", c.Value);
}
[Fact]
public static void Ctor_NameValuePath_Success()
{
Cookie c = new Cookie("hello", "goodbye", "foo");
Assert.Equal("hello", c.Name);
Assert.Equal("goodbye", c.Value);
Assert.Equal("foo", c.Path);
}
[Fact]
public static void Ctor_NameValuePathDomain_Success()
{
Cookie c = new Cookie("hello", "goodbye", "foo", "bar");
Assert.Equal("hello", c.Name);
Assert.Equal("goodbye", c.Value);
Assert.Equal("foo", c.Path);
Assert.Equal("bar", c.Domain);
}
[Fact]
public static void CookieException_Ctor_Success()
{
CookieException c = new CookieException();
}
[Fact]
public static void Comment_GetSet_Success()
{
Cookie c = new Cookie();
Assert.Equal(string.Empty, c.Comment);
c.Comment = "hello";
Assert.Equal("hello", c.Comment);
c.Comment = null;
Assert.Equal(string.Empty, c.Comment);
}
[Fact]
public static void CommentUri_GetSet_Success()
{
Cookie c = new Cookie();
Assert.Null(c.CommentUri);
c.CommentUri = new Uri("http://hello.com");
Assert.Equal(new Uri("http://hello.com"), c.CommentUri);
}
[Fact]
public static void HttpOnly_GetSet_Success()
{
Cookie c = new Cookie();
Assert.False(c.HttpOnly);
c.HttpOnly = true;
Assert.True(c.HttpOnly);
c.HttpOnly = false;
Assert.False(c.HttpOnly);
}
[Fact]
public static void Discard_GetSet_Success()
{
Cookie c = new Cookie();
Assert.False(c.Discard);
c.Discard = true;
Assert.True(c.Discard);
c.Discard = false;
Assert.False(c.Discard);
}
[Fact]
public static void Domain_GetSet_Success()
{
Cookie c = new Cookie();
Assert.Equal(string.Empty, c.Domain);
c.Domain = "hello";
Assert.Equal("hello", c.Domain);
c.Domain = null;
Assert.Equal(string.Empty, c.Domain);
}
[Fact]
public static void Expired_GetSet_Success()
{
Cookie c = new Cookie();
Assert.False(c.Expired);
c.Expires = DateTime.Now.AddDays(-1);
Assert.True(c.Expired);
c.Expires = DateTime.Now.AddDays(1);
Assert.False(c.Expired);
c.Expired = true;
Assert.True(c.Expired);
c.Expired = true;
Assert.True(c.Expired);
}
[Fact]
public static void Expires_GetSet_Success()
{
Cookie c = new Cookie();
Assert.Equal(c.Expires, DateTime.MinValue);
DateTime dt = DateTime.Now;
c.Expires = dt;
Assert.Equal(dt, c.Expires);
}
[Fact]
public static void Name_GetSet_Success()
{
Cookie c = new Cookie();
Assert.Equal(string.Empty, c.Name);
c.Name = "hello";
Assert.Equal("hello", c.Name);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("$hello")]
[InlineData("hello ")]
[InlineData("hello\t")]
[InlineData("hello\r")]
[InlineData("hello\n")]
[InlineData("hello=")]
[InlineData("hello;")]
[InlineData("hello,")]
public static void Name_Set_Invalid(string name)
{
Cookie c = new Cookie();
Assert.Throws<CookieException>(() => c.Name = name);
}
[Fact]
public static void Path_GetSet_Success()
{
Cookie c = new Cookie();
Assert.Equal(string.Empty, c.Path);
c.Path = "path";
Assert.Equal("path", c.Path);
c.Path = null;
Assert.Equal(string.Empty, c.Path);
}
[Fact]
public static void Port_GetSet_Success()
{
Cookie c = new Cookie();
Assert.Equal(string.Empty, c.Port);
c.Port = "\"80 110, 1050, 1090 ,110\"";
Assert.Equal("\"80 110, 1050, 1090 ,110\"", c.Port);
c.Port = null;
Assert.Equal(string.Empty, c.Port);
}
[Theory]
[InlineData("80, 80 \"")] //No leading quotation mark
[InlineData("\"80, 80")] //No trailing quotation mark
[InlineData("\"80, hello\"")] //Invalid port
[InlineData("\"-1, hello\"")] //Port out of range, < 0
[InlineData("\"80, 65536\"")] //Port out of range, > 65535
public static void Port_Set_Invalid(string port)
{
Cookie c = new Cookie();
Assert.Throws<CookieException>(() => c.Port = port);
}
[Fact]
public static void Secure_GetSet_Success()
{
Cookie c = new Cookie();
Assert.False(c.Secure);
c.Secure = true;
Assert.True(c.Secure);
c.Secure = false;
Assert.False(c.Secure);
}
[Fact]
public static void Timestamp_GetSet_Success()
{
DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, 0); //DateTime.Now changes as the test runs
Cookie c = new Cookie();
Assert.True(c.TimeStamp >= dt);
}
[Fact]
public static void Value_GetSet_Success()
{
Cookie c = new Cookie();
Assert.Equal(string.Empty, c.Value);
c.Value = "hello";
Assert.Equal("hello", c.Value);
c.Value = null;
Assert.Equal(string.Empty, c.Value);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp | TargetFrameworkMonikers.Uap)]
public static void Value_PassNullToCtor_GetReturnsEmptyString_net46()
{
var cookie = new Cookie("SomeName", null);
// Cookie.Value returns null on full framework.
Assert.Null(cookie.Value);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void Value_PassNullToCtor_GetReturnsEmptyString()
{
var cookie = new Cookie("SomeName", null);
// Cookie.Value returns empty string on netcore.
Assert.Equal(string.Empty, cookie.Value);
}
[Fact]
public static void Version_GetSet_Success()
{
Cookie c = new Cookie();
Assert.Equal(0, c.Version);
c.Version = 100;
Assert.Equal(100, c.Version);
}
[Fact]
public static void Version_Set_Invalid()
{
Cookie c = new Cookie();
Assert.Throws<ArgumentOutOfRangeException>(() => c.Version = -1);
}
[Fact]
public static void Equals_Compare_Success()
{
Cookie c1 = new Cookie();
Cookie c2 = new Cookie("name", "value");
Cookie c3 = new Cookie("Name", "value");
Cookie c4 = new Cookie("different-name", "value");
Cookie c5 = new Cookie("name", "different-value");
Cookie c6 = new Cookie("name", "value", "path");
Cookie c7 = new Cookie("name", "value", "path");
Cookie c8 = new Cookie("name", "value", "different-path");
Cookie c9 = new Cookie("name", "value", "path", "domain");
Cookie c10 = new Cookie("name", "value", "path", "domain");
Cookie c11 = new Cookie("name", "value", "path", "Domain");
Cookie c12 = new Cookie("name", "value", "path", "different-domain");
Cookie c13 = new Cookie("name", "value", "path", "domain") { Version = 5 };
Cookie c14 = new Cookie("name", "value", "path", "domain") { Version = 5 };
Cookie c15 = new Cookie("name", "value", "path", "domain") { Version = 100 };
Assert.False(c2.Equals(null));
Assert.False(c2.Equals(""));
Assert.NotEqual(c1, c2);
Assert.Equal(c2, c3);
Assert.Equal(c3, c2);
Assert.NotEqual(c2, c4);
Assert.NotEqual(c2, c5);
Assert.NotEqual(c2, c6);
Assert.NotEqual(c2, c9);
Assert.NotEqual(c2.GetHashCode(), c4.GetHashCode());
Assert.NotEqual(c2.GetHashCode(), c5.GetHashCode());
Assert.NotEqual(c2.GetHashCode(), c6.GetHashCode());
Assert.NotEqual(c2.GetHashCode(), c9.GetHashCode());
Assert.Equal(c6, c7);
Assert.NotEqual(c6, c8);
Assert.NotEqual(c6, c9);
Assert.NotEqual(c6.GetHashCode(), c8.GetHashCode());
Assert.NotEqual(c6.GetHashCode(), c9.GetHashCode());
Assert.Equal(c9, c10);
Assert.Equal(c9, c11);
Assert.NotEqual(c9, c12);
Assert.Equal(c9.GetHashCode(), c10.GetHashCode());
Assert.NotEqual(c9.GetHashCode(), c12.GetHashCode());
Assert.Equal(c13, c14);
Assert.NotEqual(c13, c15);
Assert.Equal(c13.GetHashCode(), c14.GetHashCode());
Assert.NotEqual(c13.GetHashCode(), c15.GetHashCode());
}
[Fact]
public static void ToString_Compare_Success()
{
Cookie c = new Cookie();
Assert.Equal(string.Empty, c.ToString());
c = new Cookie("name", "value");
Assert.Equal("name=value", c.ToString());
c = new Cookie("name", "value", "path", "domain");
c.Port = "\"80\"";
c.Version = 100;
Assert.Equal("$Version=100; name=value; $Path=path; $Domain=domain; $Port=\"80\"", c.ToString());
c.Version = 0;
Assert.Equal("name=value; $Path=path; $Domain=domain; $Port=\"80\"", c.ToString());
c.Port = "";
Assert.Equal("name=value; $Path=path; $Domain=domain; $Port", c.ToString());
}
}
}
| |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
using Mosa.Compiler.Common;
using Mosa.Compiler.Framework;
using Mosa.Compiler.Linker.Elf;
using Mosa.Compiler.MosaTypeSystem;
namespace Mosa.Platform.x64
{
/// <summary>
/// This class provides a common base class for architecture
/// specific operations.
/// </summary>
public class Architecture : BaseArchitecture
{
/// <summary>
/// Gets the endianness of the target architecture.
/// </summary>
/// <value>
/// The endianness.
/// </value>
public override Endianness Endianness { get { return Endianness.Little; } }
/// <summary>
/// Gets the type of the elf machine.
/// </summary>
/// <value>
/// The type of the elf machine.
/// </value>
public override MachineType MachineType { get { return MachineType.IA_64; } }
/// <summary>
/// Defines the register set of the target architecture.
/// </summary>
private static readonly Register[] Registers = new Register[]
{
//TODO
};
/// <summary>
/// Specifies the architecture features to use in generated code.
/// </summary>
private ArchitectureFeatureFlags architectureFeatures;
/// <summary>
/// Initializes a new instance of the <see cref="Architecture"/> class.
/// </summary>
/// <param name="architectureFeatures">The features this architecture supports.</param>
private Architecture(ArchitectureFeatureFlags architectureFeatures)
{
this.architectureFeatures = architectureFeatures;
}
/// <summary>
/// Retrieves the native integer size of the x64 platform.
/// </summary>
/// <value>This property always returns 64.</value>
public override int NativeIntegerSize
{
get { return 64; }
}
/// <summary>
/// Gets the native alignment of the architecture in bytes.
/// </summary>
/// <value>This property always returns 8.</value>
public override int NativeAlignment
{
get { return 8; }
}
/// <summary>
/// Gets the native size of architecture in bytes.
/// </summary>
/// <value>This property always returns 8.</value>
public override int NativePointerSize
{
get { return 8; }
}
/// <summary>
/// Retrieves the register set of the x64 platform.
/// </summary>
public override Register[] RegisterSet
{
get { return Registers; }
}
/// <summary>
/// Retrieves the stack frame register of the x64.
/// </summary>
public override Register StackFrameRegister
{
get { return null; /* GeneralPurposeRegister.EBP;*/ }
}
/// <summary>
/// Retrieves the stack pointer register of the x64.
/// </summary>
public override Register StackPointerRegister
{
get { return null; /* GeneralPurposeRegister.ESP;*/ }
}
/// <summary>
/// Retrieves the exception register of the architecture.
/// </summary>
public override Register ExceptionRegister
{
get { return null; /* GeneralPurposeRegister.EDI;*/ }
}
/// <summary>
/// Gets the finally return block register.
/// </summary>
public override Register LeaveTargetRegister
{
get { return null; /* GeneralPurposeRegister.EDX;*/ }
}
/// <summary>
/// Retrieves the stack pointer register of the x64.
/// </summary>
public override Register ProgramCounter
{
get { return null; }
}
/// <summary>
/// Gets the name of the platform.
/// </summary>
/// <value>
/// The name of the platform.
/// </value>
public override string PlatformName { get { return "x64"; } }
/// <summary>
/// Factory method for the Architecture class.
/// </summary>
/// <returns>The created architecture instance.</returns>
/// <param name="architectureFeatures">The features available in the architecture and code generation.</param>
/// <remarks>
/// This method creates an instance of an appropriate architecture class, which supports the specific
/// architecture features.
/// </remarks>
public static BaseArchitecture CreateArchitecture(ArchitectureFeatureFlags architectureFeatures)
{
if (architectureFeatures == ArchitectureFeatureFlags.AutoDetect)
architectureFeatures = ArchitectureFeatureFlags.MMX | ArchitectureFeatureFlags.SSE | ArchitectureFeatureFlags.SSE2;
return new Architecture(architectureFeatures);
}
/// <summary>
/// Extends the pre compiler pipeline with x64 specific stages.
/// </summary>
/// <param name="compilerPipeline">The pipeline to extend.</param>
public override void ExtendCompilerPipeline(CompilerPipeline compilerPipeline)
{
// TODO
}
/// <summary>
/// Extends the method compiler pipeline with x64 specific stages.
/// </summary>
/// <param name="methodCompilerPipeline">The method compiler pipeline to extend.</param>
public override void ExtendMethodCompilerPipeline(CompilerPipeline methodCompilerPipeline)
{
// TODO
}
/// <summary>
/// Gets the type memory requirements.
/// </summary>
/// <param name="typeLayout">The type layouts.</param>
/// <param name="type">The signature type.</param>
/// <param name="size">Receives the memory size of the type.</param>
/// <param name="alignment">Receives alignment requirements of the type.</param>
public override void GetTypeRequirements(MosaTypeLayout typeLayout, MosaType type, out int size, out int alignment)
{
if (type.IsUI8 || type.IsR8 || !type.IsValueType || type.IsPointer)
{
size = 8;
alignment = 8;
}
else if (typeLayout.IsCompoundType(type))
{
size = typeLayout.GetTypeSize(type);
alignment = 8;
}
else
{
size = 4;
alignment = 4;
}
}
/// <summary>
/// Gets the code emitter.
/// </summary>
/// <returns></returns>
public override BaseCodeEmitter GetCodeEmitter()
{
// TODO
return null;
//return new MachineCodeEmitter();
}
/// <summary>
/// Inserts the move instruction.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="destination">The destination.</param>
/// <param name="source">The source.</param>
public override void InsertMoveInstruction(Context context, Operand destination, Operand source)
{
// TODO
}
/// <summary>
/// Create platform compound move.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="destination">The destination.</param>
/// <param name="source">The source.</param>
/// <param name="size">The size.</param>
public override void InsertCompoundMoveInstruction(BaseMethodCompiler compiler, Context context, Operand destination, Operand source, int size)
{
// TODO
}
/// <summary>
/// Inserts the exchange instruction.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="destination">The destination.</param>
/// <param name="source">The source.</param>
public override void InsertExchangeInstruction(Context context, Operand destination, Operand source)
{
// TODO
}
/// <summary>
/// Inserts the jump instruction.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="destination">The destination.</param>
/// <param name="source">The source.</param>
public override void InsertJumpInstruction(Context context, Operand destination)
{
// TODO
}
/// <summary>
/// Inserts the jump instruction.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="Destination">The destination.</param>
public override void InsertJumpInstruction(Context context, BasicBlock Destination)
{
// TODO
}
/// <summary>
/// Inserts the call instruction.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="source">The source.</param>
public override void InsertCallInstruction(Context context, Operand source)
{
// TODO
}
/// <summary>
/// Inserts the add instruction.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="Destination">The destination.</param>
/// <param name="Source">The source.</param>
public override void InsertAddInstruction(Context context, Operand destination, Operand source1, Operand source2)
{
// TODO
}
/// <summary>
/// Inserts the sub instruction.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="Destination">The destination.</param>
/// <param name="Source">The source.</param>
public override void InsertSubInstruction(Context context, Operand destination, Operand source1, Operand source2)
{
// TODO
}
/// <summary>
/// Determines whether [is instruction move] [the specified instruction].
/// </summary>
/// <param name="instruction">The instruction.</param>
/// <returns></returns>
public override bool IsInstructionMove(BaseInstruction instruction)
{
// TODO
return false;
}
/// <summary>
/// Inserts the address of instruction.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="destination">The destination.</param>
/// <param name="source">The source.</param>
public override void InsertAddressOfInstruction(Context context, Operand destination, Operand source)
{
// TODO
}
}
}
| |
/*
Copyright 2017 Alexis Ryan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using WebKit;
using Ao3TrackReader.Helper;
using Ao3TrackReader.Data;
using System.IO;
using UIKit;
using CoreGraphics;
using ObjCRuntime;
using Foundation;
using Newtonsoft.Json;
using System.Threading;
namespace Ao3TrackReader
{
public partial class WebViewPage : IWebViewPage
{
public bool IsMainThread
{
get { return Foundation.NSThread.IsMain; }
}
public class WKWebView : WebKit.WKWebView
{
public WKWebView(WKWebViewConfiguration configuration) : base(new CoreGraphics.CGRect(0, 0, 360, 512), configuration)
{
}
public event EventHandler<bool> FocuseChanged;
public override bool BecomeFirstResponder()
{
bool ret = base.BecomeFirstResponder();
if (ret) FocuseChanged?.Invoke(this, true);
return ret;
}
public override bool ResignFirstResponder()
{
bool ret = base.ResignFirstResponder();
if (ret) FocuseChanged?.Invoke(this, false);
return ret;
}
}
WKWebView webView;
WKUserContentController userContentController;
public static bool HaveOSBackButton { get; } = false;
public Xamarin.Forms.View CreateWebView()
{
var preferences = new WKPreferences()
{
JavaScriptEnabled = true,
JavaScriptCanOpenWindowsAutomatically = false
};
var configuration = new WKWebViewConfiguration()
{
UserContentController = userContentController = new WKUserContentController()
};
var helper = new Ao3TrackHelper(this);
var messageHandler = new Ao3TrackReader.iOS.ScriptMessageHandler(helper);
userContentController.AddScriptMessageHandler((WKScriptMessageHandler) messageHandler, "ao3track");
this.helper = helper;
configuration.Preferences = preferences;
webView = new WKWebView(configuration)
{
NavigationDelegate = new NavigationDelegate(this)
};
webView.FocuseChanged += WebView_FocusChange;
var xview = webView.ToView();
xview.SizeChanged += Xview_SizeChanged;
return xview;
}
private void Xview_SizeChanged(object sender, EventArgs e)
{
CallJavascriptAsync("Ao3Track.Messaging.helper.setValue", "deviceWidth", DeviceWidth).Wait(0);
}
private void WebView_FocusChange(object sender, bool e)
{
if (e)
{
OnWebViewGotFocus();
}
}
public async Task<string> EvaluateJavascriptAsync(string code)
{
var result = await webView.EvaluateJavaScriptAsync(code);
return result?.ToString();
}
public void AddJavascriptObject(string name, object obj)
{
}
async Task OnInjectingScripts(CancellationToken ct)
{
await EvaluateJavascriptAsync("window.Ao3TrackHelperNative = " + helper.HelperDefJson + ";");
}
async Task<string> ReadFile(string name, CancellationToken ct)
{
using (StreamReader sr = new StreamReader(Path.Combine(NSBundle.MainBundle.BundlePath, "Content", name), Encoding.UTF8))
{
return await sr.ReadToEndAsync();
}
}
public Uri CurrentUri
{
get
{
return DoOnMainThreadAsync(() =>
{
if (!string.IsNullOrWhiteSpace(webView.Url?.AbsoluteString)) return new Uri(webView.Url.AbsoluteString);
else return new Uri("about:blank");
}).Result;
}
}
public void Navigate(Uri uri)
{
helper?.Reset();
webView.LoadRequest(new Foundation.NSUrlRequest(new Foundation.NSUrl(uri.AbsoluteUri)));
}
public void Refresh()
{
webView.Reload();
}
bool WebViewCanGoBack => webView.CanGoBack;
bool WebViewCanGoForward => webView.CanGoForward;
void WebViewGoBack()
{
webView.GoBack();
}
void WebViewGoForward()
{
webView.GoForward();
}
public double DeviceWidth
{
get
{
return webView.Frame.Width;
}
}
public double LeftOffset
{
get
{
return webView.Transform.x0;
}
set
{
if (value == 0) webView.Transform = CGAffineTransform.MakeIdentity();
else webView.Transform = CGAffineTransform.MakeTranslation(new nfloat(value), 0);
}
}
public const bool HaveClipboard = false;
public void CopyToClipboard(string str, string type)
{
}
//Android.Widget.PopupMenu contextMenu = null;
public void HideContextMenu()
{
/*
contextMenu.Dismiss();
*/
}
public void ShowContextMenu(double x, double y, string url, string innerHtml)
{
HideContextMenu();
/*
Xamarin.Forms.AbsoluteLayout.SetLayoutBounds(contextMenuPlaceholder, new Rectangle(x* Width / WebView.Width, y * Height / WebView.Height, 0, 0));
MainContent.Children.Add(contextMenuPlaceholder);
var renderer = Platform.GetRenderer(contextMenuPlaceholder) as NativeViewWrapperRenderer;
contextMenu = new PopupMenu(Forms.Context, renderer.Control);
var menu = contextMenu.Menu;
for (int i = 0; i < menuItems.Length; i++)
{
if (menuItems[i] == "-")
{
menu.Add(Menu.None, i, i, "-").SetEnabled(false);
}
else
{
menu.Add(Menu.None, i, i, menuItems[i]);
}
}
contextMenu.MenuItemClick += (s1, arg1) =>
{
contextMenuResult.TrySetResult(menuItems[arg1.Item.ItemId]);
};
contextMenu.DismissEvent += (s2, arg2) =>
{
contextMenuResult.TrySetResult("");
MainContent.Children.Remove(contextMenuPlaceholder);
};
contextMenu.Show();*/
}
class NavigationDelegate : WKNavigationDelegate
{
WebViewPage wvp;
public NavigationDelegate(WebViewPage wvp)
{
this.wvp = wvp;
}
bool canDoOnContentLoaded = false;
public override void DidFinishNavigation(WebKit.WKWebView webView, WKNavigation navigation)
{
if (canDoOnContentLoaded)
{
wvp.OnContentLoaded();
canDoOnContentLoaded = false;
}
}
public override void DidCommitNavigation(WebKit.WKWebView webView, WKNavigation navigation)
{
wvp.OnContentLoading();
canDoOnContentLoaded = true;
}
public override void DecidePolicy(WebKit.WKWebView webView, WKNavigationAction navigationAction, Action<WKNavigationActionPolicy> decisionHandler)
{
if (wvp.OnNavigationStarting(new Uri(navigationAction.Request.Url.AbsoluteString)))
decisionHandler(WKNavigationActionPolicy.Cancel);
else
decisionHandler(WKNavigationActionPolicy.Allow);
}
}
}
}
| |
// 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.Runtime.InteropServices;
using EnvDTE;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.Mocks;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel
{
public class FileCodeFunctionTests : AbstractFileCodeElementTests
{
public FileCodeFunctionTests()
: base(@"using System;
public class A
{
public A()
{
}
~A()
{
}
public static A operator +(A a1, A a2)
{
return a1;
}
private int MethodA()
{
return 1;
}
protected virtual string MethodB(int intA)
{
return intA.ToString();
}
internal static bool MethodC(int intA, bool boolB)
{
return boolB;
}
public float MethodD(int intA, bool boolB, string stringC)
{
return 1.5f;
}
void MethodE()
{
}
void MethodE(int intA)
{
}
void MethodWithBlankLine()
{
}
}
public class B : A
{
protected override string MethodB(int intA)
{
return ""Override!"";
}
}
public abstract class C
{
/// <summary>
/// A short summary.
/// </summary>
/// <param name=""intA"">A parameter.</param>
/// <returns>An int.</returns>
public abstract int MethodA(int intA);
// This is a short comment.
public abstract int MethodB(string foo);
dynamic DynamicField;
dynamic DynamicMethod(dynamic foo = 5);
}
public class Entity { }
public class Ref<T> where T : Entity
{
public static implicit operator Ref<T>(T entity)
{
return new Ref<T>(entity);
}
}
")
{
}
private CodeFunction GetCodeFunction(params object[] path)
{
return (CodeFunction)GetCodeElement(path);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void CanOverride_False()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
Assert.False(testObject.CanOverride);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void CanOverride_True()
{
CodeFunction testObject = GetCodeFunction("A", "MethodB");
Assert.True(testObject.CanOverride);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void FullName()
{
CodeFunction testObject = GetCodeFunction("A", "MethodD");
Assert.Equal("A.MethodD", testObject.FullName);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void FunctionKind_Function()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
Assert.Equal(vsCMFunction.vsCMFunctionFunction, testObject.FunctionKind);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void FunctionKind_Constructor()
{
CodeFunction testObject = GetCodeFunction("A", 1);
Assert.Equal(vsCMFunction.vsCMFunctionConstructor, testObject.FunctionKind);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void FunctionKind_Finalizer()
{
CodeFunction testObject = GetCodeFunction("A", 2);
Assert.Equal(vsCMFunction.vsCMFunctionDestructor, testObject.FunctionKind);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void IsOverloaded_True()
{
CodeFunction testObject = GetCodeFunction("A", "MethodE");
Assert.True(testObject.IsOverloaded);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void IsOverloaded_False()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
Assert.False(testObject.IsOverloaded);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void IsShared_False()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
Assert.False(testObject.IsShared);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void IsShared_True()
{
CodeFunction testObject = GetCodeFunction("A", "MethodC");
Assert.True(testObject.IsShared);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Kind()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
Assert.Equal(vsCMElement.vsCMElementFunction, testObject.Kind);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Name()
{
CodeFunction testObject = GetCodeFunction("A", "MethodC");
Assert.Equal("MethodC", testObject.Name);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Parameters_Count()
{
CodeFunction testObject = GetCodeFunction("A", "MethodD");
Assert.Equal(3, testObject.Parameters.Count);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Parent()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
Assert.NotNull(testObject.Parent);
Assert.True(testObject.Parent is CodeClass, testObject.Parent.GetType().ToString());
Assert.Equal("A", ((CodeClass)testObject.Parent).FullName);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Type()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
Assert.Equal("System.Int32", testObject.Type.AsFullName);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Comment()
{
CodeFunction testObject = GetCodeFunction("C", "MethodB");
string expected = "This is a short comment.\r\n";
Assert.Equal(expected, testObject.Comment);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void DocComment()
{
CodeFunction testObject = GetCodeFunction("C", "MethodA");
string expected = "<doc>\r\n<summary>\r\nA short summary.\r\n</summary>\r\n<param name=\"intA\">A parameter.</param>\r\n<returns>An int.</returns>\r\n</doc>";
Assert.Equal(expected, testObject.DocComment);
}
[ConditionalFact(typeof(x86), Skip = "636860")]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Overloads_Count()
{
CodeFunction testObject = GetCodeFunction("A", "MethodE");
Assert.Equal(2, testObject.Overloads.Count);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Attributes()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartAttributes));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_AttributesWithDelimiter()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<COMException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Body()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartBody);
Assert.Equal(20, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_BodyWithDelimiter()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Header()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartHeader);
Assert.Equal(18, startPoint.Line);
Assert.Equal(5, startPoint.LineCharOffset);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_HeaderWithAttributes()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Name()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Navigate()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(20, startPoint.Line);
Assert.Equal(9, startPoint.LineCharOffset);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_NavigateWithBlankLine()
{
CodeFunction testObject = GetCodeFunction("A", "MethodWithBlankLine");
TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(48, startPoint.Line);
Assert.Equal(9, startPoint.LineCharOffset);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Whole()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartWhole));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_WholeWithAttributes()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(18, startPoint.Line);
Assert.Equal(5, startPoint.LineCharOffset);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Attributes()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartAttributes));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_AttributesWithDelimiter()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<COMException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Body()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
TextPoint endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartBody);
Assert.Equal(21, endPoint.Line);
Assert.Equal(1, endPoint.LineCharOffset);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_BodyWithDelimiter()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Header()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartHeader));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_HeaderWithAttributes()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Name()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartName));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Navigate()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
TextPoint endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(21, endPoint.Line);
Assert.Equal(1, endPoint.LineCharOffset);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Whole()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartWhole));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_WholeWithAttributes()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
TextPoint endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(21, endPoint.Line);
Assert.Equal(6, endPoint.LineCharOffset);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void StartPoint()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
TextPoint startPoint = testObject.StartPoint;
Assert.Equal(18, startPoint.Line);
Assert.Equal(5, startPoint.LineCharOffset);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void EndPoint()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
TextPoint endPoint = testObject.EndPoint;
Assert.Equal(21, endPoint.Line);
Assert.Equal(6, endPoint.LineCharOffset);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void DynamicReturnType()
{
CodeVariable testObject = (CodeVariable)GetCodeElement("C", "DynamicField");
CodeTypeRef returnType = testObject.Type;
Assert.Equal(returnType.AsFullName, "dynamic");
Assert.Equal(returnType.AsString, "dynamic");
Assert.Equal(returnType.CodeType.FullName, "System.Object");
Assert.Equal(returnType.TypeKind, vsCMTypeRef.vsCMTypeRefOther);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void DynamicParameter()
{
CodeFunction testObject = GetCodeFunction("C", "DynamicMethod");
CodeTypeRef returnType = ((CodeParameter)testObject.Parameters.Item(1)).Type;
Assert.Equal(returnType.AsFullName, "dynamic");
Assert.Equal(returnType.AsString, "dynamic");
Assert.Equal(returnType.CodeType.FullName, "System.Object");
Assert.Equal(returnType.TypeKind, vsCMTypeRef.vsCMTypeRefOther);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
[WorkItem(530496)]
public void TestCodeElementFromPoint()
{
var text = CurrentDocument.GetTextAsync().Result;
var tree = CurrentDocument.GetSyntaxTreeAsync().Result;
var position = text.ToString().IndexOf("DynamicMethod", StringComparison.Ordinal);
var virtualTreePoint = new VirtualTreePoint(tree, text, position);
var textPoint = new MockTextPoint(virtualTreePoint, 4);
var scope = vsCMElement.vsCMElementFunction;
var element = CodeModel.CodeElementFromPoint(textPoint, scope);
Assert.Equal("DynamicMethod", element.Name);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
[WorkItem(726710)]
public void TestCodeElementFromPointBetweenMembers()
{
var text = CurrentDocument.GetTextAsync().Result;
var tree = CurrentDocument.GetSyntaxTreeAsync().Result;
var position = text.ToString().IndexOf("protected virtual string MethodB", StringComparison.Ordinal) - 1;
var virtualTreePoint = new VirtualTreePoint(tree, text, position);
var textPoint = new MockTextPoint(virtualTreePoint, 4);
Assert.Throws<COMException>(() =>
CodeModel.CodeElementFromPoint(textPoint, vsCMElement.vsCMElementFunction));
var element = CodeModel.CodeElementFromPoint(textPoint, vsCMElement.vsCMElementClass);
Assert.Equal("A", element.Name);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Operator()
{
CodeFunction functionObject = GetCodeFunction("A", 3);
Assert.Equal("operator +", functionObject.Name);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
[WorkItem(924179)]
public void ConversionOperator()
{
CodeClass classObject = (CodeClass)GetCodeElement("Ref");
var element = classObject.Members.Item(1);
Assert.Equal("operator implicit Ref<T>", element.Name);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Xml.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright>
//-----------------------------------------------------------------------
namespace MSBuild.ExtensionPack.Xml
{
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.Xsl;
using Microsoft.Build.Framework;
/// <summary>
/// <b>Valid TaskActions are:</b>
/// <para><i>Transform</i> (<b>Required: </b>Xml or XmlFile, XslTransform or XslTransformFile <b>Optional:</b> Conformance, Indent, OmitXmlDeclaration, OutputFile, TextEncoding <b>Output: </b>Output)</para>
/// <para><i>Validate</i> (<b>Required: </b>Xml or XmlFile, SchemaFiles <b>Optional: </b> TargetNamespace <b>Output: </b>IsValid, Output)</para>
/// <para><b>Remote Execution Support:</b> NA</para>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <Target Name="Default">
/// <ItemGroup>
/// <Schema Include="c:\Demo1\demo.xsd"/>
/// </ItemGroup>
/// <PropertyGroup>
/// <MyXml>
/// <![CDATA[
/// <Parent>
/// <Child1>Child1 data</Child1>
/// <Child2>Child2 data</Child2>
/// </Parent>]]>
/// </MyXml>
/// <MyXsl>
/// <![CDATA[<?xml version='1.0'?>
/// <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>
/// <xsl:template match='/Parent'>
/// <Root>
/// <C1>
/// <xsl:value-of select='Child1'/>
/// </C1>
/// <C2>
/// <xsl:value-of select='Child2'/>
/// </C2>
/// </Root>
/// </xsl:template>
/// </xsl:stylesheet>]]>
/// </MyXsl>
/// <MyValidXml>
/// <![CDATA[
/// <D>
/// <Name full="Mike" type="3f3">
/// <Place>aPlace</Place>
/// </Name>
/// </D>]]>
/// </MyValidXml>
/// </PropertyGroup>
/// <!-- Validate an XmlFile -->
/// <MSBuild.ExtensionPack.Xml.XmlTask TaskAction="Validate" XmlFile="c:\Demo1\demo.xml" SchemaFiles="@(Schema)">
/// <Output PropertyName="Validated" TaskParameter="IsValid"/>
/// <Output PropertyName="Out" TaskParameter="Output"/>
/// </MSBuild.ExtensionPack.Xml.XmlTask>
/// <Message Text="Valid File: $(Validated)"/>
/// <Message Text="Output: $(Out)"/>
/// <!-- Validate a piece of Xml -->
/// <MSBuild.ExtensionPack.Xml.XmlTask TaskAction="Validate" Xml="$(MyValidXml)" SchemaFiles="@(Schema)">
/// <Output PropertyName="Validated" TaskParameter="IsValid"/>
/// </MSBuild.ExtensionPack.Xml.XmlTask>
/// <Message Text="Valid File: $(Validated)"/>
/// <!-- Transform an Xml file with an Xslt file -->
/// <MSBuild.ExtensionPack.Xml.XmlTask TaskAction="Transform" XmlFile="C:\Demo1\XmlForTransform.xml" XslTransformFile="C:\Demo1\Transform.xslt">
/// <Output PropertyName="Out" TaskParameter="Output"/>
/// </MSBuild.ExtensionPack.Xml.XmlTask>
/// <Message Text="Transformed Xml: $(Out)"/>
/// <!-- Transfrom a piece of Xml with an Xslt file -->
/// <MSBuild.ExtensionPack.Xml.XmlTask TaskAction="Transform" Xml="$(MyXml)" XslTransformFile="C:\Demo1\Transform.xslt">
/// <Output PropertyName="Out" TaskParameter="Output"/>
/// </MSBuild.ExtensionPack.Xml.XmlTask>
/// <Message Text="Transformed Xml: $(Out)"/>
/// <!-- Transfrom a piece of Xml with a piece of Xslt and write it out to a file with indented formatting -->
/// <MSBuild.ExtensionPack.Xml.XmlTask TaskAction="Transform" Xml="$(MyXml)" XslTransform="$(MyXsl)" OutputFile="C:\newxml.xml" Indent="true">
/// <Output PropertyName="Out" TaskParameter="Output"/>
/// </MSBuild.ExtensionPack.Xml.XmlTask>
/// <Message Text="Transformed Xml: $(Out)"/>
/// </Target>
/// </Project>
/// ]]></code>
/// </example>
public class XmlTask : BaseTask
{
private const string TransformTaskAction = "Transform";
private const string ValidateTaskAction = "Validate";
private string targetNamespace = string.Empty;
private XDocument xmlDoc;
private Encoding fileEncoding = Encoding.UTF8;
private ConformanceLevel conformanceLevel;
/// <summary>
/// Sets the XmlFile
/// </summary>
public string XmlFile { get; set; }
/// <summary>
/// Sets the XslTransformFile
/// </summary>
public string XslTransformFile { get; set; }
/// <summary>
/// Sets the XmlFile
/// </summary>
public string Xml { get; set; }
/// <summary>
/// Sets the XslTransformFile
/// </summary>
public string XslTransform { get; set; }
/// <summary>
/// Sets the OutputFile
/// </summary>
public string OutputFile { get; set; }
/// <summary>
/// Sets the TargetNamespace for Validate. Default is ""
/// </summary>
public string TargetNamespace
{
get { return this.targetNamespace; }
set { this.targetNamespace = value; }
}
/// <summary>
/// Sets the Schema Files collection
/// </summary>
public ITaskItem[] SchemaFiles { get; set; }
/// <summary>
/// Set the OmitXmlDeclaration option for TransForm. Default is False
/// </summary>
public bool OmitXmlDeclaration { get; set; }
/// <summary>
/// Set the Indent option for TransForm. Default is False
/// </summary>
public bool Indent { get; set; }
/// <summary>
/// Set the Encoding option for TransForm. Default is UTF8
/// </summary>
public string TextEncoding
{
get { return this.fileEncoding.ToString(); }
set { this.fileEncoding = System.Text.Encoding.GetEncoding(value); }
}
/// <summary>
/// Sets the ConformanceLevel. Supports Auto, Document and Fragment. Default is ConformanceLevel.Document
/// </summary>
public string Conformance
{
get { return this.conformanceLevel.ToString(); }
set { this.conformanceLevel = (ConformanceLevel)Enum.Parse(typeof(ConformanceLevel), value); }
}
/// <summary>
/// Gets whether an XmlFile is valid xml
/// </summary>
[Output]
public bool IsValid { get; set; }
/// <summary>
/// Get the Output
/// </summary>
[Output]
public string Output { get; set; }
/// <summary>
/// Performs the action of this task.
/// </summary>
protected override void InternalExecute()
{
if (!this.TargetingLocalMachine())
{
return;
}
if (!string.IsNullOrEmpty(this.XmlFile) && !File.Exists(this.XmlFile))
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "XmlFile not found: {0}", this.XmlFile));
return;
}
if (!string.IsNullOrEmpty(this.XmlFile))
{
// Load the XmlFile
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Loading XmlFile: {0}", this.XmlFile));
this.xmlDoc = XDocument.Load(this.XmlFile);
}
else if (!string.IsNullOrEmpty(this.Xml))
{
// Load the Xml
this.LogTaskMessage(MessageImportance.Low, "Loading Xml");
using (StringReader sr = new StringReader(this.Xml))
{
this.xmlDoc = XDocument.Load(sr);
}
}
else
{
this.Log.LogError("Xml or XmlFile must be specified");
return;
}
switch (this.TaskAction)
{
case TransformTaskAction:
this.Transform();
break;
case ValidateTaskAction:
this.Validate();
break;
default:
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
return;
}
}
private void Transform()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Transforming: {0}", this.XmlFile));
XDocument xslDoc;
if (!string.IsNullOrEmpty(this.XslTransformFile) && !File.Exists(this.XslTransformFile))
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "XslTransformFile not found: {0}", this.XslTransformFile));
return;
}
if (!string.IsNullOrEmpty(this.XslTransformFile))
{
// Load the XslTransformFile
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Loading XslTransformFile: {0}", this.XslTransformFile));
xslDoc = XDocument.Load(this.XslTransformFile);
}
else if (!string.IsNullOrEmpty(this.XslTransform))
{
// Load the XslTransform
this.LogTaskMessage(MessageImportance.Low, "Loading XslTransform");
using (StringReader sr = new StringReader(this.XslTransform))
{
xslDoc = XDocument.Load(sr);
}
}
else
{
this.Log.LogError("XslTransform or XslTransformFile must be specified");
return;
}
// Load the style sheet.
XslCompiledTransform xslt = new XslCompiledTransform();
XsltSettings settings = new XsltSettings { EnableScript = true };
using (StringReader sr = new StringReader(xslDoc.ToString()))
{
xslt.Load(XmlReader.Create(sr), settings, null);
StringBuilder builder = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(builder, xslt.OutputSettings))
{
this.LogTaskMessage(MessageImportance.Low, "Running XslTransform");
// Execute the transform and output the results to a writer.
xslt.Transform(this.xmlDoc.CreateReader(), writer);
}
this.Output = builder.ToString();
}
if (!string.IsNullOrEmpty(this.OutputFile))
{
if (xslt.OutputSettings.OutputMethod == XmlOutputMethod.Text)
{
this.LogTaskMessage(MessageImportance.Low, "Writing using text method");
using (FileStream stream = new FileStream(this.OutputFile, FileMode.Create))
{
StreamWriter streamWriter = null;
try
{
streamWriter = new StreamWriter(stream, Encoding.Default);
// Output the results to a writer.
streamWriter.Write(this.Output);
}
finally
{
if (streamWriter != null)
{
streamWriter.Close();
}
}
}
}
else
{
this.LogTaskMessage(MessageImportance.Low, "Writing using XML method");
using (StringReader sr = new StringReader(this.Output))
{
XDocument newxmlDoc = XDocument.Load(sr);
if (!string.IsNullOrEmpty(this.OutputFile))
{
XmlWriterSettings writerSettings = new XmlWriterSettings { ConformanceLevel = this.conformanceLevel, Encoding = this.fileEncoding, Indent = this.Indent, OmitXmlDeclaration = this.OmitXmlDeclaration, CloseOutput = true };
using (XmlWriter xw = XmlWriter.Create(this.OutputFile, writerSettings))
{
newxmlDoc.WriteTo(xw);
}
}
}
}
}
}
private void Validate()
{
this.LogTaskMessage(!string.IsNullOrEmpty(this.XmlFile) ? string.Format(CultureInfo.CurrentCulture, "Validating: {0}", this.XmlFile) : "Validating Xml");
XmlSchemaSet schemas = new XmlSchemaSet();
foreach (ITaskItem i in this.SchemaFiles)
{
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Loading SchemaFile: {0}", i.ItemSpec));
schemas.Add(this.TargetNamespace, i.ItemSpec);
}
bool errorEncountered = false;
this.xmlDoc.Validate(
schemas,
(o, e) =>
{
this.Output += e.Message;
this.LogTaskWarning(string.Format(CultureInfo.InvariantCulture, "{0}", e.Message));
errorEncountered = true;
});
this.IsValid = errorEncountered ? false : true;
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type ListContentTypesCollectionRequest.
/// </summary>
public partial class ListContentTypesCollectionRequest : BaseRequest, IListContentTypesCollectionRequest
{
/// <summary>
/// Constructs a new ListContentTypesCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public ListContentTypesCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified ContentType to the collection via POST.
/// </summary>
/// <param name="contentType">The ContentType to add.</param>
/// <returns>The created ContentType.</returns>
public System.Threading.Tasks.Task<ContentType> AddAsync(ContentType contentType)
{
return this.AddAsync(contentType, CancellationToken.None);
}
/// <summary>
/// Adds the specified ContentType to the collection via POST.
/// </summary>
/// <param name="contentType">The ContentType to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created ContentType.</returns>
public System.Threading.Tasks.Task<ContentType> AddAsync(ContentType contentType, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<ContentType>(contentType, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IListContentTypesCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IListContentTypesCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<ListContentTypesCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IListContentTypesCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IListContentTypesCollectionRequest Expand(Expression<Func<ContentType, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IListContentTypesCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IListContentTypesCollectionRequest Select(Expression<Func<ContentType, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IListContentTypesCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IListContentTypesCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IListContentTypesCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IListContentTypesCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using ga = Google.Api;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.GkeConnect.Gateway.V1Beta1
{
/// <summary>Settings for <see cref="GatewayServiceClient"/> instances.</summary>
public sealed partial class GatewayServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="GatewayServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="GatewayServiceSettings"/>.</returns>
public static GatewayServiceSettings GetDefault() => new GatewayServiceSettings();
/// <summary>Constructs a new <see cref="GatewayServiceSettings"/> object with default settings.</summary>
public GatewayServiceSettings()
{
}
private GatewayServiceSettings(GatewayServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetResourceSettings = existing.GetResourceSettings;
PostResourceSettings = existing.PostResourceSettings;
DeleteResourceSettings = existing.DeleteResourceSettings;
PutResourceSettings = existing.PutResourceSettings;
PatchResourceSettings = existing.PatchResourceSettings;
OnCopy(existing);
}
partial void OnCopy(GatewayServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>GatewayServiceClient.GetResource</c> and <c>GatewayServiceClient.GetResourceAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetResourceSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>GatewayServiceClient.PostResource</c> and <c>GatewayServiceClient.PostResourceAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings PostResourceSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>GatewayServiceClient.DeleteResource</c> and <c>GatewayServiceClient.DeleteResourceAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings DeleteResourceSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>GatewayServiceClient.PutResource</c> and <c>GatewayServiceClient.PutResourceAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings PutResourceSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>GatewayServiceClient.PatchResource</c> and <c>GatewayServiceClient.PatchResourceAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings PatchResourceSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="GatewayServiceSettings"/> object.</returns>
public GatewayServiceSettings Clone() => new GatewayServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="GatewayServiceClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
public sealed partial class GatewayServiceClientBuilder : gaxgrpc::ClientBuilderBase<GatewayServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public GatewayServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public GatewayServiceClientBuilder()
{
UseJwtAccessWithScopes = GatewayServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref GatewayServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<GatewayServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override GatewayServiceClient Build()
{
GatewayServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<GatewayServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<GatewayServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private GatewayServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return GatewayServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<GatewayServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return GatewayServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => GatewayServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => GatewayServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => GatewayServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>GatewayService client wrapper, for convenient use.</summary>
/// <remarks>
/// Gateway service is a public API which works as a Kubernetes resource model
/// proxy between end users and registered Kubernetes clusters. Each RPC in this
/// service matches with an HTTP verb. End user will initiate kubectl commands
/// against the Gateway service, and Gateway service will forward user requests
/// to clusters.
/// </remarks>
public abstract partial class GatewayServiceClient
{
/// <summary>
/// The default endpoint for the GatewayService service, which is a host of "connectgateway.googleapis.com" and
/// a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "connectgateway.googleapis.com:443";
/// <summary>The default GatewayService scopes.</summary>
/// <remarks>
/// The default GatewayService scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="GatewayServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="GatewayServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="GatewayServiceClient"/>.</returns>
public static stt::Task<GatewayServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new GatewayServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="GatewayServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="GatewayServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="GatewayServiceClient"/>.</returns>
public static GatewayServiceClient Create() => new GatewayServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="GatewayServiceClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="GatewayServiceSettings"/>.</param>
/// <returns>The created <see cref="GatewayServiceClient"/>.</returns>
internal static GatewayServiceClient Create(grpccore::CallInvoker callInvoker, GatewayServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
GatewayService.GatewayServiceClient grpcClient = new GatewayService.GatewayServiceClient(callInvoker);
return new GatewayServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC GatewayService client</summary>
public virtual GatewayService.GatewayServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// GetResource performs an HTTP GET request on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ga::HttpBody GetResource(ga::HttpBody request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// GetResource performs an HTTP GET request on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ga::HttpBody> GetResourceAsync(ga::HttpBody request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// GetResource performs an HTTP GET request on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ga::HttpBody> GetResourceAsync(ga::HttpBody request, st::CancellationToken cancellationToken) =>
GetResourceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// PostResource performs an HTTP POST on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ga::HttpBody PostResource(ga::HttpBody request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// PostResource performs an HTTP POST on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ga::HttpBody> PostResourceAsync(ga::HttpBody request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// PostResource performs an HTTP POST on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ga::HttpBody> PostResourceAsync(ga::HttpBody request, st::CancellationToken cancellationToken) =>
PostResourceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// DeleteResource performs an HTTP DELETE on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ga::HttpBody DeleteResource(ga::HttpBody request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// DeleteResource performs an HTTP DELETE on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ga::HttpBody> DeleteResourceAsync(ga::HttpBody request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// DeleteResource performs an HTTP DELETE on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ga::HttpBody> DeleteResourceAsync(ga::HttpBody request, st::CancellationToken cancellationToken) =>
DeleteResourceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// PutResource performs an HTTP PUT on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ga::HttpBody PutResource(ga::HttpBody request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// PutResource performs an HTTP PUT on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ga::HttpBody> PutResourceAsync(ga::HttpBody request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// PutResource performs an HTTP PUT on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ga::HttpBody> PutResourceAsync(ga::HttpBody request, st::CancellationToken cancellationToken) =>
PutResourceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// PatchResource performs an HTTP PATCH on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ga::HttpBody PatchResource(ga::HttpBody request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// PatchResource performs an HTTP PATCH on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ga::HttpBody> PatchResourceAsync(ga::HttpBody request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// PatchResource performs an HTTP PATCH on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ga::HttpBody> PatchResourceAsync(ga::HttpBody request, st::CancellationToken cancellationToken) =>
PatchResourceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>GatewayService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Gateway service is a public API which works as a Kubernetes resource model
/// proxy between end users and registered Kubernetes clusters. Each RPC in this
/// service matches with an HTTP verb. End user will initiate kubectl commands
/// against the Gateway service, and Gateway service will forward user requests
/// to clusters.
/// </remarks>
public sealed partial class GatewayServiceClientImpl : GatewayServiceClient
{
private readonly gaxgrpc::ApiCall<ga::HttpBody, ga::HttpBody> _callGetResource;
private readonly gaxgrpc::ApiCall<ga::HttpBody, ga::HttpBody> _callPostResource;
private readonly gaxgrpc::ApiCall<ga::HttpBody, ga::HttpBody> _callDeleteResource;
private readonly gaxgrpc::ApiCall<ga::HttpBody, ga::HttpBody> _callPutResource;
private readonly gaxgrpc::ApiCall<ga::HttpBody, ga::HttpBody> _callPatchResource;
/// <summary>
/// Constructs a client wrapper for the GatewayService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="GatewayServiceSettings"/> used within this client.</param>
public GatewayServiceClientImpl(GatewayService.GatewayServiceClient grpcClient, GatewayServiceSettings settings)
{
GrpcClient = grpcClient;
GatewayServiceSettings effectiveSettings = settings ?? GatewayServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetResource = clientHelper.BuildApiCall<ga::HttpBody, ga::HttpBody>(grpcClient.GetResourceAsync, grpcClient.GetResource, effectiveSettings.GetResourceSettings);
Modify_ApiCall(ref _callGetResource);
Modify_GetResourceApiCall(ref _callGetResource);
_callPostResource = clientHelper.BuildApiCall<ga::HttpBody, ga::HttpBody>(grpcClient.PostResourceAsync, grpcClient.PostResource, effectiveSettings.PostResourceSettings);
Modify_ApiCall(ref _callPostResource);
Modify_PostResourceApiCall(ref _callPostResource);
_callDeleteResource = clientHelper.BuildApiCall<ga::HttpBody, ga::HttpBody>(grpcClient.DeleteResourceAsync, grpcClient.DeleteResource, effectiveSettings.DeleteResourceSettings);
Modify_ApiCall(ref _callDeleteResource);
Modify_DeleteResourceApiCall(ref _callDeleteResource);
_callPutResource = clientHelper.BuildApiCall<ga::HttpBody, ga::HttpBody>(grpcClient.PutResourceAsync, grpcClient.PutResource, effectiveSettings.PutResourceSettings);
Modify_ApiCall(ref _callPutResource);
Modify_PutResourceApiCall(ref _callPutResource);
_callPatchResource = clientHelper.BuildApiCall<ga::HttpBody, ga::HttpBody>(grpcClient.PatchResourceAsync, grpcClient.PatchResource, effectiveSettings.PatchResourceSettings);
Modify_ApiCall(ref _callPatchResource);
Modify_PatchResourceApiCall(ref _callPatchResource);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetResourceApiCall(ref gaxgrpc::ApiCall<ga::HttpBody, ga::HttpBody> call);
partial void Modify_PostResourceApiCall(ref gaxgrpc::ApiCall<ga::HttpBody, ga::HttpBody> call);
partial void Modify_DeleteResourceApiCall(ref gaxgrpc::ApiCall<ga::HttpBody, ga::HttpBody> call);
partial void Modify_PutResourceApiCall(ref gaxgrpc::ApiCall<ga::HttpBody, ga::HttpBody> call);
partial void Modify_PatchResourceApiCall(ref gaxgrpc::ApiCall<ga::HttpBody, ga::HttpBody> call);
partial void OnConstruction(GatewayService.GatewayServiceClient grpcClient, GatewayServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC GatewayService client</summary>
public override GatewayService.GatewayServiceClient GrpcClient { get; }
partial void Modify_HttpBody(ref ga::HttpBody request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// GetResource performs an HTTP GET request on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override ga::HttpBody GetResource(ga::HttpBody request, gaxgrpc::CallSettings callSettings = null)
{
Modify_HttpBody(ref request, ref callSettings);
return _callGetResource.Sync(request, callSettings);
}
/// <summary>
/// GetResource performs an HTTP GET request on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<ga::HttpBody> GetResourceAsync(ga::HttpBody request, gaxgrpc::CallSettings callSettings = null)
{
Modify_HttpBody(ref request, ref callSettings);
return _callGetResource.Async(request, callSettings);
}
/// <summary>
/// PostResource performs an HTTP POST on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override ga::HttpBody PostResource(ga::HttpBody request, gaxgrpc::CallSettings callSettings = null)
{
Modify_HttpBody(ref request, ref callSettings);
return _callPostResource.Sync(request, callSettings);
}
/// <summary>
/// PostResource performs an HTTP POST on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<ga::HttpBody> PostResourceAsync(ga::HttpBody request, gaxgrpc::CallSettings callSettings = null)
{
Modify_HttpBody(ref request, ref callSettings);
return _callPostResource.Async(request, callSettings);
}
/// <summary>
/// DeleteResource performs an HTTP DELETE on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override ga::HttpBody DeleteResource(ga::HttpBody request, gaxgrpc::CallSettings callSettings = null)
{
Modify_HttpBody(ref request, ref callSettings);
return _callDeleteResource.Sync(request, callSettings);
}
/// <summary>
/// DeleteResource performs an HTTP DELETE on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<ga::HttpBody> DeleteResourceAsync(ga::HttpBody request, gaxgrpc::CallSettings callSettings = null)
{
Modify_HttpBody(ref request, ref callSettings);
return _callDeleteResource.Async(request, callSettings);
}
/// <summary>
/// PutResource performs an HTTP PUT on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override ga::HttpBody PutResource(ga::HttpBody request, gaxgrpc::CallSettings callSettings = null)
{
Modify_HttpBody(ref request, ref callSettings);
return _callPutResource.Sync(request, callSettings);
}
/// <summary>
/// PutResource performs an HTTP PUT on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<ga::HttpBody> PutResourceAsync(ga::HttpBody request, gaxgrpc::CallSettings callSettings = null)
{
Modify_HttpBody(ref request, ref callSettings);
return _callPutResource.Async(request, callSettings);
}
/// <summary>
/// PatchResource performs an HTTP PATCH on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override ga::HttpBody PatchResource(ga::HttpBody request, gaxgrpc::CallSettings callSettings = null)
{
Modify_HttpBody(ref request, ref callSettings);
return _callPatchResource.Sync(request, callSettings);
}
/// <summary>
/// PatchResource performs an HTTP PATCH on the Kubernetes API Server.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<ga::HttpBody> PatchResourceAsync(ga::HttpBody request, gaxgrpc::CallSettings callSettings = null)
{
Modify_HttpBody(ref request, ref callSettings);
return _callPatchResource.Async(request, callSettings);
}
}
}
| |
#region BSD License
/*
Copyright (c) 2004 - 2008
Matthew Holmes (matthew@wildfiregames.com),
Dan Moorehead (dan05a@gmail.com),
C.J. Adams-Collier (cjac@colliertech.org),
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.
* The name of the author may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using Prebuild.Core.Attributes;
using Prebuild.Core.Interfaces;
using Prebuild.Core.Nodes;
using Prebuild.Core.Utilities;
namespace Prebuild.Core.Targets
{
/// <summary>
///
/// </summary>
[Target("nant")]
public class NAntTarget : ITarget
{
#region Fields
private Kernel m_Kernel;
#endregion
#region Private Methods
private static string PrependPath(string path)
{
string tmpPath = Helper.NormalizePath(path, '/');
Regex regex = new Regex(@"(\w):/(\w+)");
Match match = regex.Match(tmpPath);
//if(match.Success || tmpPath[0] == '.' || tmpPath[0] == '/')
//{
tmpPath = Helper.NormalizePath(tmpPath);
//}
// else
// {
// tmpPath = Helper.NormalizePath("./" + tmpPath);
// }
return tmpPath;
}
private static string BuildReference(SolutionNode solution, ProjectNode currentProject, ReferenceNode refr)
{
if (!String.IsNullOrEmpty(refr.Path))
{
return refr.Path;
}
if (solution.ProjectsTable.ContainsKey(refr.Name))
{
ProjectNode projectRef = (ProjectNode) solution.ProjectsTable[refr.Name];
string finalPath =
Helper.NormalizePath(refr.Name + GetProjectExtension(projectRef), '/');
return finalPath;
}
ProjectNode project = (ProjectNode) refr.Parent;
// Do we have an explicit file reference?
string fileRef = FindFileReference(refr.Name, project);
if (fileRef != null)
{
return fileRef;
}
// Is there an explicit path in the project ref?
if (refr.Path != null)
{
return Helper.NormalizePath(refr.Path + "/" + refr.Name + GetProjectExtension(project), '/');
}
// No, it's an extensionless GAC ref, but nant needs the .dll extension anyway
return refr.Name + ".dll";
}
public static string GetRefFileName(string refName)
{
if (ExtensionSpecified(refName))
{
return refName;
}
else
{
return refName + ".dll";
}
}
private static bool ExtensionSpecified(string refName)
{
return refName.EndsWith(".dll") || refName.EndsWith(".exe");
}
private static string GetProjectExtension(ProjectNode project)
{
string extension = ".dll";
if (project.Type == ProjectType.Exe || project.Type == ProjectType.WinExe)
{
extension = ".exe";
}
return extension;
}
private static string FindFileReference(string refName, ProjectNode project)
{
foreach (ReferencePathNode refPath in project.ReferencePaths)
{
string fullPath = Helper.MakeFilePath(refPath.Path, refName);
if (File.Exists(fullPath))
{
return fullPath;
}
fullPath = Helper.MakeFilePath(refPath.Path, refName, "dll");
if (File.Exists(fullPath))
{
return fullPath;
}
fullPath = Helper.MakeFilePath(refPath.Path, refName, "exe");
if (File.Exists(fullPath))
{
return fullPath;
}
}
return null;
}
/// <summary>
/// Gets the XML doc file.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="conf">The conf.</param>
/// <returns></returns>
public static string GetXmlDocFile(ProjectNode project, ConfigurationNode conf)
{
if (conf == null)
{
throw new ArgumentNullException("conf");
}
if (project == null)
{
throw new ArgumentNullException("project");
}
string docFile = (string)conf.Options["XmlDocFile"];
// if(docFile != null && docFile.Length == 0)//default to assembly name if not specified
// {
// return Path.GetFileNameWithoutExtension(project.AssemblyName) + ".xml";
// }
return docFile;
}
private void WriteProject(SolutionNode solution, ProjectNode project)
{
string projFile = Helper.MakeFilePath(project.FullPath, project.Name + GetProjectExtension(project), "build");
StreamWriter ss = new StreamWriter(projFile);
m_Kernel.CurrentWorkingDirectory.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(projFile));
bool hasDoc = false;
using (ss)
{
ss.WriteLine("<?xml version=\"1.0\" ?>");
ss.WriteLine("<project name=\"{0}\" default=\"build\">", project.Name);
ss.WriteLine(" <target name=\"{0}\">", "build");
ss.WriteLine(" <echo message=\"Build Directory is ${project::get-base-directory()}/${build.dir}\" />");
ss.WriteLine(" <mkdir dir=\"${project::get-base-directory()}/${build.dir}\" />");
ss.WriteLine(" <copy todir=\"${project::get-base-directory()}/${build.dir}\" flatten=\"true\">");
ss.WriteLine(" <fileset basedir=\"${project::get-base-directory()}\">");
foreach (ReferenceNode refr in project.References)
{
if (refr.LocalCopy)
{
ss.WriteLine(" <include name=\"{0}", Helper.NormalizePath(Helper.MakePathRelativeTo(project.FullPath, BuildReference(solution, project, refr)) + "\" />", '/'));
}
}
ss.WriteLine(" </fileset>");
ss.WriteLine(" </copy>");
if (project.ConfigFile != null && project.ConfigFile.Length!=0)
{
ss.Write(" <copy file=\"" + project.ConfigFile + "\" tofile=\"${project::get-base-directory()}/${build.dir}/${project::get-name()}");
if (project.Type == ProjectType.Library)
{
ss.Write(".dll.config\"");
}
else
{
ss.Write(".exe.config\"");
}
ss.WriteLine(" />");
}
// Add the content files to just be copied
ss.WriteLine(" {0}", "<copy todir=\"${project::get-base-directory()}/${build.dir}\">");
ss.WriteLine(" {0}", "<fileset basedir=\".\">");
foreach (string file in project.Files)
{
// Ignore if we aren't content
if (project.Files.GetBuildAction(file) != BuildAction.Content)
continue;
// Create a include tag
ss.WriteLine(" {0}", "<include name=\"" + Helper.NormalizePath(PrependPath(file), '/') + "\" />");
}
ss.WriteLine(" {0}", "</fileset>");
ss.WriteLine(" {0}", "</copy>");
ss.Write(" <csc ");
ss.Write(" target=\"{0}\"", project.Type.ToString().ToLower());
ss.Write(" debug=\"{0}\"", "${build.debug}");
ss.Write(" platform=\"${build.platform}\"");
foreach (ConfigurationNode conf in project.Configurations)
{
if (conf.Options.KeyFile != "")
{
ss.Write(" keyfile=\"{0}\"", conf.Options.KeyFile);
break;
}
}
foreach (ConfigurationNode conf in project.Configurations)
{
ss.Write(" unsafe=\"{0}\"", conf.Options.AllowUnsafe);
break;
}
foreach (ConfigurationNode conf in project.Configurations)
{
ss.Write(" warnaserror=\"{0}\"", conf.Options.WarningsAsErrors);
break;
}
foreach (ConfigurationNode conf in project.Configurations)
{
ss.Write(" define=\"{0}\"", conf.Options.CompilerDefines);
break;
}
foreach (ConfigurationNode conf in project.Configurations)
{
ss.Write(" nostdlib=\"{0}\"", conf.Options["NoStdLib"]);
break;
}
ss.Write(" main=\"{0}\"", project.StartupObject);
foreach (ConfigurationNode conf in project.Configurations)
{
if (GetXmlDocFile(project, conf) != "")
{
ss.Write(" doc=\"{0}\"", "${project::get-base-directory()}/${build.dir}/" + GetXmlDocFile(project, conf));
hasDoc = true;
}
break;
}
ss.Write(" output=\"{0}", "${project::get-base-directory()}/${build.dir}/${project::get-name()}");
if (project.Type == ProjectType.Library)
{
ss.Write(".dll\"");
}
else
{
ss.Write(".exe\"");
}
if (project.AppIcon != null && project.AppIcon.Length != 0)
{
ss.Write(" win32icon=\"{0}\"", Helper.NormalizePath(project.AppIcon, '/'));
}
// This disables a very different behavior between VS and NAnt. With Nant,
// If you have using System.Xml; it will ensure System.Xml.dll is referenced,
// but not in VS. This will force the behaviors to match, so when it works
// in nant, it will work in VS.
ss.Write(" noconfig=\"true\"");
ss.WriteLine(">");
ss.WriteLine(" <resources prefix=\"{0}\" dynamicprefix=\"true\" >", project.RootNamespace);
foreach (string file in project.Files)
{
switch (project.Files.GetBuildAction(file))
{
case BuildAction.EmbeddedResource:
ss.WriteLine(" {0}", "<include name=\"" + Helper.NormalizePath(PrependPath(file), '/') + "\" />");
break;
default:
if (project.Files.GetSubType(file) != SubType.Code && project.Files.GetSubType(file) != SubType.Settings)
{
ss.WriteLine(" <include name=\"{0}\" />", file.Substring(0, file.LastIndexOf('.')) + ".resx");
}
break;
}
}
//if (project.Files.GetSubType(file).ToString() != "Code")
//{
// ps.WriteLine(" <EmbeddedResource Include=\"{0}\">", file.Substring(0, file.LastIndexOf('.')) + ".resx");
ss.WriteLine(" </resources>");
ss.WriteLine(" <sources failonempty=\"true\">");
foreach (string file in project.Files)
{
switch (project.Files.GetBuildAction(file))
{
case BuildAction.Compile:
ss.WriteLine(" <include name=\"" + Helper.NormalizePath(PrependPath(file), '/') + "\" />");
break;
default:
break;
}
}
ss.WriteLine(" </sources>");
ss.WriteLine(" <references basedir=\"${project::get-base-directory()}\">");
ss.WriteLine(" <lib>");
ss.WriteLine(" <include name=\"${project::get-base-directory()}\" />");
foreach(ReferencePathNode refPath in project.ReferencePaths)
{
ss.WriteLine(" <include name=\"${project::get-base-directory()}/" + refPath.Path.TrimEnd('/', '\\') + "\" />");
}
ss.WriteLine(" </lib>");
foreach (ReferenceNode refr in project.References)
{
string path = Helper.NormalizePath(Helper.MakePathRelativeTo(project.FullPath, BuildReference(solution, project, refr)), '/');
if (refr.Path != null) {
if (ExtensionSpecified(refr.Name))
{
ss.WriteLine (" <include name=\"" + path + refr.Name + "\"/>");
}
else
{
ss.WriteLine (" <include name=\"" + path + refr.Name + ".dll\"/>");
}
}
else
{
ss.WriteLine (" <include name=\"" + path + "\" />");
}
}
ss.WriteLine(" </references>");
ss.WriteLine(" </csc>");
foreach (ConfigurationNode conf in project.Configurations)
{
if (!String.IsNullOrEmpty(conf.Options.OutputPath))
{
string targetDir = Helper.NormalizePath(conf.Options.OutputPath, '/');
ss.WriteLine(" <echo message=\"Copying from [${project::get-base-directory()}/${build.dir}/] to [${project::get-base-directory()}/" + targetDir + "\" />");
ss.WriteLine(" <mkdir dir=\"${project::get-base-directory()}/" + targetDir + "\"/>");
ss.WriteLine(" <copy todir=\"${project::get-base-directory()}/" + targetDir + "\">");
ss.WriteLine(" <fileset basedir=\"${project::get-base-directory()}/${build.dir}/\" >");
ss.WriteLine(" <include name=\"*.dll\"/>");
ss.WriteLine(" <include name=\"*.exe\"/>");
ss.WriteLine(" <include name=\"*.mdb\" if='${build.debug}'/>");
ss.WriteLine(" <include name=\"*.pdb\" if='${build.debug}'/>");
ss.WriteLine(" </fileset>");
ss.WriteLine(" </copy>");
break;
}
}
ss.WriteLine(" </target>");
ss.WriteLine(" <target name=\"clean\">");
ss.WriteLine(" <delete dir=\"${bin.dir}\" failonerror=\"false\" />");
ss.WriteLine(" <delete dir=\"${obj.dir}\" failonerror=\"false\" />");
ss.WriteLine(" </target>");
ss.WriteLine(" <target name=\"doc\" description=\"Creates documentation.\">");
if (hasDoc)
{
ss.WriteLine(" <property name=\"doc.target\" value=\"\" />");
ss.WriteLine(" <if test=\"${platform::is-unix()}\">");
ss.WriteLine(" <property name=\"doc.target\" value=\"Web\" />");
ss.WriteLine(" </if>");
ss.WriteLine(" <ndoc failonerror=\"false\" verbose=\"true\">");
ss.WriteLine(" <assemblies basedir=\"${project::get-base-directory()}\">");
ss.Write(" <include name=\"${build.dir}/${project::get-name()}");
if (project.Type == ProjectType.Library)
{
ss.WriteLine(".dll\" />");
}
else
{
ss.WriteLine(".exe\" />");
}
ss.WriteLine(" </assemblies>");
ss.WriteLine(" <summaries basedir=\"${project::get-base-directory()}\">");
ss.WriteLine(" <include name=\"${build.dir}/${project::get-name()}.xml\"/>");
ss.WriteLine(" </summaries>");
ss.WriteLine(" <referencepaths basedir=\"${project::get-base-directory()}\">");
ss.WriteLine(" <include name=\"${build.dir}\" />");
// foreach(ReferenceNode refr in project.References)
// {
// string path = Helper.NormalizePath(Helper.MakePathRelativeTo(project.FullPath, BuildReferencePath(solution, refr)), '/');
// if (path != "")
// {
// ss.WriteLine(" <include name=\"{0}\" />", path);
// }
// }
ss.WriteLine(" </referencepaths>");
ss.WriteLine(" <documenters>");
ss.WriteLine(" <documenter name=\"MSDN\">");
ss.WriteLine(" <property name=\"OutputDirectory\" value=\"${project::get-base-directory()}/${build.dir}/doc/${project::get-name()}\" />");
ss.WriteLine(" <property name=\"OutputTarget\" value=\"${doc.target}\" />");
ss.WriteLine(" <property name=\"HtmlHelpName\" value=\"${project::get-name()}\" />");
ss.WriteLine(" <property name=\"IncludeFavorites\" value=\"False\" />");
ss.WriteLine(" <property name=\"Title\" value=\"${project::get-name()} SDK Documentation\" />");
ss.WriteLine(" <property name=\"SplitTOCs\" value=\"False\" />");
ss.WriteLine(" <property name=\"DefaulTOC\" value=\"\" />");
ss.WriteLine(" <property name=\"ShowVisualBasic\" value=\"True\" />");
ss.WriteLine(" <property name=\"AutoDocumentConstructors\" value=\"True\" />");
ss.WriteLine(" <property name=\"ShowMissingSummaries\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"ShowMissingRemarks\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"ShowMissingParams\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"ShowMissingReturns\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"ShowMissingValues\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"DocumentInternals\" value=\"False\" />");
ss.WriteLine(" <property name=\"DocumentPrivates\" value=\"False\" />");
ss.WriteLine(" <property name=\"DocumentProtected\" value=\"True\" />");
ss.WriteLine(" <property name=\"DocumentEmptyNamespaces\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"IncludeAssemblyVersion\" value=\"True\" />");
ss.WriteLine(" </documenter>");
ss.WriteLine(" </documenters>");
ss.WriteLine(" </ndoc>");
}
ss.WriteLine(" </target>");
ss.WriteLine("</project>");
}
m_Kernel.CurrentWorkingDirectory.Pop();
}
private void WriteCombine(SolutionNode solution)
{
m_Kernel.Log.Write("Creating NAnt build files");
foreach (ProjectNode project in solution.Projects)
{
if (m_Kernel.AllowProject(project.FilterGroups))
{
m_Kernel.Log.Write("...Creating project: {0}", project.Name);
WriteProject(solution, project);
}
}
m_Kernel.Log.Write("");
string combFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "build");
StreamWriter ss = new StreamWriter(combFile);
m_Kernel.CurrentWorkingDirectory.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(combFile));
using (ss)
{
ss.WriteLine("<?xml version=\"1.0\" ?>");
ss.WriteLine("<project name=\"{0}\" default=\"build\">", solution.Name);
ss.WriteLine(" <echo message=\"Using '${nant.settings.currentframework}' Framework\"/>");
ss.WriteLine();
//ss.WriteLine(" <property name=\"dist.dir\" value=\"dist\" />");
//ss.WriteLine(" <property name=\"source.dir\" value=\"source\" />");
ss.WriteLine(" <property name=\"bin.dir\" value=\"bin\" />");
ss.WriteLine(" <property name=\"obj.dir\" value=\"obj\" />");
ss.WriteLine(" <property name=\"doc.dir\" value=\"doc\" />");
ss.WriteLine(" <property name=\"project.main.dir\" value=\"${project::get-base-directory()}\" />");
// Use the active configuration, which is the first configuration name in the prebuild file.
Dictionary<string,string> emittedConfigurations = new Dictionary<string, string>();
ss.WriteLine(" <property name=\"project.config\" value=\"{0}\" />", solution.ActiveConfig);
ss.WriteLine();
foreach (ConfigurationNode conf in solution.Configurations)
{
// If the name isn't in the emitted configurations, we give a high level target to the
// platform specific on. This lets "Debug" point to "Debug-AnyCPU".
if (!emittedConfigurations.ContainsKey(conf.Name))
{
// Add it to the dictionary so we only emit one.
emittedConfigurations.Add(conf.Name, conf.Platform);
// Write out the target block.
ss.WriteLine(" <target name=\"{0}\" description=\"{0}|{1}\" depends=\"{0}-{1}\">", conf.Name, conf.Platform);
ss.WriteLine(" </target>");
ss.WriteLine();
}
// Write out the target for the configuration.
ss.WriteLine(" <target name=\"{0}-{1}\" description=\"{0}|{1}\">", conf.Name, conf.Platform);
ss.WriteLine(" <property name=\"project.config\" value=\"{0}\" />", conf.Name);
ss.WriteLine(" <property name=\"build.debug\" value=\"{0}\" />", conf.Options["DebugInformation"].ToString().ToLower());
ss.WriteLine("\t\t <property name=\"build.platform\" value=\"{0}\" />", conf.Platform);
ss.WriteLine(" </target>");
ss.WriteLine();
}
ss.WriteLine(" <target name=\"net-1.1\" description=\"Sets framework to .NET 1.1\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"net-1.1\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"net-2.0\" description=\"Sets framework to .NET 2.0\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"net-2.0\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"net-3.5\" description=\"Sets framework to .NET 3.5\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"net-3.5\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"mono-1.0\" description=\"Sets framework to mono 1.0\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"mono-1.0\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"mono-2.0\" description=\"Sets framework to mono 2.0\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"mono-2.0\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"mono-3.5\" description=\"Sets framework to mono 3.5\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"mono-3.5\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"init\" description=\"\">");
ss.WriteLine(" <call target=\"${project.config}\" />");
ss.WriteLine(" <property name=\"sys.os.platform\"");
ss.WriteLine(" value=\"${platform::get-name()}\"");
ss.WriteLine(" />");
ss.WriteLine(" <echo message=\"Platform ${sys.os.platform}\" />");
ss.WriteLine(" <property name=\"build.dir\" value=\"${bin.dir}/${project.config}\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
// sdague - ok, this is an ugly hack, but what it lets
// us do is native include of files into the nant
// created files from all .nant/*include files. This
// lets us keep using prebuild, but allows for
// extended nant targets to do build and the like.
try
{
Regex re = new Regex(".include$");
DirectoryInfo nantdir = new DirectoryInfo(".nant");
foreach (FileSystemInfo item in nantdir.GetFileSystemInfos())
{
if (item is DirectoryInfo) { }
else if (item is FileInfo)
{
if (re.Match(item.FullName) !=
System.Text.RegularExpressions.Match.Empty)
{
Console.WriteLine("Including file: " + item.FullName);
using (FileStream fs = new FileStream(item.FullName,
FileMode.Open,
FileAccess.Read,
FileShare.None))
{
using (StreamReader sr = new StreamReader(fs))
{
ss.WriteLine("<!-- included from {0} -->", (item).FullName);
while (sr.Peek() != -1)
{
ss.WriteLine(sr.ReadLine());
}
ss.WriteLine();
}
}
}
}
}
}
catch { }
// ss.WriteLine(" <include buildfile=\".nant/local.include\" />");
// ss.WriteLine(" <target name=\"zip\" description=\"\">");
// ss.WriteLine(" <zip zipfile=\"{0}-{1}.zip\">", solution.Name, solution.Version);
// ss.WriteLine(" <fileset basedir=\"${project::get-base-directory()}\">");
// ss.WriteLine(" <include name=\"${project::get-base-directory()}/**/*.cs\" />");
// // ss.WriteLine(" <include name=\"${project.main.dir}/**/*\" />");
// ss.WriteLine(" </fileset>");
// ss.WriteLine(" </zip>");
// ss.WriteLine(" <echo message=\"Building zip target\" />");
// ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"clean\" description=\"\">");
ss.WriteLine(" <echo message=\"Deleting all builds from all configurations\" />");
//ss.WriteLine(" <delete dir=\"${dist.dir}\" failonerror=\"false\" />");
if (solution.Cleanup != null && solution.Cleanup.CleanFiles.Count > 0)
{
foreach (CleanFilesNode cleanFile in solution.Cleanup.CleanFiles)
{
ss.WriteLine(" <delete failonerror=\"false\">");
ss.WriteLine(" <fileset basedir=\"${project::get-base-directory()}\">");
ss.WriteLine(" <include name=\"{0}/*\"/>", cleanFile.Pattern);
ss.WriteLine(" <include name=\"{0}\"/>", cleanFile.Pattern);
ss.WriteLine(" </fileset>");
ss.WriteLine(" </delete>");
}
}
ss.WriteLine(" <delete dir=\"${obj.dir}\" failonerror=\"false\" />");
foreach (ProjectNode project in solution.Projects)
{
string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
ss.Write(" <nant buildfile=\"{0}\"",
Helper.NormalizePath(Helper.MakeFilePath(path, project.Name + GetProjectExtension(project), "build"), '/'));
ss.WriteLine(" target=\"clean\" />");
}
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"build\" depends=\"init\" description=\"\">");
foreach (ProjectNode project in solution.ProjectsTableOrder)
{
string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
ss.Write(" <nant buildfile=\"{0}\"",
Helper.NormalizePath(Helper.MakeFilePath(path, project.Name + GetProjectExtension(project), "build"), '/'));
ss.WriteLine(" target=\"build\" />");
}
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"build-release\" depends=\"Release, init, build\" description=\"Builds in Release mode\" />");
ss.WriteLine();
ss.WriteLine(" <target name=\"build-debug\" depends=\"Debug, init, build\" description=\"Builds in Debug mode\" />");
ss.WriteLine();
//ss.WriteLine(" <target name=\"package\" depends=\"clean, doc, copyfiles, zip\" description=\"Builds in Release mode\" />");
ss.WriteLine(" <target name=\"package\" depends=\"clean, doc\" description=\"Builds all\" />");
ss.WriteLine();
ss.WriteLine(" <target name=\"doc\" depends=\"build-release\">");
ss.WriteLine(" <echo message=\"Generating all documentation from all builds\" />");
foreach (ProjectNode project in solution.Projects)
{
string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
ss.Write(" <nant buildfile=\"{0}\"",
Helper.NormalizePath(Helper.MakeFilePath(path, project.Name + GetProjectExtension(project), "build"), '/'));
ss.WriteLine(" target=\"doc\" />");
}
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine("</project>");
}
m_Kernel.CurrentWorkingDirectory.Pop();
}
private void CleanProject(ProjectNode project)
{
m_Kernel.Log.Write("...Cleaning project: {0}", project.Name);
string projectFile = Helper.MakeFilePath(project.FullPath, project.Name + GetProjectExtension(project), "build");
Helper.DeleteIfExists(projectFile);
}
private void CleanSolution(SolutionNode solution)
{
m_Kernel.Log.Write("Cleaning NAnt build files for", solution.Name);
string slnFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "build");
Helper.DeleteIfExists(slnFile);
foreach (ProjectNode project in solution.Projects)
{
CleanProject(project);
}
m_Kernel.Log.Write("");
}
#endregion
#region ITarget Members
/// <summary>
/// Writes the specified kern.
/// </summary>
/// <param name="kern">The kern.</param>
public void Write(Kernel kern)
{
if (kern == null)
{
throw new ArgumentNullException("kern");
}
m_Kernel = kern;
foreach (SolutionNode solution in kern.Solutions)
{
WriteCombine(solution);
}
m_Kernel = null;
}
/// <summary>
/// Cleans the specified kern.
/// </summary>
/// <param name="kern">The kern.</param>
public virtual void Clean(Kernel kern)
{
if (kern == null)
{
throw new ArgumentNullException("kern");
}
m_Kernel = kern;
foreach (SolutionNode sol in kern.Solutions)
{
CleanSolution(sol);
}
m_Kernel = null;
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name
{
get
{
return "nant";
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using System.Net;
using System.Runtime.InteropServices;
public class Program {
class MyProxyImpl : System.Net.IWebProxy
{
private Uri uri;
private readonly Uri bypassed = new Uri("http://www.httpbin.org/get");
public MyProxyImpl(string uriString)
{
uri = new Uri(uriString);
}
public ICredentials Credentials {get;set;}
public Uri GetProxy(Uri destUri){
return uri;
}
public bool IsBypassed(Uri targetUri){
return bypassed.Equals(targetUri);
}
}
class MyCreds : ICredentials
{
public MyCreds() {
}
public NetworkCredential GetCredential(Uri u, string authType)
{
var c = new NetworkCredential("skapila", "blah");
c.UserName = "skapila";
c.Password = "blah";
return c;
}
}
public static void DoProxyForUrl(string url) {
var proxy = new MyProxyImpl("http://localhost:8394");
var credential = new System.Net.NetworkCredential("skapila","blah","FAREAST");
credential.UserName = "skapila";
credential.Password = "blah";
credential.Domain = "FAREAST";
proxy.Credentials = credential;
var clientHandler = new HttpClientHandler();
clientHandler.Proxy = proxy;
clientHandler.UseProxy = true;
var httpClient = new HttpClient(clientHandler);
httpClient.MaxResponseContentBufferSize = 256000;
httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
try{
var responseTask = httpClient.GetAsync(url);
responseTask.Wait();
HttpResponseMessage response = responseTask.Result;
// response.EnsureSuccessStatusCode();
if(response.Content != null) {
var readTask = response.Content.ReadAsStringAsync();
readTask.Wait();
Console.WriteLine(readTask.Result);
}
else
{
Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase + Environment.NewLine);
}
}
catch(Exception e)
{
Console.WriteLine(e);
}
finally
{
Console.WriteLine("disposing");
clientHandler.Dispose();
httpClient.Dispose();
}
}
public static void DoProxy() {
// DoProxyForUrl("http://www.example.com/example.html");
DoProxyForUrl("http://www.httpbin.org/get/");
Console.WriteLine("Done with 1");
DoProxyForUrl("http://www.httpbin.org/get/");
}
public static void DeCompressionTest(string url) {
var clientHandler = new HttpClientHandler();
clientHandler.AutomaticDecompression = DecompressionMethods.None;
//clientHandler.AutomaticDecompression = DecompressionMethods.Deflate;
clientHandler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
var httpClient = new HttpClient(clientHandler);
httpClient.MaxResponseContentBufferSize = 256000;
httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
try{
var responseTask = httpClient.GetAsync(url);
responseTask.Wait();
HttpResponseMessage response = responseTask.Result;
response.EnsureSuccessStatusCode();
if(response.Content != null) {
var readTask = response.Content.ReadAsStringAsync();
readTask.Wait();
Console.WriteLine("*****");
Console.WriteLine(readTask.Result);
}
else
{
Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase + Environment.NewLine);
}
}
catch(Exception e)
{
Console.WriteLine(e);
return ;
}
finally{
Console.WriteLine("disposing");
clientHandler.Dispose();
httpClient.Dispose();
}
return;
}
public static void DoPut() {
var httpClient = new HttpClient();
httpClient.MaxResponseContentBufferSize = 256000;
httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
try{
var responseTask = httpClient.PutAsync("https://hkrest.azurewebsites.net/api/Values/1", new StringContent("blah"));
responseTask.Wait();
HttpResponseMessage response = responseTask.Result;
response.EnsureSuccessStatusCode();
if(response.Content != null) {
var readTask = response.Content.ReadAsStringAsync();
readTask.Wait();
Console.WriteLine(readTask.Result);
}
else
{
Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase + Environment.NewLine);
}
}
catch(Exception e)
{
Console.WriteLine(e);
return ;
}
return;
}
public static void DoCredentialTest(string url) {
var credential = new MyCreds();
var clientHandler = new HttpClientHandler();
clientHandler.Credentials = credential;
clientHandler.PreAuthenticate = true;
var httpClient = new HttpClient(clientHandler);
httpClient.MaxResponseContentBufferSize = 256000;
httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
try{
var responseTask = httpClient.GetAsync(url);
responseTask.Wait();
HttpResponseMessage response = responseTask.Result;
response.EnsureSuccessStatusCode();
if(response.Content != null) {
var readTask = response.Content.ReadAsStreamAsync();
readTask.Wait();
Console.WriteLine(readTask.Result);
}
else
{
Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase + Environment.NewLine);
}
}
catch(Exception e)
{
Console.WriteLine(e);
return ;
}
return;
}
public static void DoGet() {
var httpClient = new HttpClient();
httpClient.MaxResponseContentBufferSize = 256000;
httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
try{
// var responseTask = httpClient.GetAsync("https://hkrest.azurewebsites.net/api/Values");
var responseTask = httpClient.GetAsync("http://www.example.com/example.html");
responseTask.Wait();
HttpResponseMessage response = responseTask.Result;
// response.EnsureSuccessStatusCode();
if(response.Content != null) {
var readTask = response.Content.ReadAsStreamAsync();
readTask.Wait();
Console.WriteLine(readTask.Result);
}
else
{
Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase + Environment.NewLine);
}
}
catch(Exception e)
{
Console.WriteLine(e);
return ;
}
finally
{
httpClient.Dispose();
}
return;
}
public static void Main(string[] args) {
Console.WriteLine("Initializing " );
if (args.Length < 1) {
Console.WriteLine("running Get");
DoGet();
Console.WriteLine("Second run");
DoGet();
return;
}
var arg = args[0];
if(arg.Contains("G") || arg.Contains("g")) {
Console.WriteLine("running Get");
DoGet();
}
if(arg.Contains("p") || arg.Contains("P")) {
Console.WriteLine("running PUT");
DoPut();
}
if(arg.Contains("x") || arg.Contains("X")) {
Console.WriteLine("running Proxy Test");
DoProxy();
}
if(arg.Contains("d") || arg.Contains("D")) {
var url = "http://www.example.com";
if(args.Length > 1)
url = args[1];
Console.WriteLine("running decompression tests for {0}", url);
DeCompressionTest(url);
}
if(arg.Contains("A") || arg.Contains("a")) {
var url = "http://httpbin.org/get";
if (args.Length > 1)
url = args[1];
Console.WriteLine("running authentication tests for {0}", url);
DoCredentialTest(url);
}
// if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)){
// System.Console.WriteLine("It is OSX");
// }
// else{
// System.Console.WriteLine("It is windows");
// }
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.Debugger.Interop;
using MICore;
using System.Diagnostics;
using System.Globalization;
// This file contains the various event objects that are sent to the debugger from the sample engine via IDebugEventCallback2::Event.
// These are used in EngineCallback.cs.
// The events are how the engine tells the debugger about what is happening in the debuggee process.
// There are three base classe the other events derive from: AD7AsynchronousEvent, AD7StoppingEvent, and AD7SynchronousEvent. These
// each implement the IDebugEvent2.GetAttributes method for the type of event they represent.
// Most events sent the debugger are asynchronous events.
namespace Microsoft.MIDebugEngine
{
#region Event base classes
internal class AD7AsynchronousEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return Constants.S_OK;
}
}
internal class AD7StoppingEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNC_STOP;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return Constants.S_OK;
}
}
internal class AD7SynchronousEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return Constants.S_OK;
}
}
internal class AD7SynchronousStoppingEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_STOPPING | (uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return Constants.S_OK;
}
}
#endregion
// The debug engine (DE) sends this interface to the session debug manager (SDM) when an instance of the DE is created.
internal sealed class AD7EngineCreateEvent : AD7AsynchronousEvent, IDebugEngineCreateEvent2
{
public const string IID = "FE5B734C-759D-4E59-AB04-F103343BDD06";
private IDebugEngine2 _engine;
private AD7EngineCreateEvent(AD7Engine engine)
{
_engine = engine;
}
public static void Send(AD7Engine engine)
{
AD7EngineCreateEvent eventObject = new AD7EngineCreateEvent(engine);
engine.Callback.Send(eventObject, IID, null, null);
}
int IDebugEngineCreateEvent2.GetEngine(out IDebugEngine2 engine)
{
engine = _engine;
return Constants.S_OK;
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is attached to.
internal sealed class AD7ProgramCreateEvent : AD7SynchronousEvent, IDebugProgramCreateEvent2
{
public const string IID = "96CD11EE-ECD4-4E89-957E-B5D496FC4139";
internal static void Send(AD7Engine engine)
{
AD7ProgramCreateEvent eventObject = new AD7ProgramCreateEvent();
engine.Callback.Send(eventObject, IID, engine, null);
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a module is loaded or unloaded.
internal sealed class AD7ModuleLoadEvent : AD7AsynchronousEvent, IDebugModuleLoadEvent2
{
public const string IID = "989DB083-0D7C-40D1-A9D9-921BF611A4B2";
private readonly AD7Module _module;
private readonly bool _fLoad;
public AD7ModuleLoadEvent(AD7Module module, bool fLoad)
{
_module = module;
_fLoad = fLoad;
}
int IDebugModuleLoadEvent2.GetModule(out IDebugModule2 module, ref string debugMessage, ref int fIsLoad)
{
module = _module;
if (_fLoad)
{
string symbolLoadStatus = _module.DebuggedModule.SymbolsLoaded ?
ResourceStrings.ModuleLoadedWithSymbols :
ResourceStrings.ModuleLoadedWithoutSymbols;
debugMessage = string.Format(CultureInfo.CurrentCulture, ResourceStrings.ModuleLoadMessage, _module.DebuggedModule.Name, symbolLoadStatus);
fIsLoad = 1;
}
else
{
debugMessage = string.Format(CultureInfo.CurrentCulture, ResourceStrings.ModuleUnloadMessage, _module.DebuggedModule.Name);
fIsLoad = 0;
}
return Constants.S_OK;
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a modules symbols are loaded.
internal sealed class AD7SymbolLoadEvent : AD7AsynchronousEvent, IDebugSymbolSearchEvent2
{
public const string IID = "EA5B9681-2CE5-4F7A-B842-5183911CE5C6";
private readonly AD7Module _module;
public AD7SymbolLoadEvent(AD7Module module)
{
_module = module;
}
int IDebugSymbolSearchEvent2.GetSymbolSearchInfo(out IDebugModule3 pModule, ref string pbstrDebugMessage, enum_MODULE_INFO_FLAGS[] pdwModuleInfoFlags)
{
pModule = _module;
pdwModuleInfoFlags[0] = enum_MODULE_INFO_FLAGS.MIF_SYMBOLS_LOADED;
return Constants.S_OK;
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program has run to completion
// or is otherwise destroyed.
internal sealed class AD7ProgramDestroyEvent : AD7SynchronousEvent, IDebugProgramDestroyEvent2
{
public const string IID = "E147E9E3-6440-4073-A7B7-A65592C714B5";
private readonly uint _exitCode;
public AD7ProgramDestroyEvent(uint exitCode)
{
_exitCode = exitCode;
}
#region IDebugProgramDestroyEvent2 Members
int IDebugProgramDestroyEvent2.GetExitCode(out uint exitCode)
{
exitCode = _exitCode;
return Constants.S_OK;
}
#endregion
}
internal sealed class AD7MessageEvent : IDebugEvent2, IDebugMessageEvent2
{
public const string IID = "3BDB28CF-DBD2-4D24-AF03-01072B67EB9E";
private readonly OutputMessage _outputMessage;
private readonly bool _isAsync;
public AD7MessageEvent(OutputMessage outputMessage, bool isAsync)
{
_outputMessage = outputMessage;
_isAsync = isAsync;
}
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
if (_isAsync)
eventAttributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS;
else
eventAttributes = (uint)enum_EVENTATTRIBUTES.EVENT_IMMEDIATE;
return Constants.S_OK;
}
int IDebugMessageEvent2.GetMessage(enum_MESSAGETYPE[] pMessageType, out string pbstrMessage, out uint pdwType, out string pbstrHelpFileName, out uint pdwHelpId)
{
return ConvertMessageToAD7(_outputMessage, pMessageType, out pbstrMessage, out pdwType, out pbstrHelpFileName, out pdwHelpId);
}
internal static int ConvertMessageToAD7(OutputMessage outputMessage, enum_MESSAGETYPE[] pMessageType, out string pbstrMessage, out uint pdwType, out string pbstrHelpFileName, out uint pdwHelpId)
{
const uint MB_ICONERROR = 0x00000010;
const uint MB_ICONWARNING = 0x00000030;
pMessageType[0] = outputMessage.MessageType;
pbstrMessage = outputMessage.Message;
pdwType = 0;
if ((outputMessage.MessageType & enum_MESSAGETYPE.MT_TYPE_MASK) == enum_MESSAGETYPE.MT_MESSAGEBOX)
{
switch (outputMessage.SeverityValue)
{
case OutputMessage.Severity.Error:
pdwType |= MB_ICONERROR;
break;
case OutputMessage.Severity.Warning:
pdwType |= MB_ICONWARNING;
break;
}
}
pbstrHelpFileName = null;
pdwHelpId = 0;
return Constants.S_OK;
}
int IDebugMessageEvent2.SetResponse(uint dwResponse)
{
return Constants.S_OK;
}
}
internal sealed class AD7ErrorEvent : IDebugEvent2, IDebugErrorEvent2
{
public const string IID = "FDB7A36C-8C53-41DA-A337-8BD86B14D5CB";
private readonly OutputMessage _outputMessage;
private readonly bool _isAsync;
public AD7ErrorEvent(OutputMessage outputMessage, bool isAsync)
{
_outputMessage = outputMessage;
_isAsync = isAsync;
}
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
if (_isAsync)
eventAttributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS;
else
eventAttributes = (uint)enum_EVENTATTRIBUTES.EVENT_IMMEDIATE;
return Constants.S_OK;
}
int IDebugErrorEvent2.GetErrorMessage(enum_MESSAGETYPE[] pMessageType, out string errorFormat, out int hrErrorReason, out uint pdwType, out string helpFilename, out uint pdwHelpId)
{
hrErrorReason = unchecked((int)_outputMessage.ErrorCode);
return AD7MessageEvent.ConvertMessageToAD7(_outputMessage, pMessageType, out errorFormat, out pdwType, out helpFilename, out pdwHelpId);
}
}
internal sealed class AD7BreakpointErrorEvent : AD7AsynchronousEvent, IDebugBreakpointErrorEvent2
{
public const string IID = "ABB0CA42-F82B-4622-84E4-6903AE90F210";
private AD7ErrorBreakpoint _error;
public AD7BreakpointErrorEvent(AD7ErrorBreakpoint error)
{
_error = error;
}
public int GetErrorBreakpoint(out IDebugErrorBreakpoint2 ppErrorBP)
{
ppErrorBP = _error;
return Constants.S_OK;
}
}
internal sealed class AD7BreakpointUnboundEvent : AD7AsynchronousEvent, IDebugBreakpointUnboundEvent2
{
public const string IID = "78d1db4f-c557-4dc5-a2dd-5369d21b1c8c";
private readonly enum_BP_UNBOUND_REASON _reason;
private AD7BoundBreakpoint _bp;
public AD7BreakpointUnboundEvent(AD7BoundBreakpoint bp, enum_BP_UNBOUND_REASON reason)
{
_reason = reason;
_bp = bp;
}
public int GetBreakpoint(out IDebugBoundBreakpoint2 ppBP)
{
ppBP = _bp;
return Constants.S_OK;
}
public int GetReason(enum_BP_UNBOUND_REASON[] pdwUnboundReason)
{
pdwUnboundReason[0] = _reason;
return Constants.S_OK;
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread is created in a program being debugged.
internal sealed class AD7ThreadCreateEvent : AD7AsynchronousEvent, IDebugThreadCreateEvent2
{
public const string IID = "2090CCFC-70C5-491D-A5E8-BAD2DD9EE3EA";
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread has exited.
internal sealed class AD7ThreadDestroyEvent : AD7AsynchronousEvent, IDebugThreadDestroyEvent2
{
public const string IID = "2C3B7532-A36F-4A6E-9072-49BE649B8541";
private readonly uint _exitCode;
public AD7ThreadDestroyEvent(uint exitCode)
{
_exitCode = exitCode;
}
#region IDebugThreadDestroyEvent2 Members
int IDebugThreadDestroyEvent2.GetExitCode(out uint exitCode)
{
exitCode = _exitCode;
return Constants.S_OK;
}
#endregion
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is loaded, but before any code is executed.
internal sealed class AD7LoadCompleteEvent : AD7AsynchronousEvent, IDebugLoadCompleteEvent2
{
public const string IID = "B1844850-1349-45D4-9F12-495212F5EB0B";
public AD7LoadCompleteEvent()
{
}
}
internal sealed class AD7EntryPointEvent : AD7StoppingEvent, IDebugEntryPointEvent2
{
public const string IID = "E8414A3E-1642-48EC-829E-5F4040E16DA9";
public AD7EntryPointEvent()
{
}
}
internal sealed class AD7ExpressionCompleteEvent : AD7AsynchronousEvent, IDebugExpressionEvaluationCompleteEvent2
{
private AD7Engine _engine;
public const string IID = "C0E13A85-238A-4800-8315-D947C960A843";
public AD7ExpressionCompleteEvent(AD7Engine engine, IVariableInformation var, IDebugProperty2 prop = null)
{
_engine = engine;
_var = var;
_prop = prop;
}
public int GetExpression(out IDebugExpression2 expr)
{
expr = new AD7Expression(_engine, _var);
return Constants.S_OK;
}
public int GetResult(out IDebugProperty2 prop)
{
prop = _prop != null ? _prop : new AD7Property(_engine, _var);
return Constants.S_OK;
}
private IVariableInformation _var;
private IDebugProperty2 _prop;
}
// This interface tells the session debug manager (SDM) that an exception has occurred in the debuggee.
internal sealed class AD7ExceptionEvent : AD7StoppingEvent, IDebugExceptionEvent2
{
public const string IID = "51A94113-8788-4A54-AE15-08B74FF922D0";
public AD7ExceptionEvent(string name, string description, uint code, Guid? exceptionCategory, ExceptionBreakpointState state)
{
_name = name;
_code = code;
_description = description ?? name;
_category = exceptionCategory ?? EngineConstants.EngineId;
switch (state)
{
case ExceptionBreakpointState.None:
_state = enum_EXCEPTION_STATE.EXCEPTION_STOP_SECOND_CHANCE;
break;
case ExceptionBreakpointState.BreakThrown:
_state = enum_EXCEPTION_STATE.EXCEPTION_STOP_FIRST_CHANCE | enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_FIRST_CHANCE;
break;
case ExceptionBreakpointState.BreakUserHandled:
_state = enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_UNCAUGHT;
break;
default:
Debug.Fail("Unexpected state value");
_state = enum_EXCEPTION_STATE.EXCEPTION_STOP_SECOND_CHANCE;
break;
}
}
#region IDebugExceptionEvent2 Members
public int CanPassToDebuggee()
{
// Cannot pass it on
return Constants.S_FALSE;
}
public int GetException(EXCEPTION_INFO[] pExceptionInfo)
{
EXCEPTION_INFO ex = new EXCEPTION_INFO();
ex.bstrExceptionName = _name;
ex.dwCode = _code;
ex.dwState = _state;
ex.guidType = _category;
pExceptionInfo[0] = ex;
return Constants.S_OK;
}
public int GetExceptionDescription(out string pbstrDescription)
{
pbstrDescription = _description;
return Constants.S_OK;
}
public int PassToDebuggee(int fPass)
{
return Constants.S_OK;
}
private string _name;
private uint _code;
private string _description;
private Guid _category;
private enum_EXCEPTION_STATE _state;
#endregion
}
// This interface tells the session debug manager (SDM) that a step has completed
internal sealed class AD7StepCompleteEvent : AD7StoppingEvent, IDebugStepCompleteEvent2
{
public const string IID = "0f7f24c1-74d9-4ea6-a3ea-7edb2d81441d";
}
// This interface tells the session debug manager (SDM) that an asynchronous break has been successfully completed.
internal sealed class AD7AsyncBreakCompleteEvent : AD7StoppingEvent, IDebugBreakEvent2
{
public const string IID = "c7405d1d-e24b-44e0-b707-d8a5a4e1641b";
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) to output a string for debug tracing.
internal sealed class AD7OutputDebugStringEvent : AD7AsynchronousEvent, IDebugOutputStringEvent2
{
public const string IID = "569c4bb1-7b82-46fc-ae28-4536ddad753e";
private string _str;
public AD7OutputDebugStringEvent(string str)
{
_str = str;
}
#region IDebugOutputStringEvent2 Members
int IDebugOutputStringEvent2.GetString(out string pbstrString)
{
pbstrString = _str;
return Constants.S_OK;
}
#endregion
}
// This interface is sent when a pending breakpoint has been bound in the debuggee.
internal sealed class AD7BreakpointBoundEvent : AD7AsynchronousEvent, IDebugBreakpointBoundEvent2
{
public const string IID = "1dddb704-cf99-4b8a-b746-dabb01dd13a0";
private AD7PendingBreakpoint _pendingBreakpoint;
private AD7BoundBreakpoint _boundBreakpoint;
public AD7BreakpointBoundEvent(AD7PendingBreakpoint pendingBreakpoint, AD7BoundBreakpoint boundBreakpoint)
{
_pendingBreakpoint = pendingBreakpoint;
_boundBreakpoint = boundBreakpoint;
}
#region IDebugBreakpointBoundEvent2 Members
int IDebugBreakpointBoundEvent2.EnumBoundBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum)
{
IDebugBoundBreakpoint2[] boundBreakpoints = new IDebugBoundBreakpoint2[1];
boundBreakpoints[0] = _boundBreakpoint;
ppEnum = new AD7BoundBreakpointsEnum(boundBreakpoints);
return Constants.S_OK;
}
int IDebugBreakpointBoundEvent2.GetPendingBreakpoint(out IDebugPendingBreakpoint2 ppPendingBP)
{
ppPendingBP = _pendingBreakpoint;
return Constants.S_OK;
}
#endregion
}
// This Event is sent when a breakpoint is hit in the debuggee
internal sealed class AD7BreakpointEvent : AD7StoppingEvent, IDebugBreakpointEvent2
{
public const string IID = "501C1E21-C557-48B8-BA30-A1EAB0BC4A74";
private IEnumDebugBoundBreakpoints2 _boundBreakpoints;
public AD7BreakpointEvent(IEnumDebugBoundBreakpoints2 boundBreakpoints)
{
_boundBreakpoints = boundBreakpoints;
}
#region IDebugBreakpointEvent2 Members
int IDebugBreakpointEvent2.EnumBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum)
{
ppEnum = _boundBreakpoints;
return Constants.S_OK;
}
#endregion
}
internal sealed class AD7StopCompleteEvent : AD7StoppingEvent, IDebugStopCompleteEvent2
{
public const string IID = "3DCA9DCD-FB09-4AF1-A926-45F293D48B2D";
}
internal sealed class AD7ProcessInfoUpdatedEvent : AD7AsynchronousEvent, IDebugProcessInfoUpdatedEvent158
{
public const string IID = "96C242FC-F584-4C3E-8FED-384D3D13EF36";
private readonly string _name;
private readonly uint _pid;
public AD7ProcessInfoUpdatedEvent(string name, uint pid)
{
_name = name;
_pid = pid;
}
public int GetUpdatedProcessInfo(out string pbstrName, out uint pdwSystemProcessId)
{
pbstrName = _name;
pdwSystemProcessId = _pid;
return Constants.S_OK;
}
internal static void Send(AD7Engine engine, string name, uint pid)
{
AD7ProcessInfoUpdatedEvent eventObject = new AD7ProcessInfoUpdatedEvent(name, pid);
engine.Callback.Send(eventObject, IID, engine, null);
}
}
internal sealed class AD7CustomDebugEvent : AD7AsynchronousEvent, IDebugCustomEvent110
{
public const string IID = "2615D9BC-1948-4D21-81EE-7A963F20CF59";
private readonly Guid _guidVSService;
private readonly Guid _sourceId;
private readonly int _messageCode;
private readonly object _parameter1;
private readonly object _parameter2;
public AD7CustomDebugEvent(Guid guidVSService, Guid sourceId, int messageCode, object parameter1, object parameter2)
{
_guidVSService = guidVSService;
_sourceId = sourceId;
_messageCode = messageCode;
_parameter1 = parameter1;
_parameter2 = parameter2;
}
int IDebugCustomEvent110.GetCustomEventInfo(out Guid guidVSService, VsComponentMessage[] message)
{
guidVSService = _guidVSService;
message[0].SourceId = _sourceId;
message[0].MessageCode = (uint)_messageCode;
message[0].Parameter1 = _parameter1;
message[0].Parameter2 = _parameter2;
return Constants.S_OK;
}
}
}
| |
using System;
using System.Diagnostics;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Security.Certificates;
using Org.BouncyCastle.Utilities.Collections;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.X509.Extension;
namespace Org.BouncyCastle.Tests
{
/**
* Test Utils
*/
internal class TestUtilities
{
/**
* Create a random 1024 bit RSA key pair
*/
public static AsymmetricCipherKeyPair GenerateRsaKeyPair()
{
IAsymmetricCipherKeyPairGenerator kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA");
kpGen.Init(new KeyGenerationParameters(new SecureRandom(), 1024));
return kpGen.GenerateKeyPair();
}
public static X509Certificate GenerateRootCert(
AsymmetricCipherKeyPair pair)
{
X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
certGen.SetSerialNumber(BigInteger.One);
certGen.SetIssuerDN(new X509Name("CN=Test CA Certificate"));
certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
certGen.SetSubjectDN(new X509Name("CN=Test CA Certificate"));
certGen.SetPublicKey(pair.Public);
certGen.SetSignatureAlgorithm("SHA256WithRSAEncryption");
return certGen.Generate(pair.Private);
}
public static X509Certificate GenerateIntermediateCert(
AsymmetricKeyParameter intKey,
AsymmetricKeyParameter caKey,
X509Certificate caCert)
{
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.SetSerialNumber(BigInteger.One);
certGen.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(caCert));
certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
certGen.SetSubjectDN(new X509Name("CN=Test Intermediate Certificate"));
certGen.SetPublicKey(intKey);
certGen.SetSignatureAlgorithm("SHA256WithRSAEncryption");
certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert));
certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(intKey));
certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0));
certGen.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyCertSign | KeyUsage.CrlSign));
return certGen.Generate(caKey);
}
public static X509Certificate GenerateEndEntityCert(
AsymmetricKeyParameter entityKey,
AsymmetricKeyParameter caKey,
X509Certificate caCert)
{
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.SetSerialNumber(BigInteger.One);
certGen.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(caCert));
certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
certGen.SetSubjectDN(new X509Name("CN=Test End Certificate"));
certGen.SetPublicKey(entityKey);
certGen.SetSignatureAlgorithm("SHA256WithRSAEncryption");
certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert));
certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(entityKey));
certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
certGen.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment));
return certGen.Generate(caKey);
}
public static X509Crl CreateCrl(
X509Certificate caCert,
AsymmetricKeyParameter caKey,
BigInteger serialNumber)
{
X509V2CrlGenerator crlGen = new X509V2CrlGenerator();
DateTime now = DateTime.UtcNow;
// BigInteger revokedSerialNumber = BigInteger.Two;
crlGen.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(caCert));
crlGen.SetThisUpdate(now);
crlGen.SetNextUpdate(now.AddSeconds(100));
crlGen.SetSignatureAlgorithm("SHA256WithRSAEncryption");
crlGen.AddCrlEntry(serialNumber, now, CrlReason.PrivilegeWithdrawn);
crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert));
crlGen.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(BigInteger.One));
return crlGen.Generate(caKey);
}
public static X509Certificate CreateExceptionCertificate(
bool exceptionOnEncode)
{
return new ExceptionCertificate(exceptionOnEncode);
}
private class ExceptionCertificate
: X509Certificate
{
private bool _exceptionOnEncode;
public ExceptionCertificate(
bool exceptionOnEncode)
{
_exceptionOnEncode = exceptionOnEncode;
}
public override void CheckValidity()
{
throw new CertificateNotYetValidException();
}
public override void CheckValidity(
DateTime date)
{
throw new CertificateExpiredException();
}
public override int Version
{
get { return 0; }
}
public override BigInteger SerialNumber
{
get { return null; }
}
public override X509Name IssuerDN
{
get { return null; }
}
public override X509Name SubjectDN
{
get { return null; }
}
public override DateTime NotBefore
{
get { return DateTime.MaxValue; }
}
public override DateTime NotAfter
{
get { return DateTime.MinValue; }
}
public override byte[] GetTbsCertificate()
{
throw new CertificateEncodingException();
}
public override byte[] GetSignature()
{
return new byte[0];
}
public override string SigAlgName
{
get { return null; }
}
public override string SigAlgOid
{
get { return null; }
}
public override byte[] GetSigAlgParams()
{
return new byte[0];
}
public override DerBitString IssuerUniqueID
{
get { return null; }
}
public override DerBitString SubjectUniqueID
{
get { return null; }
}
public override bool[] GetKeyUsage()
{
return new bool[0];
}
public override int GetBasicConstraints()
{
return 0;
}
public override byte[] GetEncoded()
{
if (_exceptionOnEncode)
{
throw new CertificateEncodingException();
}
return new byte[0];
}
public override void Verify(
AsymmetricKeyParameter key)
{
throw new CertificateException();
}
public override string ToString()
{
return null;
}
public override AsymmetricKeyParameter GetPublicKey()
{
return null;
}
public override ISet GetCriticalExtensionOids()
{
return null;
}
public override ISet GetNonCriticalExtensionOids()
{
return null;
}
public override Asn1OctetString GetExtensionValue(
DerObjectIdentifier oid)
{
return null;
}
}
}
}
| |
using Prism.Common;
using Prism.Interactivity.DefaultPopupWindows;
using Prism.Interactivity.InteractionRequest;
using System;
using System.Windows;
using System.Windows.Interactivity;
namespace Prism.Interactivity
{
/// <summary>
/// Shows a popup window in response to an <see cref="InteractionRequest"/> being raised.
/// </summary>
public class PopupWindowAction : TriggerAction<FrameworkElement>
{
/// <summary>
/// The content of the child window to display as part of the popup.
/// </summary>
public static readonly DependencyProperty WindowContentProperty =
DependencyProperty.Register(
"WindowContent",
typeof(FrameworkElement),
typeof(PopupWindowAction),
new PropertyMetadata(null));
/// <summary>
/// Determines if the content should be shown in a modal window or not.
/// </summary>
public static readonly DependencyProperty IsModalProperty =
DependencyProperty.Register(
"IsModal",
typeof(bool),
typeof(PopupWindowAction),
new PropertyMetadata(null));
/// <summary>
/// Determines if the content should be initially shown centered over the view that raised the interaction request or not.
/// </summary>
public static readonly DependencyProperty CenterOverAssociatedObjectProperty =
DependencyProperty.Register(
"CenterOverAssociatedObject",
typeof(bool),
typeof(PopupWindowAction),
new PropertyMetadata(null));
/// <summary>
/// If set, applies this Style to the child window.
/// </summary>
public static readonly DependencyProperty WindowStyleProperty =
DependencyProperty.Register(
"WindowStyle",
typeof(Style),
typeof(PopupWindowAction),
new PropertyMetadata(null));
/// <summary>
/// Gets or sets the content of the window.
/// </summary>
public FrameworkElement WindowContent
{
get { return (FrameworkElement)GetValue(WindowContentProperty); }
set { SetValue(WindowContentProperty, value); }
}
/// <summary>
/// Gets or sets if the window will be modal or not.
/// </summary>
public bool IsModal
{
get { return (bool)GetValue(IsModalProperty); }
set { SetValue(IsModalProperty, value); }
}
/// <summary>
/// Gets or sets if the window will be initially shown centered over the view that raised the interaction request or not.
/// </summary>
public bool CenterOverAssociatedObject
{
get { return (bool)GetValue(CenterOverAssociatedObjectProperty); }
set { SetValue(CenterOverAssociatedObjectProperty, value); }
}
/// <summary>
/// Gets or sets the Style of the Window.
/// </summary>
public Style WindowStyle
{
get { return (Style)GetValue(WindowStyleProperty); }
set { SetValue(WindowStyleProperty, value); }
}
/// <summary>
/// Displays the child window and collects results for <see cref="IInteractionRequest"/>.
/// </summary>
/// <param name="parameter">The parameter to the action. If the action does not require a parameter, the parameter may be set to a null reference.</param>
protected override void Invoke(object parameter)
{
var args = parameter as InteractionRequestedEventArgs;
if (args == null)
{
return;
}
// If the WindowContent shouldn't be part of another visual tree.
if (this.WindowContent != null && this.WindowContent.Parent != null)
{
return;
}
Window wrapperWindow = this.GetWindow(args.Context);
// We invoke the callback when the interaction's window is closed.
var callback = args.Callback;
EventHandler handler = null;
handler =
(o, e) =>
{
wrapperWindow.Closed -= handler;
wrapperWindow.Content = null;
if(callback != null) callback();
};
wrapperWindow.Closed += handler;
if (this.CenterOverAssociatedObject && this.AssociatedObject != null)
{
// If we should center the popup over the parent window we subscribe to the SizeChanged event
// so we can change its position after the dimensions are set.
SizeChangedEventHandler sizeHandler = null;
sizeHandler =
(o, e) =>
{
wrapperWindow.SizeChanged -= sizeHandler;
FrameworkElement view = this.AssociatedObject;
Point position = view.PointToScreen(new Point(0, 0));
wrapperWindow.Top = position.Y + ((view.ActualHeight - wrapperWindow.ActualHeight) / 2);
wrapperWindow.Left = position.X + ((view.ActualWidth - wrapperWindow.ActualWidth) / 2);
};
wrapperWindow.SizeChanged += sizeHandler;
}
if (this.IsModal)
{
wrapperWindow.ShowDialog();
}
else
{
wrapperWindow.Show();
}
}
/// <summary>
/// Returns the window to display as part of the trigger action.
/// </summary>
/// <param name="notification">The notification to be set as a DataContext in the window.</param>
/// <returns></returns>
protected virtual Window GetWindow(INotification notification)
{
Window wrapperWindow;
if (this.WindowContent != null)
{
wrapperWindow = CreateWindow();
if (wrapperWindow == null)
throw new NullReferenceException("CreateWindow cannot return null");
// If the WindowContent does not have its own DataContext, it will inherit this one.
wrapperWindow.DataContext = notification;
wrapperWindow.Title = notification.Title;
this.PrepareContentForWindow(notification, wrapperWindow);
}
else
{
wrapperWindow = this.CreateDefaultWindow(notification);
}
// If the user provided a Style for a Window we set it as the window's style.
if (WindowStyle != null)
wrapperWindow.Style = WindowStyle;
return wrapperWindow;
}
/// <summary>
/// Checks if the WindowContent or its DataContext implements <see cref="IInteractionRequestAware"/>.
/// If so, it sets the corresponding value.
/// Also, if WindowContent does not have a RegionManager attached, it creates a new scoped RegionManager for it.
/// </summary>
/// <param name="notification">The notification to be set as a DataContext in the HostWindow.</param>
/// <param name="wrapperWindow">The HostWindow</param>
protected virtual void PrepareContentForWindow(INotification notification, Window wrapperWindow)
{
if (this.WindowContent == null)
{
return;
}
// We set the WindowContent as the content of the window.
wrapperWindow.Content = this.WindowContent;
Action<IInteractionRequestAware> setNotificationAndClose = (iira) =>
{
iira.Notification = notification;
iira.FinishInteraction = () => wrapperWindow.Close();
};
MvvmHelpers.ViewAndViewModelAction(this.WindowContent, setNotificationAndClose);
}
/// <summary>
/// Creates a Window that is used when providing custom Window Content
/// </summary>
/// <returns>The Window</returns>
protected virtual Window CreateWindow()
{
return new DefaultWindow();
}
/// <summary>
/// When no WindowContent is sent this method is used to create a default basic window to show
/// the corresponding <see cref="INotification"/> or <see cref="IConfirmation"/>.
/// </summary>
/// <param name="notification">The INotification or IConfirmation parameter to show.</param>
/// <returns></returns>
protected Window CreateDefaultWindow(INotification notification)
{
Window window = null;
if (notification is IConfirmation)
{
window = new DefaultConfirmationWindow() { Confirmation = (IConfirmation)notification };
}
else
{
window = new DefaultNotificationWindow() { Notification = notification };
}
return window;
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Generic;
using System.Security;
using SFML.Window;
using SFML.System;
namespace SFML
{
namespace Graphics
{
////////////////////////////////////////////////////////////
/// <summary>
/// Target for off-screen 2D rendering into an texture
/// </summary>
////////////////////////////////////////////////////////////
public class RenderTexture : ObjectBase, RenderTarget
{
////////////////////////////////////////////////////////////
/// <summary>
/// Create the render-texture with the given dimensions
/// </summary>
/// <param name="width">Width of the render-texture</param>
/// <param name="height">Height of the render-texture</param>
////////////////////////////////////////////////////////////
public RenderTexture(uint width, uint height) :
this(width, height, false)
{
}
////////////////////////////////////////////////////////////
/// <summary>
/// Create the render-texture with the given dimensions and
/// an optional depth-buffer attached
/// </summary>
/// <param name="width">Width of the render-texture</param>
/// <param name="height">Height of the render-texture</param>
/// <param name="depthBuffer">Do you want a depth-buffer attached?</param>
////////////////////////////////////////////////////////////
public RenderTexture(uint width, uint height, bool depthBuffer) :
base(sfRenderTexture_create(width, height, depthBuffer))
{
myDefaultView = new View(sfRenderTexture_getDefaultView(CPointer));
myTexture = new Texture(sfRenderTexture_getTexture(CPointer));
GC.SuppressFinalize(myDefaultView);
GC.SuppressFinalize(myTexture);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Activate of deactivate the render texture as the current target
/// for rendering
/// </summary>
/// <param name="active">True to activate, false to deactivate (true by default)</param>
/// <returns>True if operation was successful, false otherwise</returns>
////////////////////////////////////////////////////////////
public bool SetActive(bool active)
{
return sfRenderTexture_setActive(CPointer, active);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Size of the rendering region of the render texture
/// </summary>
////////////////////////////////////////////////////////////
public Vector2u Size
{
get { return sfRenderTexture_getSize(CPointer); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Default view of the render texture
/// </summary>
////////////////////////////////////////////////////////////
public View DefaultView
{
get { return new View(myDefaultView); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Return the current active view
/// </summary>
/// <returns>The current view</returns>
////////////////////////////////////////////////////////////
public View GetView()
{
return new View(sfRenderTexture_getView(CPointer));
}
////////////////////////////////////////////////////////////
/// <summary>
/// Change the current active view
/// </summary>
/// <param name="view">New view</param>
////////////////////////////////////////////////////////////
public void SetView(View view)
{
sfRenderTexture_setView(CPointer, view.CPointer);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Get the viewport of a view applied to this target
/// </summary>
/// <param name="view">Target view</param>
/// <returns>Viewport rectangle, expressed in pixels in the current target</returns>
////////////////////////////////////////////////////////////
public IntRect GetViewport(View view)
{
return sfRenderTexture_getViewport(CPointer, view.CPointer);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Convert a point from target coordinates to world
/// coordinates, using the current view
///
/// This function is an overload of the MapPixelToCoords
/// function that implicitely uses the current view.
/// It is equivalent to:
/// target.MapPixelToCoords(point, target.GetView());
/// </summary>
/// <param name="point">Pixel to convert</param>
/// <returns>The converted point, in "world" coordinates</returns>
////////////////////////////////////////////////////////////
public Vector2f MapPixelToCoords(Vector2i point)
{
return MapPixelToCoords(point, GetView());
}
////////////////////////////////////////////////////////////
/// <summary>
/// Convert a point from target coordinates to world coordinates
///
/// This function finds the 2D position that matches the
/// given pixel of the render-target. In other words, it does
/// the inverse of what the graphics card does, to find the
/// initial position of a rendered pixel.
///
/// Initially, both coordinate systems (world units and target pixels)
/// match perfectly. But if you define a custom view or resize your
/// render-target, this assertion is not true anymore, ie. a point
/// located at (10, 50) in your render-target may map to the point
/// (150, 75) in your 2D world -- if the view is translated by (140, 25).
///
/// For render-windows, this function is typically used to find
/// which point (or object) is located below the mouse cursor.
///
/// This version uses a custom view for calculations, see the other
/// overload of the function if you want to use the current view of the
/// render-target.
/// </summary>
/// <param name="point">Pixel to convert</param>
/// <param name="view">The view to use for converting the point</param>
/// <returns>The converted point, in "world" coordinates</returns>
////////////////////////////////////////////////////////////
public Vector2f MapPixelToCoords(Vector2i point, View view)
{
return sfRenderTexture_mapPixelToCoords(CPointer, point, view != null ? view.CPointer : IntPtr.Zero);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Convert a point from world coordinates to target
/// coordinates, using the current view
///
/// This function is an overload of the mapCoordsToPixel
/// function that implicitely uses the current view.
/// It is equivalent to:
/// target.MapCoordsToPixel(point, target.GetView());
/// </summary>
/// <param name="point">Point to convert</param>
/// <returns>The converted point, in target coordinates (pixels)</returns>
////////////////////////////////////////////////////////////
public Vector2i MapCoordsToPixel(Vector2f point)
{
return MapCoordsToPixel(point, GetView());
}
////////////////////////////////////////////////////////////
/// <summary>
/// Convert a point from world coordinates to target coordinates
///
/// This function finds the pixel of the render-target that matches
/// the given 2D point. In other words, it goes through the same process
/// as the graphics card, to compute the final position of a rendered point.
///
/// Initially, both coordinate systems (world units and target pixels)
/// match perfectly. But if you define a custom view or resize your
/// render-target, this assertion is not true anymore, ie. a point
/// located at (150, 75) in your 2D world may map to the pixel
/// (10, 50) of your render-target -- if the view is translated by (140, 25).
///
/// This version uses a custom view for calculations, see the other
/// overload of the function if you want to use the current view of the
/// render-target.
/// </summary>
/// <param name="point">Point to convert</param>
/// <param name="view">The view to use for converting the point</param>
/// <returns>The converted point, in target coordinates (pixels)</returns>
////////////////////////////////////////////////////////////
public Vector2i MapCoordsToPixel(Vector2f point, View view)
{
return sfRenderTexture_mapCoordsToPixel(CPointer, point, view != null ? view.CPointer : IntPtr.Zero);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Clear the entire render texture with black color
/// </summary>
////////////////////////////////////////////////////////////
public void Clear()
{
sfRenderTexture_clear(CPointer, Color.Black);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Clear the entire render texture with a single color
/// </summary>
/// <param name="color">Color to use to clear the texture</param>
////////////////////////////////////////////////////////////
public void Clear(Color color)
{
sfRenderTexture_clear(CPointer, color);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Update the contents of the target texture
/// </summary>
////////////////////////////////////////////////////////////
public void Display()
{
sfRenderTexture_display(CPointer);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Target texture of the render texture
/// </summary>
////////////////////////////////////////////////////////////
public Texture Texture
{
get { return myTexture; }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Control the smooth filter
/// </summary>
////////////////////////////////////////////////////////////
public bool Smooth
{
get { return sfRenderTexture_isSmooth(CPointer); }
set { sfRenderTexture_setSmooth(CPointer, value); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Draw a drawable object to the render-target, with default render states
/// </summary>
/// <param name="drawable">Object to draw</param>
////////////////////////////////////////////////////////////
public void Draw(Drawable drawable)
{
Draw(drawable, RenderStates.Default);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Draw a drawable object to the render-target
/// </summary>
/// <param name="drawable">Object to draw</param>
/// <param name="states">Render states to use for drawing</param>
////////////////////////////////////////////////////////////
public void Draw(Drawable drawable, RenderStates states)
{
drawable.Draw(this, states);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Draw primitives defined by an array of vertices, with default render states
/// </summary>
/// <param name="vertices">Pointer to the vertices</param>
/// <param name="type">Type of primitives to draw</param>
////////////////////////////////////////////////////////////
public void Draw(Vertex[] vertices, PrimitiveType type)
{
Draw(vertices, type, RenderStates.Default);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Draw primitives defined by an array of vertices
/// </summary>
/// <param name="vertices">Pointer to the vertices</param>
/// <param name="type">Type of primitives to draw</param>
/// <param name="states">Render states to use for drawing</param>
////////////////////////////////////////////////////////////
public void Draw(Vertex[] vertices, PrimitiveType type, RenderStates states)
{
Draw(vertices, 0, (uint)vertices.Length, type, states);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Draw primitives defined by a sub-array of vertices, with default render states
/// </summary>
/// <param name="vertices">Array of vertices to draw</param>
/// <param name="start">Index of the first vertex to draw in the array</param>
/// <param name="count">Number of vertices to draw</param>
/// <param name="type">Type of primitives to draw</param>
////////////////////////////////////////////////////////////
public void Draw(Vertex[] vertices, uint start, uint count, PrimitiveType type)
{
Draw(vertices, start, count, type, RenderStates.Default);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Draw primitives defined by a sub-array of vertices
/// </summary>
/// <param name="vertices">Pointer to the vertices</param>
/// <param name="start">Index of the first vertex to use in the array</param>
/// <param name="count">Number of vertices to draw</param>
/// <param name="type">Type of primitives to draw</param>
/// <param name="states">Render states to use for drawing</param>
////////////////////////////////////////////////////////////
public void Draw(Vertex[] vertices, uint start, uint count, PrimitiveType type, RenderStates states)
{
RenderStates.MarshalData marshaledStates = states.Marshal();
unsafe
{
fixed (Vertex* vertexPtr = vertices)
{
sfRenderTexture_drawPrimitives(CPointer, vertexPtr + start, count, type, ref marshaledStates);
}
}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Save the current OpenGL render states and matrices.
///
/// This function can be used when you mix SFML drawing
/// and direct OpenGL rendering. Combined with PopGLStates,
/// it ensures that:
/// \li SFML's internal states are not messed up by your OpenGL code
/// \li your OpenGL states are not modified by a call to a SFML function
///
/// More specifically, it must be used around code that
/// calls Draw functions. Example:
///
/// // OpenGL code here...
/// window.PushGLStates();
/// window.Draw(...);
/// window.Draw(...);
/// window.PopGLStates();
/// // OpenGL code here...
///
/// Note that this function is quite expensive: it saves all the
/// possible OpenGL states and matrices, even the ones you
/// don't care about. Therefore it should be used wisely.
/// It is provided for convenience, but the best results will
/// be achieved if you handle OpenGL states yourself (because
/// you know which states have really changed, and need to be
/// saved and restored). Take a look at the ResetGLStates
/// function if you do so.
/// </summary>
////////////////////////////////////////////////////////////
public void PushGLStates()
{
sfRenderTexture_pushGLStates(CPointer);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Restore the previously saved OpenGL render states and matrices.
///
/// See the description of PushGLStates to get a detailed
/// description of these functions.
/// </summary>
////////////////////////////////////////////////////////////
public void PopGLStates()
{
sfRenderTexture_popGLStates(CPointer);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Reset the internal OpenGL states so that the target is ready for drawing.
///
/// This function can be used when you mix SFML drawing
/// and direct OpenGL rendering, if you choose not to use
/// PushGLStates/PopGLStates. It makes sure that all OpenGL
/// states needed by SFML are set, so that subsequent Draw()
/// calls will work as expected.
///
/// Example:
///
/// // OpenGL code here...
/// glPushAttrib(...);
/// window.ResetGLStates();
/// window.Draw(...);
/// window.Draw(...);
/// glPopAttrib(...);
/// // OpenGL code here...
/// </summary>
////////////////////////////////////////////////////////////
public void ResetGLStates()
{
sfRenderTexture_resetGLStates(CPointer);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Provide a string describing the object
/// </summary>
/// <returns>String description of the object</returns>
////////////////////////////////////////////////////////////
public override string ToString()
{
return "[RenderTexture]" +
" Size(" + Size + ")" +
" Texture(" + Texture + ")" +
" DefaultView(" + DefaultView + ")" +
" View(" + GetView() + ")";
}
////////////////////////////////////////////////////////////
/// <summary>
/// Handle the destruction of the object
/// </summary>
/// <param name="disposing">Is the GC disposing the object, or is it an explicit call ?</param>
////////////////////////////////////////////////////////////
protected override void Destroy(bool disposing)
{
if (!disposing)
Context.Global.SetActive(true);
sfRenderTexture_destroy(CPointer);
if (disposing)
{
myDefaultView.Dispose();
myTexture.Dispose();
}
if (!disposing)
Context.Global.SetActive(false);
}
private View myDefaultView = null;
private Texture myTexture = null;
#region Imports
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfRenderTexture_create(uint Width, uint Height, bool DepthBuffer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderTexture_destroy(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderTexture_clear(IntPtr CPointer, Color ClearColor);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern Vector2u sfRenderTexture_getSize(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern bool sfRenderTexture_setActive(IntPtr CPointer, bool Active);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern bool sfRenderTexture_saveGLStates(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern bool sfRenderTexture_restoreGLStates(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern bool sfRenderTexture_display(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderTexture_setView(IntPtr CPointer, IntPtr View);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfRenderTexture_getView(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfRenderTexture_getDefaultView(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntRect sfRenderTexture_getViewport(IntPtr CPointer, IntPtr TargetView);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern Vector2i sfRenderTexture_mapCoordsToPixel(IntPtr CPointer, Vector2f point, IntPtr View);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern Vector2f sfRenderTexture_mapPixelToCoords(IntPtr CPointer, Vector2i point, IntPtr View);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfRenderTexture_getTexture(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderTexture_setSmooth(IntPtr texture, bool smooth);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern bool sfRenderTexture_isSmooth(IntPtr texture);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
unsafe static extern void sfRenderTexture_drawPrimitives(IntPtr CPointer, Vertex* vertexPtr, uint vertexCount, PrimitiveType type, ref RenderStates.MarshalData renderStates);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderTexture_pushGLStates(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderTexture_popGLStates(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderTexture_resetGLStates(IntPtr CPointer);
#endregion
}
}
}
| |
// 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.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.DiaSymReader;
using Roslyn.Test.PdbUtilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class UsingDebugInfoTests : ExpressionCompilerTestBase
{
#region Grouped import strings
[Fact]
public void SimplestCase()
{
var source = @"
using System;
class C
{
void M()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var importStrings = GetGroupedImportStrings(comp, "M");
Assert.Equal("USystem", importStrings.Single().Single());
}
[Fact]
public void NestedNamespaces()
{
var source = @"
using System;
namespace A
{
using System.IO;
using System.Text;
class C
{
void M()
{
}
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var importStrings = GetGroupedImportStrings(comp, "M");
Assert.Equal(2, importStrings.Length);
AssertEx.Equal(importStrings[0], new[] { "USystem.IO", "USystem.Text" });
AssertEx.Equal(importStrings[1], new[] { "USystem" });
}
[Fact]
public void Forward()
{
var source = @"
using System;
namespace A
{
using System.IO;
using System.Text;
class C
{
// One of these methods will forward to the other since they're adjacent.
void M1() { }
void M2() { }
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var importStrings1 = GetGroupedImportStrings(comp, "M1");
Assert.Equal(2, importStrings1.Length);
AssertEx.Equal(importStrings1[0], new[] { "USystem.IO", "USystem.Text" });
AssertEx.Equal(importStrings1[1], new[] { "USystem" });
var importStrings2 = GetGroupedImportStrings(comp, "M2");
Assert.Equal(2, importStrings2.Length);
AssertEx.Equal(importStrings2[0], importStrings1[0]);
AssertEx.Equal(importStrings2[1], importStrings1[1]);
}
[Fact]
public void ImportKinds()
{
var source = @"
extern alias A;
using S = System;
namespace B
{
using F = S.IO.File;
using System.Text;
class C
{
void M()
{
}
}
}
";
var aliasedRef = new CSharpCompilationReference(CreateCompilation("", assemblyName: "Lib"), aliases: ImmutableArray.Create("A"));
var comp = CreateCompilationWithMscorlib(source, new[] { aliasedRef });
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
ImmutableArray<string> externAliasStrings;
var importStrings = GetGroupedImportStrings(comp, "M", out externAliasStrings);
Assert.Equal(2, importStrings.Length);
AssertEx.Equal(importStrings[0], new[] { "USystem.Text", "AF TSystem.IO.File, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" });
AssertEx.Equal(importStrings[1], new[] { "XA", "AS USystem" });
Assert.Equal("ZA Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", externAliasStrings.Single());
}
[WorkItem(1084059)]
[Fact]
public void ImportKinds_StaticType()
{
var libSource = @"
namespace N
{
public static class Static
{
}
}
";
var source = @"
extern alias A;
using static System.Math;
namespace B
{
using static A::N.Static;
class C
{
void M()
{
}
}
}
";
var aliasedRef = new CSharpCompilationReference(CreateCompilation(libSource, assemblyName: "Lib"), aliases: ImmutableArray.Create("A"));
var comp = CreateCompilationWithMscorlib(source, new[] { aliasedRef });
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
ImmutableArray<string> externAliasStrings;
var importStrings = GetGroupedImportStrings(comp, "M", out externAliasStrings);
Assert.Equal(2, importStrings.Length);
AssertEx.Equal(importStrings[0], new[] { "TN.Static, Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" });
AssertEx.Equal(importStrings[1], new[] { "XA", "TSystem.Math, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" });
Assert.Equal("ZA Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", externAliasStrings.Single());
}
[Fact]
public void ForwardToModule()
{
var source = @"
extern alias A;
namespace B
{
using System;
class C
{
void M1()
{
}
}
}
namespace D
{
using System.Text; // Different using to prevent normal forwarding.
class E
{
void M2()
{
}
}
}
";
var aliasedRef = new CSharpCompilationReference(CreateCompilation("", assemblyName: "Lib"), aliases: ImmutableArray.Create("A"));
var comp = CreateCompilationWithMscorlib(source, new[] { aliasedRef });
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
ImmutableArray<string> externAliasStrings1;
var importStrings1 = GetGroupedImportStrings(comp, "M1", out externAliasStrings1);
Assert.Equal(2, importStrings1.Length);
AssertEx.Equal("USystem", importStrings1[0].Single());
AssertEx.Equal("XA", importStrings1[1].Single());
Assert.Equal("ZA Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", externAliasStrings1.Single());
ImmutableArray<string> externAliasStrings2;
var importStrings2 = GetGroupedImportStrings(comp, "M2", out externAliasStrings2);
Assert.Equal(2, importStrings2.Length);
AssertEx.Equal("USystem.Text", importStrings2[0].Single());
AssertEx.Equal(importStrings1[1].Single(), importStrings2[1].Single());
Assert.Equal(externAliasStrings1.Single(), externAliasStrings2.Single());
}
private static ImmutableArray<ImmutableArray<string>> GetGroupedImportStrings(Compilation compilation, string methodName)
{
ImmutableArray<string> externAliasStrings;
ImmutableArray<ImmutableArray<string>> result = GetGroupedImportStrings(compilation, methodName, out externAliasStrings);
Assert.Equal(0, externAliasStrings.Length);
return result;
}
private static ImmutableArray<ImmutableArray<string>> GetGroupedImportStrings(Compilation compilation, string methodName, out ImmutableArray<string> externAliasStrings)
{
Assert.NotNull(compilation);
Assert.NotNull(methodName);
using (var exebits = new MemoryStream())
{
using (var pdbbits = new MemoryStream())
{
compilation.Emit(exebits, pdbbits);
exebits.Position = 0;
using (var module = new PEModule(new PEReader(exebits, PEStreamOptions.LeaveOpen), metadataOpt: IntPtr.Zero, metadataSizeOpt: 0))
{
var metadataReader = module.MetadataReader;
MethodDefinitionHandle methodHandle = metadataReader.MethodDefinitions.Single(mh => metadataReader.GetString(metadataReader.GetMethodDefinition(mh).Name) == methodName);
int methodToken = metadataReader.GetToken(methodHandle);
// Create a SymReader, rather than a raw COM object, because
// SymReader implements ISymUnmanagedReader3 and the COM object
// might not.
pdbbits.Position = 0;
using (var reader = new SymReader(pdbbits.ToArray()))
{
return reader.GetCSharpGroupedImportStrings(methodToken, methodVersion: 1, externAliasStrings: out externAliasStrings);
}
}
}
}
}
#endregion Grouped import strings
#region Invalid PDBs
[Fact]
public void BadPdb_ForwardChain()
{
const int methodVersion = 1;
const int methodToken1 = 0x600057a; // Forwards to 2
const int methodToken2 = 0x600055d; // Forwards to 3
const int methodToken3 = 0x6000540; // Has a using
const string importString = "USystem";
ISymUnmanagedReader reader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes>
{
{ methodToken1, new MethodDebugInfoBytes.Builder().AddForward(methodToken2).Build() },
{ methodToken2, new MethodDebugInfoBytes.Builder().AddForward(methodToken3).Build() },
{ methodToken3, new MethodDebugInfoBytes.Builder(new [] { new [] { importString } }).Build() },
}.ToImmutableDictionary());
ImmutableArray<string> externAliasStrings;
var importStrings = reader.GetCSharpGroupedImportStrings(methodToken1, methodVersion, out externAliasStrings);
Assert.True(importStrings.IsDefault);
Assert.True(externAliasStrings.IsDefault);
importStrings = reader.GetCSharpGroupedImportStrings(methodToken2, methodVersion, out externAliasStrings);
Assert.Equal(importString, importStrings.Single().Single());
Assert.Equal(0, externAliasStrings.Length);
importStrings = reader.GetCSharpGroupedImportStrings(methodToken2, methodVersion, out externAliasStrings);
Assert.Equal(importString, importStrings.Single().Single());
Assert.Equal(0, externAliasStrings.Length);
}
[Fact]
public void BadPdb_Cycle()
{
const int methodVersion = 1;
const int methodToken1 = 0x600057a; // Forwards to itself
ISymUnmanagedReader reader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes>
{
{ methodToken1, new MethodDebugInfoBytes.Builder().AddForward(methodToken1).Build() },
}.ToImmutableDictionary());
ImmutableArray<string> externAliasStrings;
var importStrings = reader.GetCSharpGroupedImportStrings(methodToken1, methodVersion, out externAliasStrings);
Assert.True(importStrings.IsDefault);
Assert.True(externAliasStrings.IsDefault);
}
[WorkItem(999086)]
[Fact]
public void BadPdb_InvalidAliasSyntax()
{
var source = @"
public class C
{
public static void Main()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source);
byte[] exeBytes;
byte[] unusedPdbBytes;
ImmutableArray<MetadataReference> references;
var result = comp.EmitAndGetReferences(out exeBytes, out unusedPdbBytes, out references);
Assert.True(result);
var symReader = ExpressionCompilerTestHelpers.ConstructSymReaderWithImports(
exeBytes,
"Main",
"USystem", // Valid.
"UACultureInfo TSystem.Globalization.CultureInfo, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", // Invalid - skipped.
"ASI USystem.IO"); // Valid.
var runtime = CreateRuntimeInstance("assemblyName", references, exeBytes, symReader);
var evalContext = CreateMethodContext(runtime, "C.Main");
var compContext = evalContext.CreateCompilationContext(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)); // Used to throw.
var imports = compContext.NamespaceBinder.ImportChain.Single();
Assert.Equal("System", imports.Usings.Single().NamespaceOrType.ToTestDisplayString());
Assert.Equal("SI", imports.UsingAliases.Keys.Single());
Assert.Equal(0, imports.ExternAliases.Length);
}
[WorkItem(999086)]
[Fact]
public void BadPdb_DotInAlias()
{
var source = @"
public class C
{
public static void Main()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source);
byte[] exeBytes;
byte[] unusedPdbBytes;
ImmutableArray<MetadataReference> references;
var result = comp.EmitAndGetReferences(out exeBytes, out unusedPdbBytes, out references);
Assert.True(result);
var symReader = ExpressionCompilerTestHelpers.ConstructSymReaderWithImports(
exeBytes,
"Main",
"USystem", // Valid.
"AMy.Alias TSystem.Globalization.CultureInfo, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", // Invalid - skipped.
"ASI USystem.IO"); // Valid.
var runtime = CreateRuntimeInstance("assemblyName", references, exeBytes, symReader);
var evalContext = CreateMethodContext(runtime, "C.Main");
var compContext = evalContext.CreateCompilationContext(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)); // Used to throw.
var imports = compContext.NamespaceBinder.ImportChain.Single();
Assert.Equal("System", imports.Usings.Single().NamespaceOrType.ToTestDisplayString());
Assert.Equal("SI", imports.UsingAliases.Keys.Single());
Assert.Equal(0, imports.ExternAliases.Length);
}
[WorkItem(1007917)]
[Fact]
public void BadPdb_NestingLevel_TooMany()
{
var source = @"
public class C
{
public static void Main()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source);
byte[] exeBytes;
byte[] unusedPdbBytes;
ImmutableArray<MetadataReference> references;
var result = comp.EmitAndGetReferences(out exeBytes, out unusedPdbBytes, out references);
Assert.True(result);
ISymUnmanagedReader symReader;
using (var peReader = new PEReader(ImmutableArray.Create(exeBytes)))
{
var metadataReader = peReader.GetMetadataReader();
var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, "Main"));
var methodToken = metadataReader.GetToken(methodHandle);
symReader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes>
{
{ methodToken, new MethodDebugInfoBytes.Builder(new [] { new[] { "USystem", "USystem.IO" } }, suppressUsingInfo: true).AddUsingInfo(1, 1).Build() },
}.ToImmutableDictionary());
}
var runtime = CreateRuntimeInstance("assemblyName", references, exeBytes, symReader);
var evalContext = CreateMethodContext(runtime, "C.Main");
var compContext = evalContext.CreateCompilationContext(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression));
var imports = compContext.NamespaceBinder.ImportChain.Single();
Assert.Equal("System.IO", imports.Usings.Single().NamespaceOrType.ToTestDisplayString()); // Note: some information is preserved.
Assert.Equal(0, imports.UsingAliases.Count);
Assert.Equal(0, imports.ExternAliases.Length);
}
[WorkItem(1007917)]
[Fact]
public void BadPdb_NestingLevel_TooFew()
{
var source = @"
namespace N
{
public class C
{
public static void Main()
{
}
}
}
";
var comp = CreateCompilationWithMscorlib(source);
byte[] exeBytes;
byte[] unusedPdbBytes;
ImmutableArray<MetadataReference> references;
var result = comp.EmitAndGetReferences(out exeBytes, out unusedPdbBytes, out references);
Assert.True(result);
ISymUnmanagedReader symReader;
using (var peReader = new PEReader(ImmutableArray.Create(exeBytes)))
{
var metadataReader = peReader.GetMetadataReader();
var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, "Main"));
var methodToken = metadataReader.GetToken(methodHandle);
symReader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes>
{
{ methodToken, new MethodDebugInfoBytes.Builder(new [] { new[] { "USystem" } }, suppressUsingInfo: true).AddUsingInfo(1).Build() },
}.ToImmutableDictionary());
}
var runtime = CreateRuntimeInstance("assemblyName", references, exeBytes, symReader);
var evalContext = CreateMethodContext(runtime, "N.C.Main");
var compContext = evalContext.CreateCompilationContext(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression));
var imports = compContext.NamespaceBinder.ImportChain.Single();
Assert.Equal("System", imports.Usings.Single().NamespaceOrType.ToTestDisplayString()); // Note: some information is preserved.
Assert.Equal(0, imports.UsingAliases.Count);
Assert.Equal(0, imports.ExternAliases.Length);
}
[WorkItem(1084059)]
[Fact]
public void BadPdb_NonStaticTypeImport()
{
var source = @"
namespace N
{
public class C
{
public static void Main()
{
}
}
}
";
var comp = CreateCompilationWithMscorlib(source);
byte[] exeBytes;
byte[] unusedPdbBytes;
ImmutableArray<MetadataReference> references;
var result = comp.EmitAndGetReferences(out exeBytes, out unusedPdbBytes, out references);
Assert.True(result);
ISymUnmanagedReader symReader;
using (var peReader = new PEReader(ImmutableArray.Create(exeBytes)))
{
var metadataReader = peReader.GetMetadataReader();
var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, "Main"));
var methodToken = metadataReader.GetToken(methodHandle);
symReader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes>
{
{ methodToken, new MethodDebugInfoBytes.Builder(new [] { new[] { "TSystem.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" } }, suppressUsingInfo: true).AddUsingInfo(1).Build() },
}.ToImmutableDictionary());
}
var runtime = CreateRuntimeInstance("assemblyName", references, exeBytes, symReader);
var evalContext = CreateMethodContext(runtime, "N.C.Main");
var compContext = evalContext.CreateCompilationContext(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression));
var imports = compContext.NamespaceBinder.ImportChain.Single();
Assert.Equal(0, imports.Usings.Length); // Note: the import is dropped
Assert.Equal(0, imports.UsingAliases.Count);
Assert.Equal(0, imports.ExternAliases.Length);
}
#endregion Invalid PDBs
#region Binder chain
[Fact]
public void ImportsForSimpleUsing()
{
var source = @"
using System;
class C
{
int M()
{
return 1;
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single());
var imports = importsList.Single();
Assert.Equal(0, imports.UsingAliases.Count);
Assert.Equal(0, imports.ExternAliases.Length);
var actualNamespace = imports.Usings.Single().NamespaceOrType;
Assert.Equal(SymbolKind.Namespace, actualNamespace.Kind);
Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)actualNamespace).Extent.Kind);
Assert.Equal("System", actualNamespace.ToTestDisplayString());
}
[Fact]
public void ImportsForMultipleUsings()
{
var source = @"
using System;
using System.IO;
using System.Text;
class C
{
int M()
{
return 1;
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single());
var imports = importsList.Single();
Assert.Equal(0, imports.UsingAliases.Count);
Assert.Equal(0, imports.ExternAliases.Length);
var usings = imports.Usings.Select(u => u.NamespaceOrType).ToArray();
Assert.Equal(3, usings.Length);
var expectedNames = new[] { "System", "System.IO", "System.Text" };
for (int i = 0; i < usings.Length; i++)
{
var actualNamespace = usings[i];
Assert.Equal(SymbolKind.Namespace, actualNamespace.Kind);
Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)actualNamespace).Extent.Kind);
Assert.Equal(expectedNames[i], actualNamespace.ToTestDisplayString());
}
}
[Fact]
public void ImportsForNestedNamespaces()
{
var source = @"
using System;
namespace A
{
using System.IO;
class C
{
int M()
{
return 1;
}
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "A.C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single()).AsEnumerable().ToArray();
Assert.Equal(2, importsList.Length);
var expectedNames = new[] { "System.IO", "System" }; // Innermost-to-outermost
for (int i = 0; i < importsList.Length; i++)
{
var imports = importsList[i];
Assert.Equal(0, imports.UsingAliases.Count);
Assert.Equal(0, imports.ExternAliases.Length);
var actualNamespace = imports.Usings.Single().NamespaceOrType;
Assert.Equal(SymbolKind.Namespace, actualNamespace.Kind);
Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)actualNamespace).Extent.Kind);
Assert.Equal(expectedNames[i], actualNamespace.ToTestDisplayString());
}
}
[Fact]
public void ImportsForNamespaceAlias()
{
var source = @"
using S = System;
class C
{
int M()
{
return 1;
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single());
var imports = importsList.Single();
Assert.Equal(0, imports.Usings.Length);
Assert.Equal(0, imports.ExternAliases.Length);
var usingAliases = imports.UsingAliases;
Assert.Equal(1, usingAliases.Count);
Assert.Equal("S", usingAliases.Keys.Single());
var aliasSymbol = usingAliases.Values.Single().Alias;
Assert.Equal("S", aliasSymbol.Name);
var namespaceSymbol = aliasSymbol.Target;
Assert.Equal(SymbolKind.Namespace, namespaceSymbol.Kind);
Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)namespaceSymbol).Extent.Kind);
Assert.Equal("System", namespaceSymbol.ToTestDisplayString());
}
[WorkItem(1084059)]
[Fact]
public void ImportsForStaticType()
{
var source = @"
using static System.Math;
class C
{
int M()
{
return 1;
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single());
var imports = importsList.Single();
Assert.Equal(0, imports.UsingAliases.Count);
Assert.Equal(0, imports.ExternAliases.Length);
var actualType = imports.Usings.Single().NamespaceOrType;
Assert.Equal(SymbolKind.NamedType, actualType.Kind);
Assert.Equal("System.Math", actualType.ToTestDisplayString());
}
[Fact]
public void ImportsForTypeAlias()
{
var source = @"
using I = System.Int32;
class C
{
int M()
{
return 1;
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single());
var imports = importsList.Single();
Assert.Equal(0, imports.Usings.Length);
Assert.Equal(0, imports.ExternAliases.Length);
var usingAliases = imports.UsingAliases;
Assert.Equal(1, usingAliases.Count);
Assert.Equal("I", usingAliases.Keys.Single());
var aliasSymbol = usingAliases.Values.Single().Alias;
Assert.Equal("I", aliasSymbol.Name);
var typeSymbol = aliasSymbol.Target;
Assert.Equal(SymbolKind.NamedType, typeSymbol.Kind);
Assert.Equal(SpecialType.System_Int32, ((NamedTypeSymbol)typeSymbol).SpecialType);
}
[Fact]
public void ImportsForVerbatimIdentifiers()
{
var source = @"
using @namespace;
using @object = @namespace;
using @string = @namespace.@class<@namespace.@interface>.@struct;
namespace @namespace
{
public class @class<T>
{
public struct @struct
{
}
}
public interface @interface
{
}
}
class C
{
int M()
{
return 1;
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single());
var imports = importsList.Single();
Assert.Equal(0, imports.ExternAliases.Length);
var @using = imports.Usings.Single();
var importedNamespace = @using.NamespaceOrType;
Assert.Equal(SymbolKind.Namespace, importedNamespace.Kind);
Assert.Equal("namespace", importedNamespace.Name);
var usingAliases = imports.UsingAliases;
const string keyword1 = "object";
const string keyword2 = "string";
AssertEx.SetEqual(usingAliases.Keys, keyword1, keyword2);
var namespaceAlias = usingAliases[keyword1];
var typeAlias = usingAliases[keyword2];
Assert.Equal(keyword1, namespaceAlias.Alias.Name);
var aliasedNamespace = namespaceAlias.Alias.Target;
Assert.Equal(SymbolKind.Namespace, aliasedNamespace.Kind);
Assert.Equal("@namespace", aliasedNamespace.ToTestDisplayString());
Assert.Equal(keyword2, typeAlias.Alias.Name);
var aliasedType = typeAlias.Alias.Target;
Assert.Equal(SymbolKind.NamedType, aliasedType.Kind);
Assert.Equal("@namespace.@class<@namespace.@interface>.@struct", aliasedType.ToTestDisplayString());
}
[Fact]
public void ImportsForGenericTypeAlias()
{
var source = @"
using I = System.Collections.Generic.IEnumerable<string>;
class C
{
int M()
{
return 1;
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single());
var imports = importsList.Single();
Assert.Equal(0, imports.Usings.Length);
Assert.Equal(0, imports.ExternAliases.Length);
var usingAliases = imports.UsingAliases;
Assert.Equal(1, usingAliases.Count);
Assert.Equal("I", usingAliases.Keys.Single());
var aliasSymbol = usingAliases.Values.Single().Alias;
Assert.Equal("I", aliasSymbol.Name);
var typeSymbol = aliasSymbol.Target;
Assert.Equal(SymbolKind.NamedType, typeSymbol.Kind);
Assert.Equal("System.Collections.Generic.IEnumerable<System.String>", typeSymbol.ToTestDisplayString());
}
[Fact]
public void ImportsForExternAlias()
{
var source = @"
extern alias X;
class C
{
int M()
{
X::System.Xml.Linq.LoadOptions.None.ToString();
return 1;
}
}
";
var comp = CreateCompilationWithMscorlib(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("X")) });
comp.VerifyDiagnostics();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single());
var imports = importsList.Single();
Assert.Equal(0, imports.Usings.Length);
Assert.Equal(0, imports.UsingAliases.Count);
var externAliases = imports.ExternAliases;
Assert.Equal(1, externAliases.Length);
var aliasSymbol = externAliases.Single().Alias;
Assert.Equal("X", aliasSymbol.Name);
var targetSymbol = aliasSymbol.Target;
Assert.Equal(SymbolKind.Namespace, targetSymbol.Kind);
Assert.True(((NamespaceSymbol)targetSymbol).IsGlobalNamespace);
Assert.Equal("System.Xml.Linq", targetSymbol.ContainingAssembly.Name);
var moduleInstance = runtime.Modules.Single(m => m.ModuleMetadata.Name.StartsWith("System.Xml.Linq", StringComparison.OrdinalIgnoreCase));
AssertEx.SetEqual(moduleInstance.MetadataReference.Properties.Aliases, "X");
}
[Fact]
public void ImportsForUsingsConsumingExternAlias()
{
var source = @"
extern alias X;
using SXL = X::System.Xml.Linq;
using LO = X::System.Xml.Linq.LoadOptions;
using X::System.Xml;
class C
{
int M()
{
X::System.Xml.Linq.LoadOptions.None.ToString();
return 1;
}
}
";
var comp = CreateCompilationWithMscorlib(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("X")) });
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single());
var imports = importsList.Single();
Assert.Equal(1, imports.ExternAliases.Length);
var @using = imports.Usings.Single();
var importedNamespace = @using.NamespaceOrType;
Assert.Equal(SymbolKind.Namespace, importedNamespace.Kind);
Assert.Equal("System.Xml", importedNamespace.ToTestDisplayString());
var usingAliases = imports.UsingAliases;
Assert.Equal(2, usingAliases.Count);
AssertEx.SetEqual(usingAliases.Keys, "SXL", "LO");
var typeAlias = usingAliases["SXL"].Alias;
Assert.Equal("SXL", typeAlias.Name);
Assert.Equal("System.Xml.Linq", typeAlias.Target.ToTestDisplayString());
var namespaceAlias = usingAliases["LO"].Alias;
Assert.Equal("LO", namespaceAlias.Name);
Assert.Equal("System.Xml.Linq.LoadOptions", namespaceAlias.Target.ToTestDisplayString());
}
[Fact]
public void ImportsForUsingsConsumingExternAliasAndGlobal()
{
var source = @"
extern alias X;
using A = X::System.Xml.Linq;
using B = global::System.Xml.Linq;
class C
{
int M()
{
A.LoadOptions.None.ToString();
B.LoadOptions.None.ToString();
return 1;
}
}
";
var comp = CreateCompilationWithMscorlib(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("global", "X")) });
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single());
var imports = importsList.Single();
Assert.Equal(0, imports.Usings.Length);
Assert.Equal(1, imports.ExternAliases.Length);
var usingAliases = imports.UsingAliases;
Assert.Equal(2, usingAliases.Count);
AssertEx.SetEqual(usingAliases.Keys, "A", "B");
var aliasA = usingAliases["A"].Alias;
Assert.Equal("A", aliasA.Name);
Assert.Equal("System.Xml.Linq", aliasA.Target.ToTestDisplayString());
var aliasB = usingAliases["B"].Alias;
Assert.Equal("B", aliasB.Name);
Assert.Equal(aliasA.Target, aliasB.Target);
}
private static ImportChain GetImports(RuntimeInstance runtime, string methodName, Syntax.ExpressionSyntax syntax)
{
var evalContext = CreateMethodContext(
runtime,
methodName: methodName);
var compContext = evalContext.CreateCompilationContext(syntax);
return compContext.NamespaceBinder.ImportChain;
}
#endregion Binder chain
[Fact]
public void NoSymbols()
{
var source =
@"using N;
class A
{
static void M() { }
}
namespace N
{
class B
{
static void M() { }
}
}";
ResultProperties resultProperties;
string error;
// With symbols, type reference without namespace qualifier.
var testData = Evaluate(
source,
OutputKind.DynamicallyLinkedLibrary,
methodName: "A.M",
expr: "typeof(B)",
resultProperties: out resultProperties,
error: out error,
includeSymbols: true);
Assert.Null(error);
// Without symbols, type reference without namespace qualifier.
testData = Evaluate(
source,
OutputKind.DynamicallyLinkedLibrary,
methodName: "A.M",
expr: "typeof(B)",
resultProperties: out resultProperties,
error: out error,
includeSymbols: false);
Assert.Equal(error, "error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)");
// With symbols, type reference inside namespace.
testData = Evaluate(
source,
OutputKind.DynamicallyLinkedLibrary,
methodName: "N.B.M",
expr: "typeof(B)",
resultProperties: out resultProperties,
error: out error,
includeSymbols: true);
Assert.Null(error);
// Without symbols, type reference inside namespace.
testData = Evaluate(
source,
OutputKind.DynamicallyLinkedLibrary,
methodName: "N.B.M",
expr: "typeof(B)",
resultProperties: out resultProperties,
error: out error,
includeSymbols: false);
Assert.Null(error);
}
}
internal static class ImportChainExtensions
{
internal static Imports Single(this ImportChain importChain)
{
return importChain.AsEnumerable().Single();
}
internal static IEnumerable<Imports> AsEnumerable(this ImportChain importChain)
{
for (var chain = importChain; chain != null; chain = chain.ParentOpt)
{
yield return chain.Imports;
}
}
}
}
| |
using System;
namespace Glimpse.Core.Tab.Assist
{
public class TabLayoutCell : ITabBuild
{
public TabLayoutCell(int cell)
{
if (cell < 0)
{
throw new ArgumentException("Cell must not be a negative value.", "cell");
}
Data = cell;
}
public TabLayoutCell(string format)
{
if (string.IsNullOrEmpty(format))
{
throw new ArgumentException("Format must not be null or empty.", "format");
}
Data = format;
}
public object Data { get; private set; }
public object Layout { get; private set; }
public bool? Key { get; private set; }
public bool? IsCode { get; private set; }
public string CodeType { get; private set; }
public string Align { get; private set; }
public string Width { get; private set; }
public string PaddingLeft { get; private set; }
public string PaddingRight { get; private set; }
public int? Span { get; private set; }
public string ClassName { get; private set; }
public bool? ForceFull { get; private set; }
public int? Limit { get; private set; }
public string Pre { get; private set; }
public string Post { get; private set; }
public bool MinDisplay { get; private set; }
public string Title { get; private set; }
public TabLayoutCell Format(string format)
{
if (string.IsNullOrEmpty(format))
{
throw new ArgumentException("Format must not be null or empty.", "format");
}
Data = format;
return this;
}
public TabLayoutCell SetLayout(TabLayout layout)
{
this.Layout = layout.Build();
return this;
}
public TabLayoutCell SetLayout(Action<TabLayout> layout)
{
var tabLayout = Assist.TabLayout.Create(layout);
this.Layout = tabLayout.Rows;
return this;
}
public TabLayoutCell AsKey()
{
this.Key = true;
return this;
}
public TabLayoutCell AsCode(CodeType codeType)
{
IsCode = true;
CodeType = CodeTypeConverter.Convert(codeType);
return this;
}
public TabLayoutCell AlignRight()
{
Align = "Right";
return this;
}
public TabLayoutCell WidthInPixels(int pixels)
{
if (pixels < 0)
{
throw new ArgumentException("Pixels must not be a negative value.", "pixels");
}
Width = pixels + "px";
return this;
}
public TabLayoutCell WidthInPercent(int percent)
{
if (percent < 0)
{
throw new ArgumentException("Percent must not be a negative value.", "percent");
}
Width = percent + "%";
return this;
}
public TabLayoutCell PaddingLeftInPixels(int pixels)
{
if (pixels < 0)
{
throw new ArgumentException("Pixels must not be a negative value.", "pixels");
}
PaddingLeft = pixels + "px";
return this;
}
public TabLayoutCell PaddingLeftInPercent(int percent)
{
if (percent < 0)
{
throw new ArgumentException("Percent must not be a negative value.", "percent");
}
PaddingLeft = percent + "%";
return this;
}
public TabLayoutCell PaddingRightInPixels(int pixels)
{
if (pixels < 0)
{
throw new ArgumentException("Pixels must not be a negative value.", "pixels");
}
PaddingRight = pixels + "px";
return this;
}
public TabLayoutCell PaddingRightInPercent(int percent)
{
if (percent < 0)
{
throw new ArgumentException("Percent must not be a negative value.", "percent");
}
PaddingRight = percent + "%";
return this;
}
public TabLayoutCell SpanColumns(int rows)
{
if (rows < 1)
{
throw new ArgumentException("Rows must not be less then 0.", "rows");
}
Span = rows;
return this;
}
public TabLayoutCell Class(string className)
{
if (string.IsNullOrEmpty(className))
{
throw new ArgumentException("Class name must not be null or empty.", "className");
}
ClassName = className;
return this;
}
public TabLayoutCell DisablePreview()
{
ForceFull = true;
return this;
}
public TabLayoutCell LimitTo(int rows)
{
if (rows < 1)
{
throw new ArgumentException("Rows must not be less then 0.", "rows");
}
Limit = rows;
return this;
}
public TabLayoutCell Prefix(string prefix)
{
if (string.IsNullOrEmpty(prefix))
{
throw new ArgumentException("Prefix must not be null or empty.", "prefix");
}
Pre = prefix;
return this;
}
public TabLayoutCell Suffix(string suffix)
{
if (string.IsNullOrEmpty(suffix))
{
throw new ArgumentException("Suffix must not be null or empty.", "suffix");
}
Post = suffix;
return this;
}
public TabLayoutCell WithTitle(string title)
{
if (string.IsNullOrEmpty(title))
{
throw new ArgumentException("Title must not be null or empty.", "title");
}
Title = title;
return this;
}
public TabLayoutCell AsMinimalDisplay()
{
MinDisplay = true;
return this;
}
public object Build()
{
return this;
}
}
}
| |
/*
* Copyright (c) .NET Foundation and Contributors
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
* https://github.com/piranhacms/piranha.core
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Piranha.Extend;
using Piranha.Extend.Fields;
using Piranha.Models;
using Piranha.Manager.Models;
using Piranha.Manager.Models.Content;
using Piranha.Services;
namespace Piranha.Manager.Services
{
public class ContentTypeService
{
private readonly IApi _api;
private readonly IContentFactory _factory;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="api">The current api</param>
/// <param name="factory">The content factory</param>
public ContentTypeService(IApi api, IContentFactory factory)
{
_api = api;
_factory = factory;
}
/// <summary>
/// Gets the currently available block types for the
/// specified page type.
/// </summary>
/// <param name="pageType">The page type id</param>
/// <param name="parentType">The optional parent group type</param>
/// <returns>The block list model</returns>
public BlockListModel GetPageBlockTypes(string pageType, string parentType = null)
{
var type = App.PageTypes.GetById(pageType);
var model = GetBlockTypes(parentType);
if (type != null && type.BlockItemTypes.Count > 0)
{
// First remove all block types that are not allowed
foreach (var category in model.Categories)
{
category.Items = category.Items.Where(i => type.BlockItemTypes.Contains(i.Type)).ToList();
}
// Secondly remove all empty categories
model.Categories = model.Categories.Where(c => c.Items.Count > 0).ToList();
}
return model;
}
/// <summary>
/// Gets the currently available block types for the
/// specified post type.
/// </summary>
/// <param name="postType">The post type id</param>
/// <param name="parentType">The optional parent group type</param>
/// <returns>The block list model</returns>
public BlockListModel GetPostBlockTypes(string postType, string parentType = null)
{
var type = App.PostTypes.GetById(postType);
var model = GetBlockTypes(parentType);
if (type != null && type.BlockItemTypes.Count > 0)
{
// First remove all block types that are not allowed
foreach (var category in model.Categories)
{
category.Items = category.Items.Where(i => type.BlockItemTypes.Contains(i.Type)).ToList();
}
// Secondly remove all empty categories
model.Categories = model.Categories.Where(c => c.Items.Count > 0).ToList();
}
return model;
}
/// <summary>
/// Gets the currently available block types.
/// </summary>
/// <param name="parentType">The optional parent group type</param>
/// <returns>The block list model</returns>
public BlockListModel GetBlockTypes(string parentType = null)
{
var model = new BlockListModel();
var parent = App.Blocks.GetByType(parentType);
var exludeGroups = parent != null && typeof(Piranha.Extend.BlockGroup).IsAssignableFrom(parent.Type);
foreach (var category in App.Blocks.GetCategories().OrderBy(c => c))
{
var listCategory = new BlockListModel.ListCategory
{
Name = category
};
var items = App.Blocks.GetByCategory(category).OrderBy(i => i.Name).ToList();
// If we have a parent, filter on allowed types
if (parent != null)
{
if (parent.ItemTypes.Count > 0)
{
// Only allow specified types
items = items.Where(i => parent.ItemTypes.Contains(i.Type)).ToList();
}
else
{
// Remove unlisted types
items = items.Where(i => !i.IsUnlisted).ToList();
}
if (exludeGroups)
{
items = items.Where(i => !typeof(Piranha.Extend.BlockGroup).IsAssignableFrom(i.Type)).ToList();
}
}
// Else remove unlisted types
else
{
items = items.Where(i => !i.IsUnlisted).ToList();
}
foreach (var block in items) {
listCategory.Items.Add(new BlockListModel.BlockItem
{
Name = block.Name,
Icon = block.Icon,
Type = block.TypeName
});
}
model.Categories.Add(listCategory);
}
// Remove empty categories
var empty = model.Categories.Where(c => c.Items.Count() == 0).ToList();
foreach (var remove in empty)
{
model.Categories.Remove(remove);
}
// Calculate type count
model.TypeCount = model.Categories.Sum(c => c.Items.Count());
return model;
}
/// <summary>
/// Creates a new content region.
/// </summary>
/// <param name="type">The type id</param>
/// <param name="region">The region id</param>
/// <returns>The new region item</returns>
public Task<RegionItemModel> CreateContentRegionAsync(string type, string region)
{
var pageType = App.ContentTypes.GetById(type);
if (pageType != null)
{
return CreateRegionAsync(pageType, region);
}
return null;
}
/// <summary>
/// Creates a new page region.
/// </summary>
/// <param name="type">The type id</param>
/// <param name="region">The region id</param>
/// <returns>The new region item</returns>
public Task<RegionItemModel> CreatePageRegionAsync(string type, string region)
{
var pageType = App.PageTypes.GetById(type);
if (pageType != null)
{
return CreateRegionAsync(pageType, region);
}
return null;
}
/// <summary>
/// Creates a new post region.
/// </summary>
/// <param name="type">The type id</param>
/// <param name="region">The region id</param>
/// <returns>The new region item</returns>
public Task<RegionItemModel> CreatePostRegionAsync(string type, string region)
{
var postType = App.PostTypes.GetById(type);
if (postType != null)
{
return CreateRegionAsync(postType, region);
}
return null;
}
/// <summary>
/// Creates a new site region.
/// </summary>
/// <param name="type">The type id</param>
/// <param name="region">The region id</param>
/// <returns>The new region item</returns>
public Task<RegionItemModel> CreateSiteRegionAsync(string type, string region)
{
var siteType = App.SiteTypes.GetById(type);
if (siteType != null)
{
return CreateRegionAsync(siteType, region);
}
return null;
}
/// <summary>
/// Creates a new region for the given content type.
/// </summary>
/// <param name="type">The content type</param>
/// <param name="region">The region id</param>
/// <returns>The new region item</returns>
private async Task<RegionItemModel> CreateRegionAsync(ContentTypeBase type, string region)
{
var regionType = type.Regions.First(r => r.Id == region);
var regionModel = await _factory.CreateDynamicRegionAsync(type, region, true);
var regionItem = new RegionItemModel
{
Title = regionType.ListTitlePlaceholder ?? "...",
IsNew = true
};
foreach (var fieldType in regionType.Fields)
{
var appFieldType = App.Fields.GetByType(fieldType.Type);
var field = new FieldModel
{
Meta = new FieldMeta
{
Id = fieldType.Id,
Name = fieldType.Title,
Component = appFieldType.Component,
Placeholder = fieldType.Placeholder,
IsHalfWidth = fieldType.Options.HasFlag(FieldOption.HalfWidth),
Description = fieldType.Description
}
};
PopulateFieldOptions(appFieldType, field);
if (regionType.Fields.Count > 1)
{
field.Model = (IField)((IDictionary<string, object>)regionModel)[fieldType.Id];
field.Meta.NotifyChange = regionType.ListTitleField == fieldType.Id;
}
else
{
field.Model = (IField)regionModel;
field.Meta.NotifyChange = true;
}
regionItem.Fields.Add(field);
}
return regionItem;
}
/// <summary>
/// Creates a new block of the specified type.
/// </summary>
/// <param name="type">The block type</param>
/// <returns>The new block</returns>
public async Task<AsyncResult<BlockModel>> CreateBlockAsync(string type)
{
var blockType = App.Blocks.GetByType(type);
if (blockType != null)
{
var block = (Block)(await _factory.CreateBlockAsync(type, true));
if (block is BlockGroup)
{
var item = new BlockGroupModel
{
Type = block.Type,
Meta = new BlockMeta
{
Name = blockType.Name,
Title = block.GetTitle(),
Icon = blockType.Icon,
Component = blockType.Component,
Width = blockType.Width.ToString().ToLower(),
IsGroup = true
}
};
item.Fields = ContentUtils.GetBlockFields(block);
return new AsyncResult<BlockModel>
{
Body = item
};
}
else
{
if (!blockType.IsGeneric)
{
// Regular block model
return new AsyncResult<BlockModel>
{
Body = new BlockItemModel
{
Model = block,
Meta = new BlockMeta
{
Name = blockType.Name,
Title = block.GetTitle(),
Icon = blockType.Icon,
Component = blockType.Component,
Width = blockType.Width.ToString().ToLower()
}
}
};
}
else
{
var blockModel = new BlockGenericModel
{
Model = ContentUtils.GetBlockFields(block),
Type = block.Type,
Meta = new BlockMeta
{
Name = blockType.Name,
Title = block.GetTitle(),
Icon = blockType.Icon,
Component = blockType.Component,
Width = blockType.Width.ToString().ToLower()
}
};
if (blockModel.Model.Count == 1)
{
blockModel.Model[0].Meta.NotifyChange = true;
}
else
{
foreach (var blockField in blockModel.Model)
{
blockField.Meta.NotifyChange =
blockField.Meta.Id == blockType.ListTitleField;
}
}
// Generic block model
return new AsyncResult<BlockModel>
{
Body = blockModel
};
}
}
}
return null;
}
/// <summary>
/// Adds options to field's meta if required
/// </summary>
/// <param name="fieldType">Type of field</param>
/// <param name="fieldModel">Field model</param>
private void PopulateFieldOptions(Runtime.AppField fieldType, FieldModel fieldModel)
{
// Check if this is a select field
if (typeof(SelectFieldBase).IsAssignableFrom(fieldType.Type))
{
foreach (var selectItem in ((SelectFieldBase)Activator.CreateInstance(fieldType.Type)).Items)
{
fieldModel.Meta.Options.Add(Convert.ToInt32(selectItem.Value), selectItem.Title);
}
}
}
}
}
| |
namespace Microsoft.Azure.Management.StorSimple8000Series
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Operations operations.
/// </summary>
internal partial class Operations : IServiceOperations<StorSimple8000SeriesManagementClient>, IOperations
{
/// <summary>
/// Initializes a new instance of the Operations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal Operations(StorSimple8000SeriesManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the StorSimple8000SeriesManagementClient
/// </summary>
public StorSimple8000SeriesManagementClient Client { get; private set; }
/// <summary>
/// Lists all of the available REST API operations of the Microsoft.Storsimple
/// provider
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<AvailableProviderOperation>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.StorSimple/operations").ToString();
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Client.ApiVersion));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<AvailableProviderOperation>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<AvailableProviderOperation>>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists all of the available REST API operations of the Microsoft.Storsimple
/// provider
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<AvailableProviderOperation>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<AvailableProviderOperation>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<AvailableProviderOperation>>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Xml.Linq;
using System.Threading.Tasks;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using System.Numerics;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Parameters;
namespace Risersoft.API.GSTN
{
public class EncryptionUtils
{
public static X509Certificate2 getPublicKey()
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
X509Certificate2 cert2 = new X509Certificate2(System.IO.Path.Combine(GSTNConstants.base_path,"Resources\\GSTN_public.cer"));
return cert2;
}
public static string GenerateHMAC(string message, string secret)
{
secret = secret ?? "";
byte[] keyByte = Encoding.UTF8.GetBytes(secret);
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
return GenerateHMAC(messageBytes, keyByte);
}
public static string GenerateHMAC(byte[] data, byte[] EK)
{
using (var HMACSHA256 = new HMACSHA256(EK))
{
byte[] hashmessage = HMACSHA256.ComputeHash(data);
return Convert.ToBase64String(hashmessage);
}
}
public static string AesEncrypt(byte[] dataToEncrypt, byte[] keyBytes)
{
AesManaged tdes = new AesManaged();
tdes.KeySize = 256;
tdes.BlockSize = 128;
tdes.Key = keyBytes;
// Encoding.ASCII.GetBytes(key);
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform crypt = tdes.CreateEncryptor();
byte[] cipher = crypt.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length);
tdes.Clear();
return Convert.ToBase64String(cipher, 0, cipher.Length);
}
public static byte[] AesDecrypt(string encryptedText, byte[] keys)
{
byte[] dataToDecrypt = Convert.FromBase64String(encryptedText);
return AesDecrypt(dataToDecrypt, keys);
}
public static byte[] AesDecrypt(byte[] dataToDecrypt, byte[] keyBytes)
{
AesManaged tdes = new AesManaged();
tdes.KeySize = 256;
tdes.BlockSize = 128;
tdes.Key = keyBytes;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform decrypt__1 = tdes.CreateDecryptor();
byte[] deCipher = decrypt__1.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length);
tdes.Clear();
return deCipher;
}
public static string RSAEncrypt(string input)
{
byte[] bytesToBeEncrypted = Encoding.ASCII.GetBytes(input);
return RsaEncrypt(bytesToBeEncrypted);
}
private static readonly byte[] Salt = new byte[] {
10,
20,
30,
40,
50,
60,
70,
80
};
public static byte[] CreateAesKey()
{
System.Security.Cryptography.AesCryptoServiceProvider crypto = new System.Security.Cryptography.AesCryptoServiceProvider();
crypto.KeySize = 256;
crypto.GenerateKey();
byte[] key = crypto.Key;
return key;
}
public static string RsaEncrypt(byte[] bytesToBeEncrypted)
{
X509Certificate2 certificate = getPublicKey();
RSACryptoServiceProvider RSA = (RSACryptoServiceProvider)certificate.PublicKey.Key;
byte[] bytesEncrypted = RSA.Encrypt(bytesToBeEncrypted, false);
string result = Convert.ToBase64String(bytesEncrypted);
return result;
}
public static byte[] sha256_hash(string value)
{
using (SHA256 hash = SHA256Managed.Create())
{
Byte[] result = hash.ComputeHash(Encoding.UTF8.GetBytes(value));
return result;
}
}
public static byte[] convertStringToByteArray(string str)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}
public static string RsaEncryptBC(byte[] bytesToEncrypt)
{
var encryptEngine = new Pkcs1Encoding(new RsaEngine());
string certificateLocation = "Resources\\GSTN_G2B_SANDBOX_UAT_public.pem";
string publicKey = File.ReadAllText(certificateLocation).Replace("RSA PUBLIC","PUBLIC");
using (var txtreader = new StringReader(publicKey))
{
var keyParameter = (AsymmetricKeyParameter)new PemReader(txtreader).ReadObject();
encryptEngine.Init(true, keyParameter);
}
var encrypted = Convert.ToBase64String(encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length));
return encrypted;
}
public static byte[] CreateAesKeyBC()
{
SecureRandom random = new SecureRandom();
byte[] keyBytes = new byte[32]; //32 Bytes = 256 Bits
random.NextBytes(keyBytes);
var key = ParameterUtilities.CreateKeyParameter("AES", keyBytes);
return key.GetKey();
}
public byte[] Hash(string text, string key)
{
var hmac = new HMac(new Sha256Digest());
hmac.Init(new KeyParameter(Encoding.UTF8.GetBytes(key)));
byte[] result = new byte[hmac.GetMacSize()];
byte[] bytes = Encoding.UTF8.GetBytes(text);
hmac.BlockUpdate(bytes, 0, bytes.Length);
hmac.DoFinal(result, 0);
return result;
}
public static string GenerateHMACBC(byte[] data, byte[] EK)
{
var hmac = new HMac(new Sha256Digest());
hmac.Init(new KeyParameter(EK));
byte[] hashMessage = new byte[hmac.GetMacSize()];
hmac.BlockUpdate(data, 0, data.Length);
hmac.DoFinal(hashMessage, 0);
return Convert.ToBase64String(hashMessage);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Xml;
using System.Security;
namespace System.Runtime.Serialization
{
#if NET_NATIVE
public abstract class PrimitiveDataContract : DataContract
#else
internal abstract class PrimitiveDataContract : DataContract
#endif
{
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds instance of CriticalHelper which keeps state that is cached statically for serialization.
/// Static fields are marked SecurityCritical or readonly to prevent
/// data from being modified or leaked to other components in appdomain.
/// </SecurityNote>
private PrimitiveDataContractCriticalHelper _helper;
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
[SecuritySafeCritical]
protected PrimitiveDataContract(Type type, XmlDictionaryString name, XmlDictionaryString ns) : base(new PrimitiveDataContractCriticalHelper(type, name, ns))
{
_helper = base.Helper as PrimitiveDataContractCriticalHelper;
}
static internal PrimitiveDataContract GetPrimitiveDataContract(Type type)
{
return DataContract.GetBuiltInDataContract(type) as PrimitiveDataContract;
}
static internal PrimitiveDataContract GetPrimitiveDataContract(string name, string ns)
{
return DataContract.GetBuiltInDataContract(name, ns) as PrimitiveDataContract;
}
internal abstract string WriteMethodName { get; }
internal abstract string ReadMethodName { get; }
public override XmlDictionaryString TopLevelElementNamespace
{
/// <SecurityNote>
/// Critical - for consistency with base class
/// Safe - for consistency with base class
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return DictionaryGlobals.SerializationNamespace; }
/// <SecurityNote>
/// Critical - for consistency with base class
/// </SecurityNote>
[SecurityCritical]
set
{ }
}
internal override bool CanContainReferences
{
get { return false; }
}
internal override bool IsPrimitive
{
get { return true; }
}
public override bool IsBuiltInDataContract
{
get
{
return true;
}
}
internal MethodInfo XmlFormatWriterMethod
{
/// <SecurityNote>
/// Critical - fetches the critical XmlFormatWriterMethod property
/// Safe - XmlFormatWriterMethod only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_helper.XmlFormatWriterMethod == null)
{
if (UnderlyingType.GetTypeInfo().IsValueType)
_helper.XmlFormatWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { UnderlyingType, typeof(XmlDictionaryString), typeof(XmlDictionaryString) });
else
_helper.XmlFormatWriterMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), UnderlyingType, typeof(XmlDictionaryString), typeof(XmlDictionaryString) });
}
return _helper.XmlFormatWriterMethod;
}
}
internal MethodInfo XmlFormatContentWriterMethod
{
/// <SecurityNote>
/// Critical - fetches the critical XmlFormatContentWriterMethod property
/// Safe - XmlFormatContentWriterMethod only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_helper.XmlFormatContentWriterMethod == null)
{
if (UnderlyingType.GetTypeInfo().IsValueType)
_helper.XmlFormatContentWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { UnderlyingType });
else
_helper.XmlFormatContentWriterMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), UnderlyingType });
}
return _helper.XmlFormatContentWriterMethod;
}
}
internal MethodInfo XmlFormatReaderMethod
{
/// <SecurityNote>
/// Critical - fetches the critical XmlFormatReaderMethod property
/// Safe - XmlFormatReaderMethod only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_helper.XmlFormatReaderMethod == null)
{
_helper.XmlFormatReaderMethod = typeof(XmlReaderDelegator).GetMethod(ReadMethodName, Globals.ScanAllMembers);
}
return _helper.XmlFormatReaderMethod;
}
}
public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
xmlWriter.WriteAnyType(obj);
}
protected object HandleReadValue(object obj, XmlObjectSerializerReadContext context)
{
context.AddNewObject(obj);
return obj;
}
protected bool TryReadNullAtTopLevel(XmlReaderDelegator reader)
{
Attributes attributes = new Attributes();
attributes.Read(reader);
if (attributes.Ref != Globals.NewObjectId)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotDeserializeRefAtTopLevel, attributes.Ref)));
if (attributes.XsiNil)
{
reader.Skip();
return true;
}
return false;
}
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds all state used for (de)serializing primitives.
/// since the data is cached statically, we lock down access to it.
/// </SecurityNote>
private class PrimitiveDataContractCriticalHelper : DataContract.DataContractCriticalHelper
{
private MethodInfo _xmlFormatWriterMethod;
private MethodInfo _xmlFormatContentWriterMethod;
private MethodInfo _xmlFormatReaderMethod;
internal PrimitiveDataContractCriticalHelper(Type type, XmlDictionaryString name, XmlDictionaryString ns) : base(type)
{
SetDataContractName(name, ns);
}
internal MethodInfo XmlFormatWriterMethod
{
get { return _xmlFormatWriterMethod; }
set { _xmlFormatWriterMethod = value; }
}
internal MethodInfo XmlFormatContentWriterMethod
{
get { return _xmlFormatContentWriterMethod; }
set { _xmlFormatContentWriterMethod = value; }
}
internal MethodInfo XmlFormatReaderMethod
{
get { return _xmlFormatReaderMethod; }
set { _xmlFormatReaderMethod = value; }
}
}
}
#if NET_NATIVE
public class CharDataContract : PrimitiveDataContract
#else
internal class CharDataContract : PrimitiveDataContract
#endif
{
public CharDataContract() : this(DictionaryGlobals.CharLocalName, DictionaryGlobals.SerializationNamespace)
{
}
internal CharDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(char), name, ns)
{
}
internal override string WriteMethodName { get { return "WriteChar"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsChar"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteChar((char)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsChar()
: HandleReadValue(reader.ReadElementContentAsChar(), context);
}
}
#if NET_NATIVE
public class BooleanDataContract : PrimitiveDataContract
#else
internal class BooleanDataContract : PrimitiveDataContract
#endif
{
public BooleanDataContract() : base(typeof(bool), DictionaryGlobals.BooleanLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteBoolean"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsBoolean"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteBoolean((bool)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsBoolean()
: HandleReadValue(reader.ReadElementContentAsBoolean(), context);
}
}
#if NET_NATIVE
public class SignedByteDataContract : PrimitiveDataContract
#else
internal class SignedByteDataContract : PrimitiveDataContract
#endif
{
public SignedByteDataContract() : base(typeof(sbyte), DictionaryGlobals.SignedByteLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteSignedByte"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsSignedByte"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteSignedByte((sbyte)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsSignedByte()
: HandleReadValue(reader.ReadElementContentAsSignedByte(), context);
}
}
#if NET_NATIVE
public class UnsignedByteDataContract : PrimitiveDataContract
#else
internal class UnsignedByteDataContract : PrimitiveDataContract
#endif
{
public UnsignedByteDataContract() : base(typeof(byte), DictionaryGlobals.UnsignedByteLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteUnsignedByte"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedByte"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteUnsignedByte((byte)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsUnsignedByte()
: HandleReadValue(reader.ReadElementContentAsUnsignedByte(), context);
}
}
#if NET_NATIVE
public class ShortDataContract : PrimitiveDataContract
#else
internal class ShortDataContract : PrimitiveDataContract
#endif
{
public ShortDataContract() : base(typeof(short), DictionaryGlobals.ShortLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteShort"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsShort"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteShort((short)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsShort()
: HandleReadValue(reader.ReadElementContentAsShort(), context);
}
}
#if NET_NATIVE
public class UnsignedShortDataContract : PrimitiveDataContract
#else
internal class UnsignedShortDataContract : PrimitiveDataContract
#endif
{
public UnsignedShortDataContract() : base(typeof(ushort), DictionaryGlobals.UnsignedShortLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteUnsignedShort"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedShort"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteUnsignedShort((ushort)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsUnsignedShort()
: HandleReadValue(reader.ReadElementContentAsUnsignedShort(), context);
}
}
#if NET_NATIVE
public class IntDataContract : PrimitiveDataContract
#else
internal class IntDataContract : PrimitiveDataContract
#endif
{
public IntDataContract() : base(typeof(int), DictionaryGlobals.IntLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteInt"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsInt"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteInt((int)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsInt()
: HandleReadValue(reader.ReadElementContentAsInt(), context);
}
}
#if NET_NATIVE
public class UnsignedIntDataContract : PrimitiveDataContract
#else
internal class UnsignedIntDataContract : PrimitiveDataContract
#endif
{
public UnsignedIntDataContract() : base(typeof(uint), DictionaryGlobals.UnsignedIntLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteUnsignedInt"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedInt"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteUnsignedInt((uint)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsUnsignedInt()
: HandleReadValue(reader.ReadElementContentAsUnsignedInt(), context);
}
}
#if NET_NATIVE
public class LongDataContract : PrimitiveDataContract
#else
internal class LongDataContract : PrimitiveDataContract
#endif
{
public LongDataContract() : this(DictionaryGlobals.LongLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal LongDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(long), name, ns)
{
}
internal override string WriteMethodName { get { return "WriteLong"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsLong"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteLong((long)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsLong()
: HandleReadValue(reader.ReadElementContentAsLong(), context);
}
}
#if NET_NATIVE
public class UnsignedLongDataContract : PrimitiveDataContract
#else
internal class UnsignedLongDataContract : PrimitiveDataContract
#endif
{
public UnsignedLongDataContract() : base(typeof(ulong), DictionaryGlobals.UnsignedLongLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteUnsignedLong"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedLong"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteUnsignedLong((ulong)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsUnsignedLong()
: HandleReadValue(reader.ReadElementContentAsUnsignedLong(), context);
}
}
#if NET_NATIVE
public class FloatDataContract : PrimitiveDataContract
#else
internal class FloatDataContract : PrimitiveDataContract
#endif
{
public FloatDataContract() : base(typeof(float), DictionaryGlobals.FloatLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteFloat"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsFloat"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteFloat((float)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsFloat()
: HandleReadValue(reader.ReadElementContentAsFloat(), context);
}
}
#if NET_NATIVE
public class DoubleDataContract : PrimitiveDataContract
#else
internal class DoubleDataContract : PrimitiveDataContract
#endif
{
public DoubleDataContract() : base(typeof(double), DictionaryGlobals.DoubleLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteDouble"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsDouble"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteDouble((double)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsDouble()
: HandleReadValue(reader.ReadElementContentAsDouble(), context);
}
}
#if NET_NATIVE
public class DecimalDataContract : PrimitiveDataContract
#else
internal class DecimalDataContract : PrimitiveDataContract
#endif
{
public DecimalDataContract() : base(typeof(decimal), DictionaryGlobals.DecimalLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteDecimal"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsDecimal"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteDecimal((decimal)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsDecimal()
: HandleReadValue(reader.ReadElementContentAsDecimal(), context);
}
}
#if NET_NATIVE
public class DateTimeDataContract : PrimitiveDataContract
#else
internal class DateTimeDataContract : PrimitiveDataContract
#endif
{
public DateTimeDataContract() : base(typeof(DateTime), DictionaryGlobals.DateTimeLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteDateTime"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsDateTime"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteDateTime((DateTime)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsDateTime()
: HandleReadValue(reader.ReadElementContentAsDateTime(), context);
}
}
#if NET_NATIVE
public class StringDataContract : PrimitiveDataContract
#else
internal class StringDataContract : PrimitiveDataContract
#endif
{
public StringDataContract() : this(DictionaryGlobals.StringLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal StringDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(string), name, ns)
{
}
internal override string WriteMethodName { get { return "WriteString"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsString"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteString((string)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
if (context == null)
{
return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsString();
}
else
{
return HandleReadValue(reader.ReadElementContentAsString(), context);
}
}
}
internal class HexBinaryDataContract : StringDataContract
{
internal HexBinaryDataContract() : base(DictionaryGlobals.hexBinaryLocalName, DictionaryGlobals.SchemaNamespace) { }
}
#if NET_NATIVE
public class ByteArrayDataContract : PrimitiveDataContract
#else
internal class ByteArrayDataContract : PrimitiveDataContract
#endif
{
public ByteArrayDataContract() : base(typeof(byte[]), DictionaryGlobals.ByteArrayLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteBase64"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsBase64"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteBase64((byte[])obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
if (context == null)
{
return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsBase64();
}
else
{
return HandleReadValue(reader.ReadElementContentAsBase64(), context);
}
}
}
#if NET_NATIVE
public class ObjectDataContract : PrimitiveDataContract
#else
internal class ObjectDataContract : PrimitiveDataContract
#endif
{
public ObjectDataContract() : base(typeof(object), DictionaryGlobals.ObjectLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteAnyType"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsAnyType"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
// write nothing
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
object obj;
if (reader.IsEmptyElement)
{
reader.Skip();
obj = new object();
}
else
{
string localName = reader.LocalName;
string ns = reader.NamespaceURI;
reader.Read();
try
{
reader.ReadEndElement();
obj = new object();
}
catch (XmlException xes)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.XmlForObjectCannotHaveContent, localName, ns), xes));
}
}
return (context == null) ? obj : HandleReadValue(obj, context);
}
internal override bool CanContainReferences
{
get { return true; }
}
internal override bool IsPrimitive
{
get { return false; }
}
}
#if NET_NATIVE
public class TimeSpanDataContract : PrimitiveDataContract
#else
internal class TimeSpanDataContract : PrimitiveDataContract
#endif
{
public TimeSpanDataContract() : this(DictionaryGlobals.TimeSpanLocalName, DictionaryGlobals.SerializationNamespace)
{
}
internal TimeSpanDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(TimeSpan), name, ns)
{
}
internal override string WriteMethodName { get { return "WriteTimeSpan"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsTimeSpan"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteTimeSpan((TimeSpan)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsTimeSpan()
: HandleReadValue(reader.ReadElementContentAsTimeSpan(), context);
}
}
#if NET_NATIVE
public class GuidDataContract : PrimitiveDataContract
#else
internal class GuidDataContract : PrimitiveDataContract
#endif
{
public GuidDataContract() : this(DictionaryGlobals.GuidLocalName, DictionaryGlobals.SerializationNamespace)
{
}
internal GuidDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(Guid), name, ns)
{
}
internal override string WriteMethodName { get { return "WriteGuid"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsGuid"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteGuid((Guid)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsGuid()
: HandleReadValue(reader.ReadElementContentAsGuid(), context);
}
}
#if NET_NATIVE
public class UriDataContract : PrimitiveDataContract
#else
internal class UriDataContract : PrimitiveDataContract
#endif
{
public UriDataContract() : base(typeof(Uri), DictionaryGlobals.UriLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteUri"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsUri"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteUri((Uri)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
if (context == null)
{
return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsUri();
}
else
{
return HandleReadValue(reader.ReadElementContentAsUri(), context);
}
}
}
#if NET_NATIVE
public class QNameDataContract : PrimitiveDataContract
#else
internal class QNameDataContract : PrimitiveDataContract
#endif
{
public QNameDataContract() : base(typeof(XmlQualifiedName), DictionaryGlobals.QNameLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteQName"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsQName"; } }
internal override bool IsPrimitive
{
get { return false; }
}
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteQName((XmlQualifiedName)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
if (context == null)
{
return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsQName();
}
else
{
return HandleReadValue(reader.ReadElementContentAsQName(), context);
}
}
internal override void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString ns)
{
if (object.ReferenceEquals(ns, DictionaryGlobals.SerializationNamespace))
writer.WriteStartElement(Globals.SerPrefix, name, ns);
else if (ns != null && ns.Value != null && ns.Value.Length > 0)
writer.WriteStartElement(Globals.ElementPrefix, name, ns);
else
writer.WriteStartElement(name, ns);
}
}
}
| |
using System;
namespace Greatbone
{
/// <summary>
/// A text/plain model or comma-separate values (CSV). Also it can be used as a UTF-8 string builder.
/// </summary>
public class Text : ISource
{
protected char[] charbuf;
// number of chars
protected int count;
// combination of bytes
int sum;
// number of rest octets
int rest;
public Text(int capacity = 512)
{
charbuf = new char[capacity];
sum = 0;
rest = 0;
}
public int Count => count;
public void Add(char c)
{
// ensure capacity
int len = charbuf.Length; // old length
if (count >= len)
{
int newlen = len * 4; // new length
char[] buf = charbuf;
charbuf = new char[newlen];
Array.Copy(buf, 0, charbuf, 0, len);
}
charbuf[count++] = c;
}
// utf-8 decoding
public void Accept(int b)
{
// process a byte
if (rest == 0)
{
if (b > 0xff) // if a char already
{
Add((char) b);
return;
}
if (b < 0x80)
{
Add((char) b); // single byte
}
else if (b >= 0xc0 && b < 0xe0)
{
sum = (b & 0x1f) << 6;
rest = 1;
}
else if (b >= 0xe0 && b < 0xf0)
{
sum = (b & 0x0f) << 12;
rest = 2;
}
}
else if (rest == 1)
{
sum |= (b & 0x3f);
rest--;
Add((char) sum);
}
else if (rest == 2)
{
sum |= (b & 0x3f) << 6;
rest--;
}
}
public virtual void Clear()
{
count = 0;
sum = 0;
rest = 0;
}
public bool Get(string name, ref bool v)
{
throw new NotImplementedException();
}
public bool Get(string name, ref char v)
{
throw new NotImplementedException();
}
public bool Get(string name, ref short v)
{
throw new NotImplementedException();
}
public bool Get(string name, ref int v)
{
throw new NotImplementedException();
}
public bool Get(string name, ref long v)
{
throw new NotImplementedException();
}
public bool Get(string name, ref double v)
{
throw new NotImplementedException();
}
public bool Get(string name, ref decimal v)
{
throw new NotImplementedException();
}
public bool Get(string name, ref DateTime v)
{
throw new NotImplementedException();
}
public bool Get(string name, ref string v)
{
throw new NotImplementedException();
}
public bool Get(string name, ref ArraySegment<byte> v)
{
throw new NotImplementedException();
}
public bool Get(string name, ref byte[] v)
{
throw new NotImplementedException();
}
public bool Get(string name, ref short[] v)
{
throw new NotImplementedException();
}
public bool Get(string name, ref int[] v)
{
throw new NotImplementedException();
}
public bool Get(string name, ref long[] v)
{
throw new NotImplementedException();
}
public bool Get(string name, ref string[] v)
{
throw new NotImplementedException();
}
public bool Get(string name, ref JObj v)
{
throw new NotImplementedException();
}
public bool Get(string name, ref JArr v)
{
throw new NotImplementedException();
}
public bool Get<D>(string name, ref D v, byte proj = 0x0f) where D : IData, new()
{
throw new NotImplementedException();
}
public bool Get<D>(string name, ref D[] v, byte proj = 0x0f) where D : IData, new()
{
throw new NotImplementedException();
}
//
// LET
//
public ISource Let(out bool v)
{
throw new NotImplementedException();
}
public ISource Let(out char v)
{
throw new NotImplementedException();
}
public ISource Let(out short v)
{
throw new NotImplementedException();
}
public ISource Let(out int v)
{
throw new NotImplementedException();
}
public ISource Let(out long v)
{
throw new NotImplementedException();
}
public ISource Let(out double v)
{
throw new NotImplementedException();
}
public ISource Let(out decimal v)
{
throw new NotImplementedException();
}
public ISource Let(out DateTime v)
{
throw new NotImplementedException();
}
public ISource Let(out string v)
{
throw new NotImplementedException();
}
public ISource Let(out ArraySegment<byte> v)
{
throw new NotImplementedException();
}
public ISource Let(out short[] v)
{
throw new NotImplementedException();
}
public ISource Let(out int[] v)
{
throw new NotImplementedException();
}
public ISource Let(out long[] v)
{
throw new NotImplementedException();
}
public ISource Let(out string[] v)
{
throw new NotImplementedException();
}
public ISource Let(out JObj v)
{
throw new NotImplementedException();
}
public ISource Let(out JArr v)
{
throw new NotImplementedException();
}
public ISource Let<D>(out D v, byte proj = 0x0f) where D : IData, new()
{
throw new NotImplementedException();
}
public ISource Let<D>(out D[] v, byte proj = 0x0f) where D : IData, new()
{
throw new NotImplementedException();
}
//
// ENTITY
//
public D ToObject<D>(byte proj = 0x0f) where D : IData, new()
{
throw new NotImplementedException();
}
public D[] ToArray<D>(byte proj = 0x0f) where D : IData, new()
{
throw new NotImplementedException();
}
public bool DataSet => false;
public bool Next()
{
throw new NotImplementedException();
}
public void Write<C>(C cnt) where C : IContent, ISink
{
throw new NotImplementedException();
}
public IContent Dump()
{
var cnt = new TextContent(true, 4096);
cnt.Add(charbuf, 0, count);
return cnt;
}
public bool Equals(string str)
{
if (str == null || str.Length != count) return false;
for (int i = 0; i < count; i++)
{
if (charbuf[i] != str[i]) return false;
}
return true;
}
public bool StartsWith(string str)
{
if (str == null || str.Length > count) return false;
for (int i = 0; i < count; i++)
{
if (charbuf[i] != str[i]) return false;
}
return true;
}
public bool EndsWith(string str)
{
if (str == null || str.Length > count) return false;
for (int i = count - 1; i >= 0; i--)
{
if (charbuf[i] != str[i]) return false;
}
return true;
}
public string ToString(int start, int len)
{
return new string(charbuf, start, len);
}
public override string ToString()
{
return new string(charbuf, 0, count);
}
}
}
| |
namespace T5Suite2
{
partial class frmMultiAdapterConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.chkUseADC1 = new DevExpress.XtraEditors.CheckEdit();
this.chkUseADC2 = new DevExpress.XtraEditors.CheckEdit();
this.chkUseADC3 = new DevExpress.XtraEditors.CheckEdit();
this.chkUseADC4 = new DevExpress.XtraEditors.CheckEdit();
this.chkUseADC5 = new DevExpress.XtraEditors.CheckEdit();
this.chkUseThermoInput = new DevExpress.XtraEditors.CheckEdit();
this.groupControl1 = new DevExpress.XtraEditors.GroupControl();
this.labelControl1 = new DevExpress.XtraEditors.LabelControl();
this.textEdit1 = new DevExpress.XtraEditors.TextEdit();
this.buttonEdit5 = new DevExpress.XtraEditors.ButtonEdit();
this.buttonEdit4 = new DevExpress.XtraEditors.ButtonEdit();
this.buttonEdit3 = new DevExpress.XtraEditors.ButtonEdit();
this.buttonEdit2 = new DevExpress.XtraEditors.ButtonEdit();
this.buttonEdit1 = new DevExpress.XtraEditors.ButtonEdit();
this.simpleButton1 = new DevExpress.XtraEditors.SimpleButton();
((System.ComponentModel.ISupportInitialize)(this.chkUseADC1.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.chkUseADC2.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.chkUseADC3.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.chkUseADC4.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.chkUseADC5.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.chkUseThermoInput.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.groupControl1)).BeginInit();
this.groupControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.textEdit1.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.buttonEdit5.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.buttonEdit4.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.buttonEdit3.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.buttonEdit2.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.buttonEdit1.Properties)).BeginInit();
this.SuspendLayout();
//
// chkUseADC1
//
this.chkUseADC1.Location = new System.Drawing.Point(18, 37);
this.chkUseADC1.Name = "chkUseADC1";
this.chkUseADC1.Properties.Caption = "Use analogue to digital channel #1";
this.chkUseADC1.Size = new System.Drawing.Size(198, 18);
this.chkUseADC1.TabIndex = 0;
this.chkUseADC1.CheckedChanged += new System.EventHandler(this.chkUseADC1_CheckedChanged);
//
// chkUseADC2
//
this.chkUseADC2.Location = new System.Drawing.Point(18, 63);
this.chkUseADC2.Name = "chkUseADC2";
this.chkUseADC2.Properties.Caption = "Use analogue to digital channel #2";
this.chkUseADC2.Size = new System.Drawing.Size(198, 18);
this.chkUseADC2.TabIndex = 1;
this.chkUseADC2.CheckedChanged += new System.EventHandler(this.chkUseADC2_CheckedChanged);
//
// chkUseADC3
//
this.chkUseADC3.Location = new System.Drawing.Point(18, 89);
this.chkUseADC3.Name = "chkUseADC3";
this.chkUseADC3.Properties.Caption = "Use analogue to digital channel #3";
this.chkUseADC3.Size = new System.Drawing.Size(198, 18);
this.chkUseADC3.TabIndex = 2;
this.chkUseADC3.CheckedChanged += new System.EventHandler(this.chkUseADC3_CheckedChanged);
//
// chkUseADC4
//
this.chkUseADC4.Location = new System.Drawing.Point(18, 115);
this.chkUseADC4.Name = "chkUseADC4";
this.chkUseADC4.Properties.Caption = "Use analogue to digital channel #4";
this.chkUseADC4.Size = new System.Drawing.Size(198, 18);
this.chkUseADC4.TabIndex = 3;
this.chkUseADC4.CheckedChanged += new System.EventHandler(this.chkUseADC4_CheckedChanged);
//
// chkUseADC5
//
this.chkUseADC5.Location = new System.Drawing.Point(18, 141);
this.chkUseADC5.Name = "chkUseADC5";
this.chkUseADC5.Properties.Caption = "Use analogue to digital channel #5";
this.chkUseADC5.Size = new System.Drawing.Size(198, 18);
this.chkUseADC5.TabIndex = 4;
this.chkUseADC5.CheckedChanged += new System.EventHandler(this.chkUseADC5_CheckedChanged);
//
// chkUseThermoInput
//
this.chkUseThermoInput.Location = new System.Drawing.Point(18, 167);
this.chkUseThermoInput.Name = "chkUseThermoInput";
this.chkUseThermoInput.Properties.Caption = "Use thermocouple input";
this.chkUseThermoInput.Size = new System.Drawing.Size(198, 18);
this.chkUseThermoInput.TabIndex = 5;
this.chkUseThermoInput.CheckedChanged += new System.EventHandler(this.chkUseThermoInput_CheckedChanged);
//
// groupControl1
//
this.groupControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupControl1.Controls.Add(this.labelControl1);
this.groupControl1.Controls.Add(this.textEdit1);
this.groupControl1.Controls.Add(this.buttonEdit5);
this.groupControl1.Controls.Add(this.buttonEdit4);
this.groupControl1.Controls.Add(this.buttonEdit3);
this.groupControl1.Controls.Add(this.buttonEdit2);
this.groupControl1.Controls.Add(this.buttonEdit1);
this.groupControl1.Controls.Add(this.chkUseADC3);
this.groupControl1.Controls.Add(this.chkUseThermoInput);
this.groupControl1.Controls.Add(this.chkUseADC1);
this.groupControl1.Controls.Add(this.chkUseADC5);
this.groupControl1.Controls.Add(this.chkUseADC2);
this.groupControl1.Controls.Add(this.chkUseADC4);
this.groupControl1.Location = new System.Drawing.Point(12, 12);
this.groupControl1.Name = "groupControl1";
this.groupControl1.Size = new System.Drawing.Size(624, 206);
this.groupControl1.TabIndex = 6;
this.groupControl1.Text = "CombiAdapter options...";
//
// labelControl1
//
this.labelControl1.Location = new System.Drawing.Point(241, 174);
this.labelControl1.Name = "labelControl1";
this.labelControl1.Size = new System.Drawing.Size(68, 13);
this.labelControl1.TabIndex = 12;
this.labelControl1.Text = "Channel name";
//
// textEdit1
//
this.textEdit1.Enabled = false;
this.textEdit1.Location = new System.Drawing.Point(329, 167);
this.textEdit1.Name = "textEdit1";
this.textEdit1.Size = new System.Drawing.Size(271, 20);
this.textEdit1.TabIndex = 11;
//
// buttonEdit5
//
this.buttonEdit5.Enabled = false;
this.buttonEdit5.Location = new System.Drawing.Point(241, 141);
this.buttonEdit5.Name = "buttonEdit5";
this.buttonEdit5.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.buttonEdit5.Size = new System.Drawing.Size(359, 20);
this.buttonEdit5.TabIndex = 10;
this.buttonEdit5.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(this.buttonEdit5_ButtonClick);
//
// buttonEdit4
//
this.buttonEdit4.Enabled = false;
this.buttonEdit4.Location = new System.Drawing.Point(241, 115);
this.buttonEdit4.Name = "buttonEdit4";
this.buttonEdit4.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.buttonEdit4.Size = new System.Drawing.Size(359, 20);
this.buttonEdit4.TabIndex = 9;
this.buttonEdit4.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(this.buttonEdit4_ButtonClick);
//
// buttonEdit3
//
this.buttonEdit3.Enabled = false;
this.buttonEdit3.Location = new System.Drawing.Point(241, 89);
this.buttonEdit3.Name = "buttonEdit3";
this.buttonEdit3.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.buttonEdit3.Size = new System.Drawing.Size(359, 20);
this.buttonEdit3.TabIndex = 8;
this.buttonEdit3.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(this.buttonEdit3_ButtonClick);
//
// buttonEdit2
//
this.buttonEdit2.Enabled = false;
this.buttonEdit2.Location = new System.Drawing.Point(241, 63);
this.buttonEdit2.Name = "buttonEdit2";
this.buttonEdit2.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.buttonEdit2.Size = new System.Drawing.Size(359, 20);
this.buttonEdit2.TabIndex = 7;
this.buttonEdit2.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(this.buttonEdit2_ButtonClick);
//
// buttonEdit1
//
this.buttonEdit1.Enabled = false;
this.buttonEdit1.Location = new System.Drawing.Point(241, 37);
this.buttonEdit1.Name = "buttonEdit1";
this.buttonEdit1.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.buttonEdit1.Size = new System.Drawing.Size(359, 20);
this.buttonEdit1.TabIndex = 6;
this.buttonEdit1.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(this.buttonEdit1_ButtonClick);
//
// simpleButton1
//
this.simpleButton1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.simpleButton1.Location = new System.Drawing.Point(561, 224);
this.simpleButton1.Name = "simpleButton1";
this.simpleButton1.Size = new System.Drawing.Size(75, 23);
this.simpleButton1.TabIndex = 7;
this.simpleButton1.Text = "Ok";
this.simpleButton1.Click += new System.EventHandler(this.simpleButton1_Click);
//
// frmMultiAdapterConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(648, 259);
this.ControlBox = false;
this.Controls.Add(this.simpleButton1);
this.Controls.Add(this.groupControl1);
this.Name = "frmMultiAdapterConfig";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Configuration for CombiAdapter...";
((System.ComponentModel.ISupportInitialize)(this.chkUseADC1.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.chkUseADC2.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.chkUseADC3.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.chkUseADC4.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.chkUseADC5.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.chkUseThermoInput.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.groupControl1)).EndInit();
this.groupControl1.ResumeLayout(false);
this.groupControl1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.textEdit1.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.buttonEdit5.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.buttonEdit4.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.buttonEdit3.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.buttonEdit2.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.buttonEdit1.Properties)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraEditors.CheckEdit chkUseADC1;
private DevExpress.XtraEditors.CheckEdit chkUseADC2;
private DevExpress.XtraEditors.CheckEdit chkUseADC3;
private DevExpress.XtraEditors.CheckEdit chkUseADC4;
private DevExpress.XtraEditors.CheckEdit chkUseADC5;
private DevExpress.XtraEditors.CheckEdit chkUseThermoInput;
private DevExpress.XtraEditors.GroupControl groupControl1;
private DevExpress.XtraEditors.SimpleButton simpleButton1;
private DevExpress.XtraEditors.ButtonEdit buttonEdit5;
private DevExpress.XtraEditors.ButtonEdit buttonEdit4;
private DevExpress.XtraEditors.ButtonEdit buttonEdit3;
private DevExpress.XtraEditors.ButtonEdit buttonEdit2;
private DevExpress.XtraEditors.ButtonEdit buttonEdit1;
private DevExpress.XtraEditors.LabelControl labelControl1;
private DevExpress.XtraEditors.TextEdit textEdit1;
}
}
| |
/*
* 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.Reflection;
using System.Text;
using Nwc.XmlRpc;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "XmlRpcGroupsServicesConnectorModule")]
public class XmlRpcGroupsServicesConnectorModule : ISharedRegionModule, IGroupsServicesConnector
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_debugEnabled = false;
public const GroupPowers DefaultEveryonePowers
= GroupPowers.AllowSetHome
| GroupPowers.Accountable
| GroupPowers.JoinChat
| GroupPowers.AllowVoiceChat
| GroupPowers.ReceiveNotices
| GroupPowers.StartProposal
| GroupPowers.VoteOnProposal;
// Would this be cleaner as (GroupPowers)ulong.MaxValue?
public const GroupPowers DefaultOwnerPowers
= GroupPowers.Accountable
| GroupPowers.AllowEditLand
| GroupPowers.AllowFly
| GroupPowers.AllowLandmark
| GroupPowers.AllowRez
| GroupPowers.AllowSetHome
| GroupPowers.AllowVoiceChat
| GroupPowers.AssignMember
| GroupPowers.AssignMemberLimited
| GroupPowers.ChangeActions
| GroupPowers.ChangeIdentity
| GroupPowers.ChangeMedia
| GroupPowers.ChangeOptions
| GroupPowers.CreateRole
| GroupPowers.DeedObject
| GroupPowers.DeleteRole
| GroupPowers.Eject
| GroupPowers.FindPlaces
| GroupPowers.Invite
| GroupPowers.JoinChat
| GroupPowers.LandChangeIdentity
| GroupPowers.LandDeed
| GroupPowers.LandDivideJoin
| GroupPowers.LandEdit
| GroupPowers.LandEjectAndFreeze
| GroupPowers.LandGardening
| GroupPowers.LandManageAllowed
| GroupPowers.LandManageBanned
| GroupPowers.LandManagePasses
| GroupPowers.LandOptions
| GroupPowers.LandRelease
| GroupPowers.LandSetSale
| GroupPowers.ModerateChat
| GroupPowers.ObjectManipulate
| GroupPowers.ObjectSetForSale
| GroupPowers.ReceiveNotices
| GroupPowers.RemoveMember
| GroupPowers.ReturnGroupOwned
| GroupPowers.ReturnGroupSet
| GroupPowers.ReturnNonGroup
| GroupPowers.RoleProperties
| GroupPowers.SendNotices
| GroupPowers.SetLandingPoint
| GroupPowers.StartProposal
| GroupPowers.VoteOnProposal;
private bool m_connectorEnabled = false;
private string m_groupsServerURI = string.Empty;
private bool m_disableKeepAlive = true;
private string m_groupReadKey = string.Empty;
private string m_groupWriteKey = string.Empty;
private IUserAccountService m_accountService = null;
private ExpiringCache<string, XmlRpcResponse> m_memoryCache;
private int m_cacheTimeout = 30;
// Used to track which agents are have dropped from a group chat session
// Should be reset per agent, on logon
// TODO: move this to Flotsam XmlRpc Service
// SessionID, List<AgentID>
private Dictionary<UUID, List<UUID>> m_groupsAgentsDroppedFromChatSession = new Dictionary<UUID, List<UUID>>();
private Dictionary<UUID, List<UUID>> m_groupsAgentsInvitedToChatSession = new Dictionary<UUID, List<UUID>>();
#region Region Module interfaceBase Members
public string Name
{
get { return "XmlRpcGroupsServicesConnector"; }
}
// this module is not intended to be replaced, but there should only be 1 of them.
public Type ReplaceableInterface
{
get { return null; }
}
public void Initialise(IConfigSource config)
{
IConfig groupsConfig = config.Configs["Groups"];
if (groupsConfig == null)
{
// Do not run this module by default.
return;
}
else
{
// if groups aren't enabled, we're not needed.
// if we're not specified as the connector to use, then we're not wanted
if ((groupsConfig.GetBoolean("Enabled", false) == false)
|| (groupsConfig.GetString("ServicesConnectorModule", "XmlRpcGroupsServicesConnector") != Name))
{
m_connectorEnabled = false;
return;
}
m_log.DebugFormat("[XMLRPC-GROUPS-CONNECTOR]: Initializing {0}", this.Name);
m_groupsServerURI = groupsConfig.GetString("GroupsServerURI", string.Empty);
if (string.IsNullOrEmpty(m_groupsServerURI))
{
m_log.ErrorFormat("Please specify a valid URL for GroupsServerURI in OpenSim.ini, [Groups]");
m_connectorEnabled = false;
return;
}
m_disableKeepAlive = groupsConfig.GetBoolean("XmlRpcDisableKeepAlive", true);
m_groupReadKey = groupsConfig.GetString("XmlRpcServiceReadKey", string.Empty);
m_groupWriteKey = groupsConfig.GetString("XmlRpcServiceWriteKey", string.Empty);
m_cacheTimeout = groupsConfig.GetInt("GroupsCacheTimeout", 30);
if (m_cacheTimeout == 0)
{
m_log.WarnFormat("[XMLRPC-GROUPS-CONNECTOR]: Groups Cache Disabled.");
}
else
{
m_log.InfoFormat("[XMLRPC-GROUPS-CONNECTOR]: Groups Cache Timeout set to {0}.", m_cacheTimeout);
}
m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", false);
// If we got all the config options we need, lets start'er'up
m_memoryCache = new ExpiringCache<string, XmlRpcResponse>();
m_connectorEnabled = true;
}
}
public void Close()
{
}
public void AddRegion(OpenSim.Region.Framework.Scenes.Scene scene)
{
if (m_connectorEnabled)
{
if (m_accountService == null)
{
m_accountService = scene.UserAccountService;
}
scene.RegisterModuleInterface<IGroupsServicesConnector>(this);
}
}
public void RemoveRegion(OpenSim.Region.Framework.Scenes.Scene scene)
{
if (scene.RequestModuleInterface<IGroupsServicesConnector>() == this)
{
scene.UnregisterModuleInterface<IGroupsServicesConnector>(this);
}
}
public void RegionLoaded(OpenSim.Region.Framework.Scenes.Scene scene)
{
// TODO: May want to consider listenning for Agent Connections so we can pre-cache group info
// scene.EventManager.OnNewClient += OnNewClient;
}
#endregion
#region ISharedRegionModule Members
public void PostInitialise()
{
// NoOp
}
#endregion
#region IGroupsServicesConnector Members
/// <summary>
/// Create a Group, including Everyone and Owners Role, place FounderID in both groups, select Owner as selected role, and newly created group as agent's active role.
/// </summary>
public UUID CreateGroup(UUID requestingAgentID, string name, string charter, bool showInList, UUID insigniaID,
int membershipFee, bool openEnrollment, bool allowPublish,
bool maturePublish, UUID founderID)
{
UUID GroupID = UUID.Random();
UUID OwnerRoleID = UUID.Random();
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
param["Name"] = name;
param["Charter"] = charter;
param["ShowInList"] = showInList == true ? 1 : 0;
param["InsigniaID"] = insigniaID.ToString();
param["MembershipFee"] = membershipFee;
param["OpenEnrollment"] = openEnrollment == true ? 1 : 0;
param["AllowPublish"] = allowPublish == true ? 1 : 0;
param["MaturePublish"] = maturePublish == true ? 1 : 0;
param["FounderID"] = founderID.ToString();
param["EveryonePowers"] = ((ulong)DefaultEveryonePowers).ToString();
param["OwnerRoleID"] = OwnerRoleID.ToString();
param["OwnersPowers"] = ((ulong)DefaultOwnerPowers).ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.createGroup", param);
if (respData.Contains("error"))
{
// UUID is not nullable
return UUID.Zero;
}
return UUID.Parse((string)respData["GroupID"]);
}
public void UpdateGroup(UUID requestingAgentID, UUID groupID, string charter, bool showInList,
UUID insigniaID, int membershipFee, bool openEnrollment,
bool allowPublish, bool maturePublish)
{
Hashtable param = new Hashtable();
param["GroupID"] = groupID.ToString();
param["Charter"] = charter;
param["ShowInList"] = showInList == true ? 1 : 0;
param["InsigniaID"] = insigniaID.ToString();
param["MembershipFee"] = membershipFee;
param["OpenEnrollment"] = openEnrollment == true ? 1 : 0;
param["AllowPublish"] = allowPublish == true ? 1 : 0;
param["MaturePublish"] = maturePublish == true ? 1 : 0;
XmlRpcCall(requestingAgentID, "groups.updateGroup", param);
}
public void AddGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description,
string title, ulong powers)
{
Hashtable param = new Hashtable();
param["GroupID"] = groupID.ToString();
param["RoleID"] = roleID.ToString();
param["Name"] = name;
param["Description"] = description;
param["Title"] = title;
param["Powers"] = powers.ToString();
XmlRpcCall(requestingAgentID, "groups.addRoleToGroup", param);
}
public void RemoveGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID)
{
Hashtable param = new Hashtable();
param["GroupID"] = groupID.ToString();
param["RoleID"] = roleID.ToString();
XmlRpcCall(requestingAgentID, "groups.removeRoleFromGroup", param);
}
public void UpdateGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description,
string title, ulong powers)
{
Hashtable param = new Hashtable();
param["GroupID"] = groupID.ToString();
param["RoleID"] = roleID.ToString();
if (name != null)
{
param["Name"] = name;
}
if (description != null)
{
param["Description"] = description;
}
if (title != null)
{
param["Title"] = title;
}
param["Powers"] = powers.ToString();
XmlRpcCall(requestingAgentID, "groups.updateGroupRole", param);
}
public GroupRecord GetGroupRecord(UUID requestingAgentID, UUID GroupID, string GroupName)
{
Hashtable param = new Hashtable();
if (GroupID != UUID.Zero)
{
param["GroupID"] = GroupID.ToString();
}
if (!string.IsNullOrEmpty(GroupName))
{
param["Name"] = GroupName.ToString();
}
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroup", param);
if (respData.Contains("error"))
{
return null;
}
return GroupProfileHashtableToGroupRecord(respData);
}
public GroupProfileData GetMemberGroupProfile(UUID requestingAgentID, UUID GroupID, UUID AgentID)
{
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroup", param);
if (respData.Contains("error"))
{
// GroupProfileData is not nullable
return new GroupProfileData();
}
GroupMembershipData MemberInfo = GetAgentGroupMembership(requestingAgentID, AgentID, GroupID);
GroupProfileData MemberGroupProfile = GroupProfileHashtableToGroupProfileData(respData);
if(MemberInfo != null)
{
MemberGroupProfile.MemberTitle = MemberInfo.GroupTitle;
MemberGroupProfile.PowersMask = MemberInfo.GroupPowers;
}
return MemberGroupProfile;
}
public void SetAgentActiveGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
XmlRpcCall(requestingAgentID, "groups.setAgentActiveGroup", param);
}
public void SetAgentActiveGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
param["SelectedRoleID"] = RoleID.ToString();
XmlRpcCall(requestingAgentID, "groups.setAgentGroupInfo", param);
}
public void SetAgentGroupInfo(UUID requestingAgentID, UUID AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
param["AcceptNotices"] = AcceptNotices ? "1" : "0";
param["ListInProfile"] = ListInProfile ? "1" : "0";
XmlRpcCall(requestingAgentID, "groups.setAgentGroupInfo", param);
}
public void AddAgentToGroupInvite(UUID requestingAgentID, UUID inviteID, UUID groupID, UUID roleID, UUID agentID)
{
Hashtable param = new Hashtable();
param["InviteID"] = inviteID.ToString();
param["AgentID"] = agentID.ToString();
param["RoleID"] = roleID.ToString();
param["GroupID"] = groupID.ToString();
XmlRpcCall(requestingAgentID, "groups.addAgentToGroupInvite", param);
}
public GroupInviteInfo GetAgentToGroupInvite(UUID requestingAgentID, UUID inviteID)
{
Hashtable param = new Hashtable();
param["InviteID"] = inviteID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentToGroupInvite", param);
if (respData.Contains("error"))
{
return null;
}
GroupInviteInfo inviteInfo = new GroupInviteInfo();
inviteInfo.InviteID = inviteID;
inviteInfo.GroupID = UUID.Parse((string)respData["GroupID"]);
inviteInfo.RoleID = UUID.Parse((string)respData["RoleID"]);
inviteInfo.AgentID = UUID.Parse((string)respData["AgentID"]);
return inviteInfo;
}
public void RemoveAgentToGroupInvite(UUID requestingAgentID, UUID inviteID)
{
Hashtable param = new Hashtable();
param["InviteID"] = inviteID.ToString();
XmlRpcCall(requestingAgentID, "groups.removeAgentToGroupInvite", param);
}
public void AddAgentToGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
param["RoleID"] = RoleID.ToString();
XmlRpcCall(requestingAgentID, "groups.addAgentToGroup", param);
}
public void RemoveAgentFromGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
XmlRpcCall(requestingAgentID, "groups.removeAgentFromGroup", param);
}
public void AddAgentToGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
param["RoleID"] = RoleID.ToString();
XmlRpcCall(requestingAgentID, "groups.addAgentToGroupRole", param);
}
public void RemoveAgentFromGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
param["RoleID"] = RoleID.ToString();
XmlRpcCall(requestingAgentID, "groups.removeAgentFromGroupRole", param);
}
public List<DirGroupsReplyData> FindGroups(UUID requestingAgentID, string search)
{
Hashtable param = new Hashtable();
param["Search"] = search;
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.findGroups", param);
List<DirGroupsReplyData> findings = new List<DirGroupsReplyData>();
if (!respData.Contains("error"))
{
Hashtable results = (Hashtable)respData["results"];
foreach (Hashtable groupFind in results.Values)
{
DirGroupsReplyData data = new DirGroupsReplyData();
data.groupID = new UUID((string)groupFind["GroupID"]); ;
data.groupName = (string)groupFind["Name"];
data.members = int.Parse((string)groupFind["Members"]);
// data.searchOrder = order;
findings.Add(data);
}
}
return findings;
}
public GroupMembershipData GetAgentGroupMembership(UUID requestingAgentID, UUID AgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentGroupMembership", param);
if (respData.Contains("error"))
{
return null;
}
GroupMembershipData data = HashTableToGroupMembershipData(respData);
return data;
}
public GroupMembershipData GetAgentActiveMembership(UUID requestingAgentID, UUID AgentID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentActiveMembership", param);
if (respData.Contains("error"))
{
return null;
}
return HashTableToGroupMembershipData(respData);
}
public List<GroupMembershipData> GetAgentGroupMemberships(UUID requestingAgentID, UUID AgentID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentGroupMemberships", param);
List<GroupMembershipData> memberships = new List<GroupMembershipData>();
if (!respData.Contains("error"))
{
foreach (object membership in respData.Values)
{
memberships.Add(HashTableToGroupMembershipData((Hashtable)membership));
}
}
return memberships;
}
public List<GroupRolesData> GetAgentGroupRoles(UUID requestingAgentID, UUID AgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentRoles", param);
List<GroupRolesData> Roles = new List<GroupRolesData>();
if (respData.Contains("error"))
{
return Roles;
}
foreach (Hashtable role in respData.Values)
{
GroupRolesData data = new GroupRolesData();
data.RoleID = new UUID((string)role["RoleID"]);
data.Name = (string)role["Name"];
data.Description = (string)role["Description"];
data.Powers = ulong.Parse((string)role["Powers"]);
data.Title = (string)role["Title"];
Roles.Add(data);
}
return Roles;
}
public List<GroupRolesData> GetGroupRoles(UUID requestingAgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupRoles", param);
List<GroupRolesData> Roles = new List<GroupRolesData>();
if (respData.Contains("error"))
{
return Roles;
}
foreach (Hashtable role in respData.Values)
{
GroupRolesData data = new GroupRolesData();
data.Description = (string)role["Description"];
data.Members = int.Parse((string)role["Members"]);
data.Name = (string)role["Name"];
data.Powers = ulong.Parse((string)role["Powers"]);
data.RoleID = new UUID((string)role["RoleID"]);
data.Title = (string)role["Title"];
Roles.Add(data);
}
return Roles;
}
public List<GroupMembersData> GetGroupMembers(UUID requestingAgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupMembers", param);
List<GroupMembersData> members = new List<GroupMembersData>();
if (respData.Contains("error"))
{
return members;
}
foreach (Hashtable membership in respData.Values)
{
GroupMembersData data = new GroupMembersData();
data.AcceptNotices = ((string)membership["AcceptNotices"]) == "1";
data.AgentID = new UUID((string)membership["AgentID"]);
data.Contribution = int.Parse((string)membership["Contribution"]);
data.IsOwner = ((string)membership["IsOwner"]) == "1";
data.ListInProfile = ((string)membership["ListInProfile"]) == "1";
data.AgentPowers = ulong.Parse((string)membership["AgentPowers"]);
data.Title = (string)membership["Title"];
members.Add(data);
}
return members;
}
public List<GroupRoleMembersData> GetGroupRoleMembers(UUID requestingAgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupRoleMembers", param);
List<GroupRoleMembersData> members = new List<GroupRoleMembersData>();
if (!respData.Contains("error"))
{
foreach (Hashtable membership in respData.Values)
{
GroupRoleMembersData data = new GroupRoleMembersData();
data.MemberID = new UUID((string)membership["AgentID"]);
data.RoleID = new UUID((string)membership["RoleID"]);
members.Add(data);
}
}
return members;
}
public List<GroupNoticeData> GetGroupNotices(UUID requestingAgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupNotices", param);
List<GroupNoticeData> values = new List<GroupNoticeData>();
if (!respData.Contains("error"))
{
foreach (Hashtable value in respData.Values)
{
GroupNoticeData data = new GroupNoticeData();
data.NoticeID = UUID.Parse((string)value["NoticeID"]);
data.Timestamp = uint.Parse((string)value["Timestamp"]);
data.FromName = (string)value["FromName"];
data.Subject = (string)value["Subject"];
data.HasAttachment = false;
data.AssetType = 0;
values.Add(data);
}
}
return values;
}
public GroupNoticeInfo GetGroupNotice(UUID requestingAgentID, UUID noticeID)
{
Hashtable param = new Hashtable();
param["NoticeID"] = noticeID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupNotice", param);
if (respData.Contains("error"))
{
return null;
}
GroupNoticeInfo data = new GroupNoticeInfo();
data.GroupID = UUID.Parse((string)respData["GroupID"]);
data.Message = (string)respData["Message"];
data.BinaryBucket = Utils.HexStringToBytes((string)respData["BinaryBucket"], true);
data.noticeData.NoticeID = UUID.Parse((string)respData["NoticeID"]);
data.noticeData.Timestamp = uint.Parse((string)respData["Timestamp"]);
data.noticeData.FromName = (string)respData["FromName"];
data.noticeData.Subject = (string)respData["Subject"];
data.noticeData.HasAttachment = false;
data.noticeData.AssetType = 0;
if (data.Message == null)
{
data.Message = string.Empty;
}
return data;
}
public void AddGroupNotice(UUID requestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, byte[] binaryBucket)
{
string binBucket = OpenMetaverse.Utils.BytesToHexString(binaryBucket, "");
Hashtable param = new Hashtable();
param["GroupID"] = groupID.ToString();
param["NoticeID"] = noticeID.ToString();
param["FromName"] = fromName;
param["Subject"] = subject;
param["Message"] = message;
param["BinaryBucket"] = binBucket;
param["TimeStamp"] = ((uint)Util.UnixTimeSinceEpoch()).ToString();
XmlRpcCall(requestingAgentID, "groups.addGroupNotice", param);
}
#endregion
#region GroupSessionTracking
public void ResetAgentGroupChatSessions(UUID agentID)
{
foreach (List<UUID> agentList in m_groupsAgentsDroppedFromChatSession.Values)
{
agentList.Remove(agentID);
}
}
public bool hasAgentBeenInvitedToGroupChatSession(UUID agentID, UUID groupID)
{
// If we're tracking this group, and we can find them in the tracking, then they've been invited
return m_groupsAgentsInvitedToChatSession.ContainsKey(groupID)
&& m_groupsAgentsInvitedToChatSession[groupID].Contains(agentID);
}
public bool hasAgentDroppedGroupChatSession(UUID agentID, UUID groupID)
{
// If we're tracking drops for this group,
// and we find them, well... then they've dropped
return m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID)
&& m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID);
}
public void AgentDroppedFromGroupChatSession(UUID agentID, UUID groupID)
{
if (m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID))
{
if (m_groupsAgentsInvitedToChatSession[groupID].Contains(agentID))
m_groupsAgentsInvitedToChatSession[groupID].Remove(agentID);
// If not in dropped list, add
if (!m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID))
m_groupsAgentsDroppedFromChatSession[groupID].Add(agentID);
}
}
public void AgentInvitedToGroupChatSession(UUID agentID, UUID groupID)
{
// Add Session Status if it doesn't exist for this session
CreateGroupChatSessionTracking(groupID);
// If nessesary, remove from dropped list
if (m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID))
m_groupsAgentsDroppedFromChatSession[groupID].Remove(agentID);
if (!m_groupsAgentsInvitedToChatSession[groupID].Contains(agentID))
m_groupsAgentsInvitedToChatSession[groupID].Add(agentID);
}
private void CreateGroupChatSessionTracking(UUID groupID)
{
if (!m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID))
{
m_groupsAgentsDroppedFromChatSession.Add(groupID, new List<UUID>());
m_groupsAgentsInvitedToChatSession.Add(groupID, new List<UUID>());
}
}
#endregion
#region XmlRpcHashtableMarshalling
private GroupProfileData GroupProfileHashtableToGroupProfileData(Hashtable groupProfile)
{
GroupProfileData group = new GroupProfileData();
group.GroupID = UUID.Parse((string)groupProfile["GroupID"]);
group.Name = (string)groupProfile["Name"];
if (groupProfile["Charter"] != null)
{
group.Charter = (string)groupProfile["Charter"];
}
group.ShowInList = ((string)groupProfile["ShowInList"]) == "1";
group.InsigniaID = UUID.Parse((string)groupProfile["InsigniaID"]);
group.MembershipFee = int.Parse((string)groupProfile["MembershipFee"]);
group.OpenEnrollment = ((string)groupProfile["OpenEnrollment"]) == "1";
group.AllowPublish = ((string)groupProfile["AllowPublish"]) == "1";
group.MaturePublish = ((string)groupProfile["MaturePublish"]) == "1";
group.FounderID = UUID.Parse((string)groupProfile["FounderID"]);
group.OwnerRole = UUID.Parse((string)groupProfile["OwnerRoleID"]);
group.GroupMembershipCount = int.Parse((string)groupProfile["GroupMembershipCount"]);
group.GroupRolesCount = int.Parse((string)groupProfile["GroupRolesCount"]);
return group;
}
private GroupRecord GroupProfileHashtableToGroupRecord(Hashtable groupProfile)
{
GroupRecord group = new GroupRecord();
group.GroupID = UUID.Parse((string)groupProfile["GroupID"]);
group.GroupName = groupProfile["Name"].ToString();
if (groupProfile["Charter"] != null)
{
group.Charter = (string)groupProfile["Charter"];
}
group.ShowInList = ((string)groupProfile["ShowInList"]) == "1";
group.GroupPicture = UUID.Parse((string)groupProfile["InsigniaID"]);
group.MembershipFee = int.Parse((string)groupProfile["MembershipFee"]);
group.OpenEnrollment = ((string)groupProfile["OpenEnrollment"]) == "1";
group.AllowPublish = ((string)groupProfile["AllowPublish"]) == "1";
group.MaturePublish = ((string)groupProfile["MaturePublish"]) == "1";
group.FounderID = UUID.Parse((string)groupProfile["FounderID"]);
group.OwnerRoleID = UUID.Parse((string)groupProfile["OwnerRoleID"]);
return group;
}
private static GroupMembershipData HashTableToGroupMembershipData(Hashtable respData)
{
GroupMembershipData data = new GroupMembershipData();
data.AcceptNotices = ((string)respData["AcceptNotices"] == "1");
data.Contribution = int.Parse((string)respData["Contribution"]);
data.ListInProfile = ((string)respData["ListInProfile"] == "1");
data.ActiveRole = new UUID((string)respData["SelectedRoleID"]);
data.GroupTitle = (string)respData["Title"];
data.GroupPowers = ulong.Parse((string)respData["GroupPowers"]);
// Is this group the agent's active group
data.GroupID = new UUID((string)respData["GroupID"]);
UUID ActiveGroup = new UUID((string)respData["ActiveGroupID"]);
data.Active = data.GroupID.Equals(ActiveGroup);
data.AllowPublish = ((string)respData["AllowPublish"] == "1");
if (respData["Charter"] != null)
{
data.Charter = (string)respData["Charter"];
}
data.FounderID = new UUID((string)respData["FounderID"]);
data.GroupID = new UUID((string)respData["GroupID"]);
data.GroupName = (string)respData["GroupName"];
data.GroupPicture = new UUID((string)respData["InsigniaID"]);
data.MaturePublish = ((string)respData["MaturePublish"] == "1");
data.MembershipFee = int.Parse((string)respData["MembershipFee"]);
data.OpenEnrollment = ((string)respData["OpenEnrollment"] == "1");
data.ShowInList = ((string)respData["ShowInList"] == "1");
return data;
}
#endregion
/// <summary>
/// Encapsulate the XmlRpc call to standardize security and error handling.
/// </summary>
private Hashtable XmlRpcCall(UUID requestingAgentID, string function, Hashtable param)
{
XmlRpcResponse resp = null;
string CacheKey = null;
// Only bother with the cache if it isn't disabled.
if (m_cacheTimeout > 0)
{
if (!function.StartsWith("groups.get"))
{
// Any and all updates cause the cache to clear
m_memoryCache.Clear();
}
else
{
StringBuilder sb = new StringBuilder(requestingAgentID + function);
foreach (object key in param.Keys)
{
if (param[key] != null)
{
sb.AppendFormat(",{0}:{1}", key.ToString(), param[key].ToString());
}
}
CacheKey = sb.ToString();
m_memoryCache.TryGetValue(CacheKey, out resp);
}
}
if (resp == null)
{
if (m_debugEnabled)
m_log.DebugFormat("[XMLRPC-GROUPS-CONNECTOR]: Cache miss for key {0}", CacheKey);
string UserService;
UUID SessionID;
GetClientGroupRequestID(requestingAgentID, out UserService, out SessionID);
param.Add("RequestingAgentID", requestingAgentID.ToString());
param.Add("RequestingAgentUserService", UserService);
param.Add("RequestingSessionID", SessionID.ToString());
param.Add("ReadKey", m_groupReadKey);
param.Add("WriteKey", m_groupWriteKey);
IList parameters = new ArrayList();
parameters.Add(param);
ConfigurableKeepAliveXmlRpcRequest req;
req = new ConfigurableKeepAliveXmlRpcRequest(function, parameters, m_disableKeepAlive);
try
{
resp = req.Send(m_groupsServerURI);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[XMLRPC-GROUPS-CONNECTOR]: An error has occured while attempting to access the XmlRpcGroups server method {0} at {1}: {2}",
function, m_groupsServerURI, e.Message);
if(m_debugEnabled)
{
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0}", e.StackTrace);
foreach (string ResponseLine in req.RequestResponse.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
{
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} ", ResponseLine);
}
foreach (string key in param.Keys)
{
m_log.WarnFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} :: {1}", key, param[key].ToString());
}
}
if ((m_cacheTimeout > 0) && (CacheKey != null))
{
m_memoryCache.AddOrUpdate(CacheKey, resp, 10.0);
}
Hashtable respData = new Hashtable();
respData.Add("error", e.ToString());
return respData;
}
if ((m_cacheTimeout > 0) && (CacheKey != null))
{
m_memoryCache.AddOrUpdate(CacheKey, resp, 10.0);
}
}
if (resp.Value is Hashtable)
{
Hashtable respData = (Hashtable)resp.Value;
if (respData.Contains("error") && !respData.Contains("succeed"))
{
LogRespDataToConsoleError(requestingAgentID, function, param, respData);
}
return respData;
}
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: The XmlRpc server returned a {1} instead of a hashtable for {0}", function, resp.Value.GetType().ToString());
if (resp.Value is ArrayList)
{
ArrayList al = (ArrayList)resp.Value;
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: Contains {0} elements", al.Count);
foreach (object o in al)
{
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} :: {1}", o.GetType().ToString(), o.ToString());
}
}
else
{
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: Function returned: {0}", resp.Value.ToString());
}
Hashtable error = new Hashtable();
error.Add("error", "invalid return value");
return error;
}
private void LogRespDataToConsoleError(UUID requestingAgentID, string function, Hashtable param, Hashtable respData)
{
m_log.ErrorFormat(
"[XMLRPC-GROUPS-CONNECTOR]: Error when calling {0} for {1} with params {2}. Response params are {3}",
function, requestingAgentID, Util.PrettyFormatToSingleLine(param), Util.PrettyFormatToSingleLine(respData));
}
/// <summary>
/// Group Request Tokens are an attempt to allow the groups service to authenticate
/// requests.
/// TODO: This broke after the big grid refactor, either find a better way, or discard this
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
private void GetClientGroupRequestID(UUID AgentID, out string UserServiceURL, out UUID SessionID)
{
UserServiceURL = "";
SessionID = UUID.Zero;
// Need to rework this based on changes to User Services
/*
UserAccount userAccount = m_accountService.GetUserAccount(UUID.Zero,AgentID);
if (userAccount == null)
{
// This should be impossible. If I've been passed a reference to a client
// that client should be registered with the UserService. So something
// is horribly wrong somewhere.
m_log.WarnFormat("[GROUPS]: Could not find a UserServiceURL for {0}", AgentID);
}
else if (userProfile is ForeignUserProfileData)
{
// They aren't from around here
ForeignUserProfileData fupd = (ForeignUserProfileData)userProfile;
UserServiceURL = fupd.UserServerURI;
SessionID = fupd.CurrentAgent.SessionID;
}
else
{
// They're a local user, use this:
UserServiceURL = m_commManager.NetworkServersInfo.UserURL;
SessionID = userProfile.CurrentAgent.SessionID;
}
*/
}
}
}
namespace Nwc.XmlRpc
{
using System;
using System.Collections;
using System.IO;
using System.Xml;
using System.Net;
using System.Text;
using System.Reflection;
/// <summary>Class supporting the request side of an XML-RPC transaction.</summary>
public class ConfigurableKeepAliveXmlRpcRequest : XmlRpcRequest
{
private XmlRpcRequestSerializer _serializer = new XmlRpcRequestSerializer();
private XmlRpcResponseDeserializer _deserializer = new XmlRpcResponseDeserializer();
private bool _disableKeepAlive = true;
public string RequestResponse = String.Empty;
/// <summary>Instantiate an <c>XmlRpcRequest</c> for a specified method and parameters.</summary>
/// <param name="methodName"><c>String</c> designating the <i>object.method</i> on the server the request
/// should be directed to.</param>
/// <param name="parameters"><c>ArrayList</c> of XML-RPC type parameters to invoke the request with.</param>
public ConfigurableKeepAliveXmlRpcRequest(String methodName, IList parameters, bool disableKeepAlive)
{
MethodName = methodName;
_params = parameters;
_disableKeepAlive = disableKeepAlive;
}
/// <summary>Send the request to the server.</summary>
/// <param name="url"><c>String</c> The url of the XML-RPC server.</param>
/// <returns><c>XmlRpcResponse</c> The response generated.</returns>
public XmlRpcResponse Send(String url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
if (request == null)
throw new XmlRpcException(XmlRpcErrorCodes.TRANSPORT_ERROR,
XmlRpcErrorCodes.TRANSPORT_ERROR_MSG + ": Could not create request with " + url);
request.Method = "POST";
request.ContentType = "text/xml";
request.AllowWriteStreamBuffering = true;
request.KeepAlive = !_disableKeepAlive;
request.Timeout = 30000;
using (Stream stream = request.GetRequestStream())
{
using (XmlTextWriter xml = new XmlTextWriter(stream, Encoding.ASCII))
{
_serializer.Serialize(xml, this);
xml.Flush();
}
}
XmlRpcResponse resp;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream s = response.GetResponseStream())
{
using (StreamReader input = new StreamReader(s))
{
string inputXml = input.ReadToEnd();
try
{
resp = (XmlRpcResponse)_deserializer.Deserialize(inputXml);
}
catch (Exception e)
{
RequestResponse = inputXml;
throw e;
}
}
}
}
return resp;
}
}
}
| |
using System;
using System.Collections.Generic;
namespace SharpCompress.Compressor.Rar.VM
{
internal class RarVM : BitInput
{
//private void InitBlock()
//{
// Mem.set_Renamed(offset + 0, Byte.valueOf((sbyte) (value_Renamed & 0xff)));
// Mem.set_Renamed(offset + 1, Byte.valueOf((sbyte) ((Utility.URShift(value_Renamed, 8)) & 0xff)));
// Mem.set_Renamed(offset + 2, Byte.valueOf((sbyte) ((Utility.URShift(value_Renamed, 16)) & 0xff)));
// Mem.set_Renamed(offset + 3, Byte.valueOf((sbyte) ((Utility.URShift(value_Renamed, 24)) & 0xff)));
//}
internal byte[] Mem { get; private set; }
public const int VM_MEMSIZE = 0x40000;
//UPGRADE_NOTE: Final was removed from the declaration of 'VM_MEMMASK '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int VM_MEMMASK = (VM_MEMSIZE - 1);
public const int VM_GLOBALMEMADDR = 0x3C000;
public const int VM_GLOBALMEMSIZE = 0x2000;
public const int VM_FIXEDGLOBALSIZE = 64;
private const int regCount = 8;
private const long UINT_MASK = 0xffffFFFF; //((long)2*(long)Integer.MAX_VALUE);
private int[] R = new int[regCount];
private VMFlags flags;
private int maxOpCount = 25000000;
private int codeSize;
private int IP;
internal RarVM()
{
//InitBlock();
Mem = null;
}
internal void init()
{
if (Mem == null)
{
Mem = new byte[VM_MEMSIZE + 4];
}
}
private bool IsVMMem(byte[] mem)
{
return this.Mem == mem;
}
private int GetValue(bool byteMode, byte[] mem, int offset)
{
if (byteMode)
{
if (IsVMMem(mem))
{
return (mem[offset]);
}
else
{
return (mem[offset] & 0xff);
}
}
else
{
if (IsVMMem(mem))
{
return Utility.readIntLittleEndian(mem, offset);
}
else
{
return Utility.readIntBigEndian(mem, offset);
}
}
}
private void SetValue(bool byteMode, byte[] mem, int offset, int value)
{
if (byteMode)
{
if (IsVMMem(mem))
{
mem[offset] = (byte) value;
}
else
{
mem[offset] = (byte) ((mem[offset] & 0x00) | (byte) (value & 0xff));
}
}
else
{
if (IsVMMem(mem))
{
Utility.WriteLittleEndian(mem, offset, value);
// Mem[offset + 0] = (byte) value;
// Mem[offset + 1] = (byte) (value >>> 8);
// Mem[offset + 2] = (byte) (value >>> 16);
// Mem[offset + 3] = (byte) (value >>> 24);
}
else
{
Utility.writeIntBigEndian(mem, offset, value);
// Mem[offset + 3] = (byte) value;
// Mem[offset + 2] = (byte) (value >>> 8);
// Mem[offset + 1] = (byte) (value >>> 16);
// Mem[offset + 0] = (byte) (value >>> 24);
}
}
// #define SET_VALUE(ByteMode,Addr,Value) SetValue(ByteMode,(uint
// *)Addr,Value)
}
internal void SetLowEndianValue(List<byte> mem, int offset, int value)
{
mem[offset + 0] = (byte) (value & 0xff);
mem[offset + 1] = (byte) (Utility.URShift(value, 8) & 0xff);
mem[offset + 2] = (byte) (Utility.URShift(value, 16) & 0xff);
mem[offset + 3] = (byte) (Utility.URShift(value, 24) & 0xff);
}
private int GetOperand(VMPreparedOperand cmdOp)
{
int ret = 0;
if (cmdOp.Type == VMOpType.VM_OPREGMEM)
{
int pos = (cmdOp.Offset + cmdOp.Base) & VM_MEMMASK;
ret = Utility.readIntLittleEndian(Mem, pos);
}
else
{
int pos = cmdOp.Offset;
ret = Utility.readIntLittleEndian(Mem, pos);
}
return ret;
}
public void execute(VMPreparedProgram prg)
{
for (int i = 0; i < prg.InitR.Length; i++)
// memcpy(R,Prg->InitR,sizeof(Prg->InitR));
{
R[i] = prg.InitR[i];
}
long globalSize = (long) (Math.Min(prg.GlobalData.Count, VM_GLOBALMEMSIZE)) & 0xffFFffFF;
if (globalSize != 0)
{
for (int i = 0; i < globalSize; i++)
// memcpy(Mem+VM_GLOBALMEMADDR,&Prg->GlobalData[0],GlobalSize);
{
Mem[VM_GLOBALMEMADDR + i] = prg.GlobalData[i];
}
}
long staticSize = (long) (Math.Min(prg.StaticData.Count, VM_GLOBALMEMSIZE - globalSize)) & 0xffFFffFF;
if (staticSize != 0)
{
for (int i = 0; i < staticSize; i++)
// memcpy(Mem+VM_GLOBALMEMADDR+GlobalSize,&Prg->StaticData[0],StaticSize);
{
Mem[VM_GLOBALMEMADDR + (int) globalSize + i] = prg.StaticData[i];
}
}
R[7] = VM_MEMSIZE;
flags = 0;
//UPGRADE_NOTE: There is an untranslated Statement. Please refer to original code. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1153'"
List<VMPreparedCommand> preparedCode = prg.AltCommands.Count != 0
? prg
.AltCommands
: prg.Commands;
if (!ExecuteCode(preparedCode, prg.CommandCount))
{
preparedCode[0].OpCode = VMCommands.VM_RET;
}
int newBlockPos = GetValue(false, Mem, VM_GLOBALMEMADDR + 0x20) & VM_MEMMASK;
int newBlockSize = GetValue(false, Mem, VM_GLOBALMEMADDR + 0x1c) & VM_MEMMASK;
if ((newBlockPos + newBlockSize) >= VM_MEMSIZE)
{
newBlockPos = 0;
newBlockSize = 0;
}
prg.FilteredDataOffset = newBlockPos;
prg.FilteredDataSize = newBlockSize;
prg.GlobalData.Clear();
int dataSize = Math.Min(GetValue(false, Mem, VM_GLOBALMEMADDR + 0x30), VM_GLOBALMEMSIZE - VM_FIXEDGLOBALSIZE);
if (dataSize != 0)
{
//prg.GlobalData.Clear();
// ->GlobalData.Add(dataSize+VM_FIXEDGLOBALSIZE);
//prg.GlobalData.SetSize(dataSize + VM_FIXEDGLOBALSIZE);
Utility.SetSize(prg.GlobalData,dataSize + VM_FIXEDGLOBALSIZE);
for (int i = 0; i < dataSize + VM_FIXEDGLOBALSIZE; i++)
// memcpy(&Prg->GlobalData[0],&Mem[VM_GLOBALMEMADDR],DataSize+VM_FIXEDGLOBALSIZE);
{
prg.GlobalData[i] = Mem[VM_GLOBALMEMADDR + i];
}
}
}
private bool setIP(int ip)
{
if ((ip) >= codeSize)
{
return (true);
}
if (--maxOpCount <= 0)
{
return (false);
}
IP = ip;
return true;
}
private bool ExecuteCode(List<VMPreparedCommand> preparedCode,
int cmdCount)
{
maxOpCount = 25000000;
this.codeSize = cmdCount;
this.IP = 0;
while (true)
{
VMPreparedCommand cmd = preparedCode[IP];
int op1 = GetOperand(cmd.Op1);
int op2 = GetOperand(cmd.Op2);
switch (cmd.OpCode)
{
case VMCommands.VM_MOV:
SetValue(cmd.IsByteMode, Mem, op1, GetValue(cmd.IsByteMode, Mem, op2));
// SET_VALUE(Cmd->ByteMode,Op1,GET_VALUE(Cmd->ByteMode,Op2));
break;
case VMCommands.VM_MOVB:
SetValue(true, Mem, op1, GetValue(true, Mem, op2));
break;
case VMCommands.VM_MOVD:
SetValue(false, Mem, op1, GetValue(false, Mem, op2));
break;
case VMCommands.VM_CMP:
{
VMFlags value1 = (VMFlags) GetValue(cmd.IsByteMode, Mem, op1);
VMFlags result = value1 - GetValue(cmd.IsByteMode, Mem, op2);
if (result == 0)
{
flags = VMFlags.VM_FZ;
}
else
{
flags = (VMFlags) ((result > value1) ? 1 : 0 | (int) (result & VMFlags.VM_FS));
}
}
break;
case VMCommands.VM_CMPB:
{
VMFlags value1 = (VMFlags) GetValue(true, Mem, op1);
VMFlags result = value1 - GetValue(true, Mem, op2);
if (result == 0)
{
flags = VMFlags.VM_FZ;
}
else
{
flags = (VMFlags) ((result > value1) ? 1 : 0 | (int) (result & VMFlags.VM_FS));
}
}
break;
case VMCommands.VM_CMPD:
{
VMFlags value1 = (VMFlags) GetValue(false, Mem, op1);
VMFlags result = value1 - GetValue(false, Mem, op2);
if (result == 0)
{
flags = VMFlags.VM_FZ;
}
else
{
flags = (VMFlags) ((result > value1) ? 1 : 0 | (int) (result & VMFlags.VM_FS));
}
}
break;
case VMCommands.VM_ADD:
{
int value1 = GetValue(cmd.IsByteMode, Mem, op1);
int result =
(int)
((((long) value1 + (long) GetValue(cmd.IsByteMode, Mem, op2))) &
unchecked((int) 0xffffffff));
if (cmd.IsByteMode)
{
result &= 0xff;
flags =
(VMFlags)
((result < value1)
? 1
: 0 |
(result == 0
? (int) VMFlags.VM_FZ
: (((result & 0x80) != 0) ? (int) VMFlags.VM_FS : 0)));
// Flags=(Result<Value1)|(Result==0 ? VM_FZ:((Result&0x80) ?
// VM_FS:0));
}
else
flags =
(VMFlags)
((result < value1)
? 1
: 0 | (result == 0 ? (int) VMFlags.VM_FZ : (result & (int) VMFlags.VM_FS)));
SetValue(cmd.IsByteMode, Mem, op1, result);
}
break;
case VMCommands.VM_ADDB:
SetValue(true, Mem, op1,
(int)
((long) GetValue(true, Mem, op1) & 0xFFffFFff + (long) GetValue(true, Mem, op2) &
unchecked((int) 0xFFffFFff)));
break;
case VMCommands.VM_ADDD:
SetValue(false, Mem, op1,
(int)
((long) GetValue(false, Mem, op1) & 0xFFffFFff + (long) GetValue(false, Mem, op2) &
unchecked((int) 0xFFffFFff)));
break;
case VMCommands.VM_SUB:
{
int value1 = GetValue(cmd.IsByteMode, Mem, op1);
int result =
(int)
((long) value1 & 0xffFFffFF - (long) GetValue(cmd.IsByteMode, Mem, op2) &
unchecked((int) 0xFFffFFff));
flags =
(VMFlags)
((result == 0)
? (int) VMFlags.VM_FZ
: ((result > value1) ? 1 : 0 | (result & (int) VMFlags.VM_FS)));
SetValue(cmd.IsByteMode, Mem, op1, result); // (Cmd->ByteMode,Op1,Result);
}
break;
case VMCommands.VM_SUBB:
SetValue(true, Mem, op1,
(int)
((long) GetValue(true, Mem, op1) & 0xFFffFFff - (long) GetValue(true, Mem, op2) &
unchecked((int) 0xFFffFFff)));
break;
case VMCommands.VM_SUBD:
SetValue(false, Mem, op1,
(int)
((long) GetValue(false, Mem, op1) & 0xFFffFFff - (long) GetValue(false, Mem, op2) &
unchecked((int) 0xFFffFFff)));
break;
case VMCommands.VM_JZ:
if ((flags & VMFlags.VM_FZ) != 0)
{
setIP(GetValue(false, Mem, op1));
continue;
}
break;
case VMCommands.VM_JNZ:
if ((flags & VMFlags.VM_FZ) == 0)
{
setIP(GetValue(false, Mem, op1));
continue;
}
break;
case VMCommands.VM_INC:
{
int result = (int) ((long) GetValue(cmd.IsByteMode, Mem, op1) & 0xFFffFFffL + 1L);
if (cmd.IsByteMode)
{
result &= 0xff;
}
SetValue(cmd.IsByteMode, Mem, op1, result);
flags = (VMFlags) (result == 0 ? (int) VMFlags.VM_FZ : result & (int) VMFlags.VM_FS);
}
break;
case VMCommands.VM_INCB:
SetValue(true, Mem, op1, (int) ((long) GetValue(true, Mem, op1) & 0xFFffFFffL + 1L));
break;
case VMCommands.VM_INCD:
SetValue(false, Mem, op1, (int) ((long) GetValue(false, Mem, op1) & 0xFFffFFffL + 1L));
break;
case VMCommands.VM_DEC:
{
int result = (int) ((long) GetValue(cmd.IsByteMode, Mem, op1) & 0xFFffFFff - 1);
SetValue(cmd.IsByteMode, Mem, op1, result);
flags = (VMFlags) (result == 0 ? (int) VMFlags.VM_FZ : result & (int) VMFlags.VM_FS);
}
break;
case VMCommands.VM_DECB:
SetValue(true, Mem, op1, (int) ((long) GetValue(true, Mem, op1) & 0xFFffFFff - 1));
break;
case VMCommands.VM_DECD:
SetValue(false, Mem, op1, (int) ((long) GetValue(false, Mem, op1) & 0xFFffFFff - 1));
break;
case VMCommands.VM_JMP:
setIP(GetValue(false, Mem, op1));
continue;
case VMCommands.VM_XOR:
{
int result = GetValue(cmd.IsByteMode, Mem, op1) ^ GetValue(cmd.IsByteMode, Mem, op2);
flags = (VMFlags) (result == 0 ? (int) VMFlags.VM_FZ : result & (int) VMFlags.VM_FS);
SetValue(cmd.IsByteMode, Mem, op1, result);
}
break;
case VMCommands.VM_AND:
{
int result = GetValue(cmd.IsByteMode, Mem, op1) & GetValue(cmd.IsByteMode, Mem, op2);
flags = (VMFlags) (result == 0 ? (int) VMFlags.VM_FZ : result & (int) VMFlags.VM_FS);
SetValue(cmd.IsByteMode, Mem, op1, result);
}
break;
case VMCommands.VM_OR:
{
int result = GetValue(cmd.IsByteMode, Mem, op1) | GetValue(cmd.IsByteMode, Mem, op2);
flags = (VMFlags) (result == 0 ? (int) VMFlags.VM_FZ : result & (int) VMFlags.VM_FS);
SetValue(cmd.IsByteMode, Mem, op1, result);
}
break;
case VMCommands.VM_TEST:
{
int result = GetValue(cmd.IsByteMode, Mem, op1) & GetValue(cmd.IsByteMode, Mem, op2);
flags = (VMFlags) (result == 0 ? (int) VMFlags.VM_FZ : result & (int) VMFlags.VM_FS);
}
break;
case VMCommands.VM_JS:
if ((flags & VMFlags.VM_FS) != 0)
{
setIP(GetValue(false, Mem, op1));
continue;
}
break;
case VMCommands.VM_JNS:
if ((flags & VMFlags.VM_FS) == 0)
{
setIP(GetValue(false, Mem, op1));
continue;
}
break;
case VMCommands.VM_JB:
if ((flags & VMFlags.VM_FC) != 0)
{
setIP(GetValue(false, Mem, op1));
continue;
}
break;
case VMCommands.VM_JBE:
if ((flags & (VMFlags.VM_FC | VMFlags.VM_FZ)) != 0)
{
setIP(GetValue(false, Mem, op1));
continue;
}
break;
case VMCommands.VM_JA:
if ((flags & (VMFlags.VM_FC | VMFlags.VM_FZ)) == 0)
{
setIP(GetValue(false, Mem, op1));
continue;
}
break;
case VMCommands.VM_JAE:
if ((flags & VMFlags.VM_FC) == 0)
{
setIP(GetValue(false, Mem, op1));
continue;
}
break;
case VMCommands.VM_PUSH:
R[7] -= 4;
SetValue(false, Mem, R[7] & VM_MEMMASK, GetValue(false, Mem, op1));
break;
case VMCommands.VM_POP:
SetValue(false, Mem, op1, GetValue(false, Mem, R[7] & VM_MEMMASK));
R[7] += 4;
break;
case VMCommands.VM_CALL:
R[7] -= 4;
SetValue(false, Mem, R[7] & VM_MEMMASK, IP + 1);
setIP(GetValue(false, Mem, op1));
continue;
case VMCommands.VM_NOT:
SetValue(cmd.IsByteMode, Mem, op1, ~GetValue(cmd.IsByteMode, Mem, op1));
break;
case VMCommands.VM_SHL:
{
int value1 = GetValue(cmd.IsByteMode, Mem, op1);
int value2 = GetValue(cmd.IsByteMode, Mem, op2);
int result = value1 << value2;
flags =
(VMFlags)
((result == 0 ? (int) VMFlags.VM_FZ : (result & (int) VMFlags.VM_FS)) |
(((value1 << (value2 - 1)) & unchecked((int) 0x80000000)) != 0
? (int) VMFlags.VM_FC
: 0));
SetValue(cmd.IsByteMode, Mem, op1, result);
}
break;
case VMCommands.VM_SHR:
{
int value1 = GetValue(cmd.IsByteMode, Mem, op1);
int value2 = GetValue(cmd.IsByteMode, Mem, op2);
int result = Utility.URShift(value1, value2);
flags =
(VMFlags)
((result == 0 ? (int) VMFlags.VM_FZ : (result & (int) VMFlags.VM_FS)) |
((Utility.URShift(value1, (value2 - 1))) & (int) VMFlags.VM_FC));
SetValue(cmd.IsByteMode, Mem, op1, result);
}
break;
case VMCommands.VM_SAR:
{
int value1 = GetValue(cmd.IsByteMode, Mem, op1);
int value2 = GetValue(cmd.IsByteMode, Mem, op2);
int result = ((int) value1) >> value2;
flags =
(VMFlags)
((result == 0 ? (int) VMFlags.VM_FZ : (result & (int) VMFlags.VM_FS)) |
((value1 >> (value2 - 1)) & (int) VMFlags.VM_FC));
SetValue(cmd.IsByteMode, Mem, op1, result);
}
break;
case VMCommands.VM_NEG:
{
int result = -GetValue(cmd.IsByteMode, Mem, op1);
flags =
(VMFlags)
(result == 0
? (int) VMFlags.VM_FZ
: (int) VMFlags.VM_FC | (result & (int) VMFlags.VM_FS));
SetValue(cmd.IsByteMode, Mem, op1, result);
}
break;
case VMCommands.VM_NEGB:
SetValue(true, Mem, op1, -GetValue(true, Mem, op1));
break;
case VMCommands.VM_NEGD:
SetValue(false, Mem, op1, -GetValue(false, Mem, op1));
break;
case VMCommands.VM_PUSHA:
{
for (int i = 0, SP = R[7] - 4; i < regCount; i++, SP -= 4)
{
SetValue(false, Mem, SP & VM_MEMMASK, R[i]);
}
R[7] -= regCount*4;
}
break;
case VMCommands.VM_POPA:
{
for (int i = 0, SP = R[7]; i < regCount; i++, SP += 4)
R[7 - i] = GetValue(false, Mem, SP & VM_MEMMASK);
}
break;
case VMCommands.VM_PUSHF:
R[7] -= 4;
SetValue(false, Mem, R[7] & VM_MEMMASK, (int) flags);
break;
case VMCommands.VM_POPF:
flags = (VMFlags) GetValue(false, Mem, R[7] & VM_MEMMASK);
R[7] += 4;
break;
case VMCommands.VM_MOVZX:
SetValue(false, Mem, op1, GetValue(true, Mem, op2));
break;
case VMCommands.VM_MOVSX:
SetValue(false, Mem, op1, (byte) GetValue(true, Mem, op2));
break;
case VMCommands.VM_XCHG:
{
int value1 = GetValue(cmd.IsByteMode, Mem, op1);
SetValue(cmd.IsByteMode, Mem, op1, GetValue(cmd.IsByteMode, Mem, op2));
SetValue(cmd.IsByteMode, Mem, op2, value1);
}
break;
case VMCommands.VM_MUL:
{
int result =
(int)
(((long) GetValue(cmd.IsByteMode, Mem, op1) &
0xFFffFFff*(long) GetValue(cmd.IsByteMode, Mem, op2) & unchecked((int) 0xFFffFFff)) &
unchecked((int) 0xFFffFFff));
SetValue(cmd.IsByteMode, Mem, op1, result);
}
break;
case VMCommands.VM_DIV:
{
int divider = GetValue(cmd.IsByteMode, Mem, op2);
if (divider != 0)
{
int result = GetValue(cmd.IsByteMode, Mem, op1)/divider;
SetValue(cmd.IsByteMode, Mem, op1, result);
}
}
break;
case VMCommands.VM_ADC:
{
int value1 = GetValue(cmd.IsByteMode, Mem, op1);
int FC = (int) (flags & VMFlags.VM_FC);
int result =
(int)
((long) value1 & 0xFFffFFff + (long) GetValue(cmd.IsByteMode, Mem, op2) &
0xFFffFFff + (long) FC & unchecked((int) 0xFFffFFff));
if (cmd.IsByteMode)
{
result &= 0xff;
}
flags =
(VMFlags)
((result < value1 || result == value1 && FC != 0)
? 1
: 0 | (result == 0 ? (int) VMFlags.VM_FZ : (result & (int) VMFlags.VM_FS)));
SetValue(cmd.IsByteMode, Mem, op1, result);
}
break;
case VMCommands.VM_SBB:
{
int value1 = GetValue(cmd.IsByteMode, Mem, op1);
int FC = (int) (flags & VMFlags.VM_FC);
int result =
(int)
((long) value1 & 0xFFffFFff - (long) GetValue(cmd.IsByteMode, Mem, op2) &
0xFFffFFff - (long) FC & unchecked((int) 0xFFffFFff));
if (cmd.IsByteMode)
{
result &= 0xff;
}
flags =
(VMFlags)
((result > value1 || result == value1 && FC != 0)
? 1
: 0 | (result == 0 ? (int) VMFlags.VM_FZ : (result & (int) VMFlags.VM_FS)));
SetValue(cmd.IsByteMode, Mem, op1, result);
}
break;
case VMCommands.VM_RET:
if (R[7] >= VM_MEMSIZE)
{
return (true);
}
setIP(GetValue(false, Mem, R[7] & VM_MEMMASK));
R[7] += 4;
continue;
case VMCommands.VM_STANDARD:
ExecuteStandardFilter((VMStandardFilters) (cmd.Op1.Data));
break;
case VMCommands.VM_PRINT:
break;
}
IP++;
--maxOpCount;
}
}
public void prepare(byte[] code, int codeSize, VMPreparedProgram prg)
{
InitBitInput();
int cpLength = System.Math.Min(MAX_SIZE, codeSize);
// memcpy(inBuf,Code,Min(CodeSize,BitInput::MAX_SIZE));
#if !PORTABLE
Buffer.BlockCopy(code, 0, InBuf, 0, cpLength);
#else
Array.Copy(code, 0, InBuf, 0, cpLength);
#endif
byte xorSum = 0;
for (int i = 1; i < codeSize; i++)
{
xorSum ^= code[i];
}
AddBits(8);
prg.CommandCount = 0;
if (xorSum == code[0])
{
VMStandardFilters filterType = IsStandardFilter(code, codeSize);
if (filterType != VMStandardFilters.VMSF_NONE)
{
VMPreparedCommand curCmd = new VMPreparedCommand();
curCmd.OpCode = VMCommands.VM_STANDARD;
curCmd.Op1.Data = (int) filterType;
curCmd.Op1.Type = VMOpType.VM_OPNONE;
curCmd.Op2.Type = VMOpType.VM_OPNONE;
codeSize = 0;
prg.Commands.Add(curCmd);
prg.CommandCount = prg.CommandCount + 1;
// TODO
// curCmd->Op1.Data=FilterType;
// >>>>>> CurCmd->Op1.Addr=&CurCmd->Op1.Data; <<<<<<<<<< not set
// do i need to ?
// >>>>>> CurCmd->Op2.Addr=&CurCmd->Op2.Data; <<<<<<<<<< "
// CurCmd->Op1.Type=CurCmd->Op2.Type=VM_OPNONE;
// CodeSize=0;
}
int dataFlag = GetBits();
AddBits(1);
// Read static data contained in DB operators. This data cannot be
// changed,
// it is a part of VM code, not a filter parameter.
if ((dataFlag & 0x8000) != 0)
{
long dataSize = (long) ((long) ReadData(this) & 0xffFFffFFL + 1L);
for (int i = 0; inAddr < codeSize && i < dataSize; i++)
{
prg.StaticData.Add((byte) (GetBits() >> 8));
AddBits(8);
}
}
while (inAddr < codeSize)
{
VMPreparedCommand curCmd = new VMPreparedCommand();
int data = GetBits();
if ((data & 0x8000) == 0)
{
curCmd.OpCode = (VMCommands) ((data >> 12));
AddBits(4);
}
else
{
curCmd.OpCode = (VMCommands) ((data >> 10) - 24);
AddBits(6);
}
if ((VMCmdFlags.VM_CmdFlags[(int) curCmd.OpCode] & VMCmdFlags.VMCF_BYTEMODE) != 0)
{
curCmd.IsByteMode = (GetBits() >> 15) == 1 ? true : false;
AddBits(1);
}
else
{
curCmd.IsByteMode = false;
}
curCmd.Op1.Type = VMOpType.VM_OPNONE;
curCmd.Op2.Type = VMOpType.VM_OPNONE;
int opNum = (VMCmdFlags.VM_CmdFlags[(int) curCmd.OpCode] & VMCmdFlags.VMCF_OPMASK);
// TODO >>> CurCmd->Op1.Addr=CurCmd->Op2.Addr=NULL; <<<???
if (opNum > 0)
{
decodeArg(curCmd.Op1, curCmd.IsByteMode);
if (opNum == 2)
decodeArg(curCmd.Op2, curCmd.IsByteMode);
else
{
if (curCmd.Op1.Type == VMOpType.VM_OPINT &&
(VMCmdFlags.VM_CmdFlags[(int) curCmd.OpCode] &
(VMCmdFlags.VMCF_JUMP | VMCmdFlags.VMCF_PROC)) != 0)
{
int distance = curCmd.Op1.Data;
if (distance >= 256)
distance -= 256;
else
{
if (distance >= 136)
{
distance -= 264;
}
else
{
if (distance >= 16)
{
distance -= 8;
}
else
{
if (distance >= 8)
{
distance -= 16;
}
}
}
distance += prg.CommandCount;
}
curCmd.Op1.Data = distance;
}
}
}
prg.CommandCount = (prg.CommandCount + 1);
prg.Commands.Add(curCmd);
}
}
VMPreparedCommand curCmd2 = new VMPreparedCommand();
curCmd2.OpCode = VMCommands.VM_RET;
// TODO CurCmd->Op1.Addr=&CurCmd->Op1.Data;
// CurCmd->Op2.Addr=&CurCmd->Op2.Data;
curCmd2.Op1.Type = VMOpType.VM_OPNONE;
curCmd2.Op2.Type = VMOpType.VM_OPNONE;
// for (int i=0;i<prg.CmdCount;i++)
// {
// VM_PreparedCommand *Cmd=&Prg->Cmd[I];
// if (Cmd->Op1.Addr==NULL)
// Cmd->Op1.Addr=&Cmd->Op1.Data;
// if (Cmd->Op2.Addr==NULL)
// Cmd->Op2.Addr=&Cmd->Op2.Data;
// }
prg.Commands.Add(curCmd2);
prg.CommandCount = prg.CommandCount + 1;
// #ifdef VM_OPTIMIZE
if (codeSize != 0)
{
optimize(prg);
}
}
private void decodeArg(VMPreparedOperand op, bool byteMode)
{
int data = GetBits();
if ((data & 0x8000) != 0)
{
op.Type = VMOpType.VM_OPREG;
op.Data = (data >> 12) & 7;
op.Offset = op.Data;
AddBits(4);
}
else
{
if ((data & 0xc000) == 0)
{
op.Type = VMOpType.VM_OPINT;
if (byteMode)
{
op.Data = (data >> 6) & 0xff;
AddBits(10);
}
else
{
AddBits(2);
op.Data = ReadData(this);
}
}
else
{
op.Type = VMOpType.VM_OPREGMEM;
if ((data & 0x2000) == 0)
{
op.Data = (data >> 10) & 7;
op.Offset = op.Data;
op.Base = 0;
AddBits(6);
}
else
{
if ((data & 0x1000) == 0)
{
op.Data = (data >> 9) & 7;
op.Offset = op.Data;
AddBits(7);
}
else
{
op.Data = 0;
AddBits(4);
}
op.Base = ReadData(this);
}
}
}
}
private void optimize(VMPreparedProgram prg)
{
//UPGRADE_NOTE: There is an untranslated Statement. Please refer to original code. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1153'"
List<VMPreparedCommand> commands = prg.Commands;
//UPGRADE_ISSUE: The following fragment of code could not be parsed and was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1156'"
foreach (VMPreparedCommand cmd in commands)
{
switch (cmd.OpCode)
{
case VMCommands.VM_MOV:
cmd.OpCode = cmd.IsByteMode ? VMCommands.VM_MOVB : VMCommands.VM_MOVD;
continue;
case VMCommands.VM_CMP:
cmd.OpCode = cmd.IsByteMode ? VMCommands.VM_CMPB : VMCommands.VM_CMPD;
continue;
}
if ((VMCmdFlags.VM_CmdFlags[(int) cmd.OpCode] & VMCmdFlags.VMCF_CHFLAGS) == 0)
{
continue;
}
bool flagsRequired = false;
for (int i = commands.IndexOf(cmd) + 1; i < commands.Count; i++)
{
int flags = VMCmdFlags.VM_CmdFlags[(int) commands[i].OpCode];
if ((flags & (VMCmdFlags.VMCF_JUMP | VMCmdFlags.VMCF_PROC | VMCmdFlags.VMCF_USEFLAGS)) != 0)
{
flagsRequired = true;
break;
}
if ((flags & VMCmdFlags.VMCF_CHFLAGS) != 0)
{
break;
}
}
if (flagsRequired)
{
continue;
}
switch (cmd.OpCode)
{
case VMCommands.VM_ADD:
cmd.OpCode = cmd.IsByteMode ? VMCommands.VM_ADDB : VMCommands.VM_ADDD;
continue;
case VMCommands.VM_SUB:
cmd.OpCode = cmd.IsByteMode ? VMCommands.VM_SUBB : VMCommands.VM_SUBD;
continue;
case VMCommands.VM_INC:
cmd.OpCode = cmd.IsByteMode ? VMCommands.VM_INCB : VMCommands.VM_INCD;
continue;
case VMCommands.VM_DEC:
cmd.OpCode = cmd.IsByteMode ? VMCommands.VM_DECB : VMCommands.VM_DECD;
continue;
case VMCommands.VM_NEG:
cmd.OpCode = cmd.IsByteMode ? VMCommands.VM_NEGB : VMCommands.VM_NEGD;
continue;
}
}
}
internal static int ReadData(BitInput rarVM)
{
int data = rarVM.GetBits();
switch (data & 0xc000)
{
case 0:
rarVM.AddBits(6);
return ((data >> 10) & 0xf);
case 0x4000:
if ((data & 0x3c00) == 0)
{
data = unchecked((int) 0xffffff00) | ((data >> 2) & 0xff);
rarVM.AddBits(14);
}
else
{
data = (data >> 6) & 0xff;
rarVM.AddBits(10);
}
return (data);
case 0x8000:
rarVM.AddBits(2);
data = rarVM.GetBits();
rarVM.AddBits(16);
return (data);
default:
rarVM.AddBits(2);
data = (rarVM.GetBits() << 16);
rarVM.AddBits(16);
data |= rarVM.GetBits();
rarVM.AddBits(16);
return (data);
}
}
private VMStandardFilters IsStandardFilter(byte[] code, int codeSize)
{
VMStandardFilterSignature[] stdList = new VMStandardFilterSignature[]
{
new VMStandardFilterSignature(53, 0xad576887,
VMStandardFilters.VMSF_E8),
new VMStandardFilterSignature(57, 0x3cd7e57e,
VMStandardFilters.VMSF_E8E9),
new VMStandardFilterSignature(120, 0x3769893f,
VMStandardFilters.VMSF_ITANIUM),
new VMStandardFilterSignature(29, 0x0e06077d,
VMStandardFilters.VMSF_DELTA),
new VMStandardFilterSignature(149, 0x1c2c5dc8,
VMStandardFilters.VMSF_RGB),
new VMStandardFilterSignature(216, 0xbc85e701,
VMStandardFilters.VMSF_AUDIO),
new VMStandardFilterSignature(40, 0x46b9c560,
VMStandardFilters.VMSF_UPCASE)
};
uint CodeCRC = RarCRC.CheckCrc(0xffffffff, code, 0, code.Length) ^ 0xffffffff;
for (int i = 0; i < stdList.Length; i++)
{
if (stdList[i].CRC == CodeCRC && stdList[i].Length == code.Length)
{
return (stdList[i].Type);
}
}
return (VMStandardFilters.VMSF_NONE);
}
private void ExecuteStandardFilter(VMStandardFilters filterType)
{
switch (filterType)
{
case VMStandardFilters.VMSF_E8:
case VMStandardFilters.VMSF_E8E9:
{
int dataSize = R[4];
long fileOffset = R[6] & unchecked((int) 0xFFffFFff);
if (dataSize >= VM_GLOBALMEMADDR)
{
break;
}
int fileSize = 0x1000000;
byte cmpByte2 = (byte) ((filterType == VMStandardFilters.VMSF_E8E9) ? 0xe9 : 0xe8);
for (int curPos = 0; curPos < dataSize - 4;)
{
byte curByte = Mem[curPos++];
if (curByte == 0xe8 || curByte == cmpByte2)
{
// #ifdef PRESENT_INT32
// sint32 Offset=CurPos+FileOffset;
// sint32 Addr=GET_VALUE(false,Data);
// if (Addr<0)
// {
// if (Addr+Offset>=0)
// SET_VALUE(false,Data,Addr+FileSize);
// }
// else
// if (Addr<FileSize)
// SET_VALUE(false,Data,Addr-Offset);
// #else
long offset = curPos + fileOffset;
long Addr = GetValue(false, Mem, curPos);
if ((Addr & unchecked((int) 0x80000000)) != 0)
{
if (((Addr + offset) & unchecked((int) 0x80000000)) == 0)
SetValue(false, Mem, curPos, (int) Addr + fileSize);
}
else
{
if (((Addr - fileSize) & unchecked((int) 0x80000000)) != 0)
{
SetValue(false, Mem, curPos, (int) (Addr - offset));
}
}
// #endif
curPos += 4;
}
}
}
break;
case VMStandardFilters.VMSF_ITANIUM:
{
int dataSize = R[4];
long fileOffset = R[6] & unchecked((int) 0xFFffFFff);
if (dataSize >= VM_GLOBALMEMADDR)
{
break;
}
int curPos = 0;
//UPGRADE_NOTE: Final was removed from the declaration of 'Masks '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
byte[] Masks = new byte[] {4, 4, 6, 6, 0, 0, 7, 7, 4, 4, 0, 0, 4, 4, 0, 0};
fileOffset = Utility.URShift(fileOffset, 4);
while (curPos < dataSize - 21)
{
int Byte = (Mem[curPos] & 0x1f) - 0x10;
if (Byte >= 0)
{
byte cmdMask = Masks[Byte];
if (cmdMask != 0)
for (int i = 0; i <= 2; i++)
if ((cmdMask & (1 << i)) != 0)
{
int startPos = i*41 + 5;
int opType = filterItanium_GetBits(curPos, startPos + 37, 4);
if (opType == 5)
{
int offset = filterItanium_GetBits(curPos, startPos + 13, 20);
filterItanium_SetBits(curPos, (int) (offset - fileOffset) & 0xfffff,
startPos + 13, 20);
}
}
}
curPos += 16;
fileOffset++;
}
}
break;
case VMStandardFilters.VMSF_DELTA:
{
int dataSize = R[4] & unchecked((int) 0xFFffFFff);
int channels = R[0] & unchecked((int) 0xFFffFFff);
int srcPos = 0;
int border = (dataSize*2) & unchecked((int) 0xFFffFFff);
SetValue(false, Mem, VM_GLOBALMEMADDR + 0x20, (int) dataSize);
if (dataSize >= VM_GLOBALMEMADDR/2)
{
break;
}
// bytes from same channels are grouped to continual data blocks,
// so we need to place them back to their interleaving positions
for (int curChannel = 0; curChannel < channels; curChannel++)
{
byte PrevByte = 0;
for (int destPos = dataSize + curChannel; destPos < border; destPos += channels)
{
Mem[destPos] = (PrevByte = (byte) (PrevByte - Mem[srcPos++]));
}
}
}
break;
case VMStandardFilters.VMSF_RGB:
{
// byte *SrcData=Mem,*DestData=SrcData+DataSize;
int dataSize = R[4], width = R[0] - 3, posR = R[1];
int channels = 3;
int srcPos = 0;
int destDataPos = dataSize;
SetValue(false, Mem, VM_GLOBALMEMADDR + 0x20, dataSize);
if (dataSize >= VM_GLOBALMEMADDR/2 || posR < 0)
{
break;
}
for (int curChannel = 0; curChannel < channels; curChannel++)
{
long prevByte = 0;
for (int i = curChannel; i < dataSize; i += channels)
{
long predicted;
int upperPos = i - width;
if (upperPos >= 3)
{
int upperDataPos = destDataPos + upperPos;
int upperByte = Mem[(int) upperDataPos] & 0xff;
int upperLeftByte = Mem[upperDataPos - 3] & 0xff;
predicted = prevByte + upperByte - upperLeftByte;
int pa = System.Math.Abs((int) (predicted - prevByte));
int pb = System.Math.Abs((int) (predicted - upperByte));
int pc = System.Math.Abs((int) (predicted - upperLeftByte));
if (pa <= pb && pa <= pc)
{
predicted = prevByte;
}
else
{
if (pb <= pc)
{
predicted = upperByte;
}
else
{
predicted = upperLeftByte;
}
}
}
else
{
predicted = prevByte;
}
prevByte = (predicted - Mem[srcPos++] & 0xff) & 0xff;
Mem[destDataPos + i] = (byte) (prevByte & 0xff);
}
}
for (int i = posR, border = dataSize - 2; i < border; i += 3)
{
byte G = Mem[destDataPos + i + 1];
Mem[destDataPos + i] = (byte) (Mem[destDataPos + i] + G);
Mem[destDataPos + i + 2] = (byte) (Mem[destDataPos + i + 2] + G);
}
}
break;
case VMStandardFilters.VMSF_AUDIO:
{
int dataSize = R[4], channels = R[0];
int srcPos = 0;
int destDataPos = dataSize;
//byte *SrcData=Mem,*DestData=SrcData+DataSize;
SetValue(false, Mem, VM_GLOBALMEMADDR + 0x20, dataSize);
if (dataSize >= VM_GLOBALMEMADDR/2)
{
break;
}
for (int curChannel = 0; curChannel < channels; curChannel++)
{
long prevByte = 0;
long prevDelta = 0;
long[] Dif = new long[7];
int D1 = 0, D2 = 0, D3;
int K1 = 0, K2 = 0, K3 = 0;
for (int i = curChannel, byteCount = 0; i < dataSize; i += channels, byteCount++)
{
D3 = D2;
D2 = (int) (prevDelta - D1);
D1 = (int) prevDelta;
long predicted = 8*prevByte + K1*D1 + K2*D2 + K3*D3;
predicted = Utility.URShift(predicted, 3) & 0xff;
long curByte = (long) (Mem[srcPos++]);
predicted -= curByte;
Mem[destDataPos + i] = (byte) predicted;
prevDelta = (byte) (predicted - prevByte);
//fix java byte
if (prevDelta >= 128)
{
prevDelta = 0 - (256 - prevDelta);
}
prevByte = predicted;
//fix java byte
if (curByte >= 128)
{
curByte = 0 - (256 - curByte);
}
int D = ((int) curByte) << 3;
Dif[0] += System.Math.Abs(D);
Dif[1] += System.Math.Abs(D - D1);
Dif[2] += System.Math.Abs(D + D1);
Dif[3] += System.Math.Abs(D - D2);
Dif[4] += System.Math.Abs(D + D2);
Dif[5] += System.Math.Abs(D - D3);
Dif[6] += System.Math.Abs(D + D3);
if ((byteCount & 0x1f) == 0)
{
long minDif = Dif[0], numMinDif = 0;
Dif[0] = 0;
for (int j = 1; j < Dif.Length; j++)
{
if (Dif[j] < minDif)
{
minDif = Dif[j];
numMinDif = j;
}
Dif[j] = 0;
}
switch ((int) numMinDif)
{
case 1:
if (K1 >= -16)
K1--;
break;
case 2:
if (K1 < 16)
K1++;
break;
case 3:
if (K2 >= -16)
K2--;
break;
case 4:
if (K2 < 16)
K2++;
break;
case 5:
if (K3 >= -16)
K3--;
break;
case 6:
if (K3 < 16)
K3++;
break;
}
}
}
}
}
break;
case VMStandardFilters.VMSF_UPCASE:
{
int dataSize = R[4], srcPos = 0, destPos = dataSize;
if (dataSize >= VM_GLOBALMEMADDR/2)
{
break;
}
while (srcPos < dataSize)
{
byte curByte = Mem[srcPos++];
if (curByte == 2 && (curByte = Mem[srcPos++]) != 2)
{
curByte = (byte) (curByte - 32);
}
Mem[destPos++] = curByte;
}
SetValue(false, Mem, VM_GLOBALMEMADDR + 0x1c, destPos - dataSize);
SetValue(false, Mem, VM_GLOBALMEMADDR + 0x20, dataSize);
}
break;
}
}
private void filterItanium_SetBits(int curPos, int bitField, int bitPos, int bitCount)
{
int inAddr = bitPos/8;
int inBit = bitPos & 7;
int andMask = Utility.URShift(unchecked((int) 0xffffffff), (32 - bitCount));
andMask = ~(andMask << inBit);
bitField <<= inBit;
for (int i = 0; i < 4; i++)
{
Mem[curPos + inAddr + i] &= (byte) (andMask);
Mem[curPos + inAddr + i] |= (byte) (bitField);
andMask = (Utility.URShift(andMask, 8)) | unchecked((int) 0xff000000);
bitField = Utility.URShift(bitField, 8);
}
}
private int filterItanium_GetBits(int curPos, int bitPos, int bitCount)
{
int inAddr = bitPos/8;
int inBit = bitPos & 7;
int bitField = (int) (Mem[curPos + inAddr++] & 0xff);
bitField |= (int) ((Mem[curPos + inAddr++] & 0xff) << 8);
bitField |= (int) ((Mem[curPos + inAddr++] & 0xff) << 16);
bitField |= (int) ((Mem[curPos + inAddr] & 0xff) << 24);
bitField = Utility.URShift(bitField, inBit);
return (bitField & (Utility.URShift(unchecked((int) 0xffffffff), (32 - bitCount))));
}
public virtual void setMemory(int pos, byte[] data, int offset, int dataSize)
{
if (pos < VM_MEMSIZE)
{
//&& data!=Mem+Pos)
//memmove(Mem+Pos,Data,Min(DataSize,VM_MEMSIZE-Pos));
for (int i = 0; i < System.Math.Min(data.Length - offset, dataSize); i++)
{
if ((VM_MEMSIZE - pos) < i)
{
break;
}
Mem[pos + i] = data[offset + i];
}
}
}
}
//
}
| |
// Copyright (c) rubicon IT GmbH, www.rubicon.eu
//
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership. rubicon licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Remotion.Linq.Clauses.ExpressionTreeVisitors;
using Remotion.Linq.Parsing.ExpressionTreeVisitors;
using Remotion.Linq.Parsing.ExpressionTreeVisitors.Transformation;
using Remotion.Linq.Parsing.Structure.ExpressionTreeProcessors;
using Remotion.Linq.Parsing.Structure.IntermediateModel;
using Remotion.Linq.Parsing.Structure.NodeTypeProviders;
using Remotion.Linq.Utilities;
namespace Remotion.Linq.Parsing.Structure
{
/// <summary>
/// Parses an expression tree into a chain of <see cref="IExpressionNode"/> objects after executing a sequence of
/// <see cref="IExpressionTreeProcessor"/> objects.
/// </summary>
internal sealed class ExpressionTreeParser
{
#if NETFX_CORE
private static readonly MethodInfo s_getArrayLengthMethod = typeof (Array).GetRuntimeProperty ("Length").GetMethod;
#else
private static readonly MethodInfo s_getArrayLengthMethod = typeof (Array).GetProperty ("Length").GetGetMethod();
#endif
[Obsolete (
"This method has been removed. Use QueryParser.CreateDefault, or create a customized ExpressionTreeParser using the constructor. (1.13.93)",
true)]
public static ExpressionTreeParser CreateDefault ()
{
throw new NotImplementedException();
}
/// <summary>
/// Creates a default <see cref="CompoundNodeTypeProvider"/> that already has all expression node parser defined by the re-linq assembly
/// registered. Users can add inner providers to register their own expression node parsers.
/// </summary>
/// <returns>A default <see cref="CompoundNodeTypeProvider"/> that already has all expression node parser defined by the re-linq assembly
/// registered.</returns>
public static CompoundNodeTypeProvider CreateDefaultNodeTypeProvider ()
{
#if NETFX_CORE
var searchedTypes = typeof (MethodInfoBasedNodeTypeRegistry).GetTypeInfo().Assembly.DefinedTypes.Select (ti => ti.AsType()).ToList();
#else
var searchedTypes = typeof (MethodInfoBasedNodeTypeRegistry).GetTypeInfo().Assembly.GetTypes().Select (ti => ti.AsType()).ToList();
#endif
var innerProviders = new INodeTypeProvider[]
{
MethodInfoBasedNodeTypeRegistry.CreateFromTypes (searchedTypes),
MethodNameBasedNodeTypeRegistry.CreateFromTypes(searchedTypes)
};
return new CompoundNodeTypeProvider (innerProviders);
}
/// <summary>
/// Creates a default <see cref="CompoundExpressionTreeProcessor"/> that already has the expression tree processing steps defined by the re-linq assembly
/// registered. Users can insert additional processing steps.
/// </summary>
/// <param name="tranformationProvider">The tranformation provider to be used by the <see cref="TransformingExpressionTreeProcessor"/> included
/// in the result set. Use <see cref="ExpressionTransformerRegistry.CreateDefault"/> to create a default provider.</param>
/// <returns>
/// A default <see cref="CompoundExpressionTreeProcessor"/> that already has all expression tree processing steps defined by the re-linq assembly
/// registered.
/// </returns>
/// <remarks>
/// The following steps are included:
/// <list type="bullet">
/// <item><see cref="PartialEvaluatingExpressionTreeProcessor"/></item>
/// <item><see cref="TransformingExpressionTreeProcessor"/> (parameterized with <paramref name="tranformationProvider"/>)</item>
/// </list>
/// </remarks>
public static CompoundExpressionTreeProcessor CreateDefaultProcessor (IExpressionTranformationProvider tranformationProvider)
{
ArgumentUtility.CheckNotNull ("tranformationProvider", tranformationProvider);
return new CompoundExpressionTreeProcessor (new IExpressionTreeProcessor[] {
new PartialEvaluatingExpressionTreeProcessor(),
new TransformingExpressionTreeProcessor (tranformationProvider) });
}
private readonly UniqueIdentifierGenerator _identifierGenerator = new UniqueIdentifierGenerator ();
private readonly INodeTypeProvider _nodeTypeProvider;
private readonly IExpressionTreeProcessor _processor;
private readonly MethodCallExpressionParser _methodCallExpressionParser;
/// <summary>
/// Initializes a new instance of the <see cref="ExpressionTreeParser"/> class with a custom <see cref="INodeTypeProvider"/> and
/// <see cref="IExpressionTreeProcessor"/> implementation.
/// </summary>
/// <param name="nodeTypeProvider">The <see cref="INodeTypeProvider"/> to use when parsing <see cref="Expression"/> trees. Use
/// <see cref="CreateDefaultNodeTypeProvider"/> to create an instance of <see cref="CompoundNodeTypeProvider"/> that already includes all
/// default node types. (The <see cref="CompoundNodeTypeProvider"/> can be customized as needed by adding or removing
/// <see cref="CompoundNodeTypeProvider.InnerProviders"/>).</param>
/// <param name="processor">The <see cref="IExpressionTreeProcessor"/> to apply to <see cref="Expression"/> trees before parsing their nodes. Use
/// <see cref="CreateDefaultProcessor"/> to create an instance of <see cref="CompoundExpressionTreeProcessor"/> that already includes
/// the default steps. (The <see cref="CompoundExpressionTreeProcessor"/> can be customized as needed by adding or removing
/// <see cref="CompoundExpressionTreeProcessor.InnerProcessors"/>).</param>
public ExpressionTreeParser (INodeTypeProvider nodeTypeProvider, IExpressionTreeProcessor processor)
{
ArgumentUtility.CheckNotNull ("nodeTypeProvider", nodeTypeProvider);
ArgumentUtility.CheckNotNull ("processor", processor);
_nodeTypeProvider = nodeTypeProvider;
_processor = processor;
_methodCallExpressionParser = new MethodCallExpressionParser (_nodeTypeProvider);
}
/// <summary>
/// Gets the node type provider used to parse <see cref="MethodCallExpression"/> instances in <see cref="ParseTree"/>.
/// </summary>
/// <value>The node type provider.</value>
public INodeTypeProvider NodeTypeProvider
{
get { return _nodeTypeProvider; }
}
/// <summary>
/// Gets the processing steps used by <see cref="ParseTree"/> to process the <see cref="Expression"/> tree before analyzing its structure.
/// </summary>
/// <value>The processing steps.</value>
public IExpressionTreeProcessor Processor
{
get { return _processor; }
}
/// <summary>
/// Parses the given <paramref name="expressionTree"/> into a chain of <see cref="IExpressionNode"/> instances, using
/// <see cref="MethodInfoBasedNodeTypeRegistry"/> to convert expressions to nodes.
/// </summary>
/// <param name="expressionTree">The expression tree to parse.</param>
/// <returns>A chain of <see cref="IExpressionNode"/> instances representing the <paramref name="expressionTree"/>.</returns>
public IExpressionNode ParseTree (Expression expressionTree)
{
ArgumentUtility.CheckNotNull ("expressionTree", expressionTree);
if (expressionTree.Type == typeof (void))
{
throw new NotSupportedException (
string.Format ("Expressions of type void ('{0}') are not supported.", FormattingExpressionTreeVisitor.Format (expressionTree)));
}
var processedExpressionTree = _processor.Process (expressionTree);
return ParseNode (processedExpressionTree, null);
}
/// <summary>
/// Gets the query operator <see cref="MethodCallExpression"/> represented by <paramref name="expression"/>. If <paramref name="expression"/>
/// is already a <see cref="MethodCallExpression"/>, that is the assumed query operator. If <paramref name="expression"/> is a
/// <see cref="MemberExpression"/> and the member's getter is registered with <see cref="NodeTypeProvider"/>, a corresponding
/// <see cref="MethodCallExpression"/> is constructed and returned. Otherwise, <see langword="null" /> is returned.
/// </summary>
/// <param name="expression">The expression to get a query operator expression for.</param>
/// <returns>A <see cref="MethodCallExpression"/> to be parsed as a query operator, or <see langword="null"/> if the expression does not represent
/// a query operator.</returns>
public MethodCallExpression GetQueryOperatorExpression (Expression expression)
{
var methodCallExpression = expression as MethodCallExpression;
if (methodCallExpression != null)
return methodCallExpression;
var memberExpression = expression as MemberExpression;
if (memberExpression != null)
{
var propertyInfo = memberExpression.Member as PropertyInfo;
if (propertyInfo == null)
return null;
#if NETFX_CORE
var getterMethod = propertyInfo.GetMethod;
#else
var getterMethod = propertyInfo.GetGetMethod();
#endif
if (getterMethod == null || !_nodeTypeProvider.IsRegistered (getterMethod))
return null;
return Expression.Call (memberExpression.Expression, getterMethod);
}
var unaryExpression = expression as UnaryExpression;
if (unaryExpression != null)
{
if (unaryExpression.NodeType == ExpressionType.ArrayLength && _nodeTypeProvider.IsRegistered (s_getArrayLengthMethod))
return Expression.Call (unaryExpression.Operand, s_getArrayLengthMethod);
}
return null;
}
private IExpressionNode ParseNode (Expression expression, string associatedIdentifier)
{
if (string.IsNullOrEmpty (associatedIdentifier))
associatedIdentifier = _identifierGenerator.GetUniqueIdentifier ("<generated>_");
var methodCallExpression = GetQueryOperatorExpression(expression);
if (methodCallExpression != null)
return ParseMethodCallExpression (methodCallExpression, associatedIdentifier);
else
return ParseNonQueryOperatorExpression(expression, associatedIdentifier);
}
private IExpressionNode ParseMethodCallExpression (MethodCallExpression methodCallExpression, string associatedIdentifier)
{
string associatedIdentifierForSource = InferAssociatedIdentifierForSource (methodCallExpression);
Expression sourceExpression;
IEnumerable<Expression> arguments;
if (methodCallExpression.Object != null)
{
sourceExpression = methodCallExpression.Object;
arguments = methodCallExpression.Arguments;
}
else
{
sourceExpression = methodCallExpression.Arguments[0];
arguments = methodCallExpression.Arguments.Skip (1);
}
var source = ParseNode (sourceExpression, associatedIdentifierForSource);
return _methodCallExpressionParser.Parse (associatedIdentifier, source, arguments, methodCallExpression);
}
private IExpressionNode ParseNonQueryOperatorExpression (Expression expression, string associatedIdentifier)
{
var preprocessedExpression = expression; //PATCH: SubQueryFindingExpressionTreeVisitor.Process (expression, _nodeTypeProvider);
try
{
// Assertions to ensure the argument exception can only happen because of an unsupported type in expression.
Assertion.IsNotNull (expression);
Assertion.IsFalse (string.IsNullOrEmpty (associatedIdentifier));
return new MainSourceExpressionNode (associatedIdentifier, preprocessedExpression);
}
catch (ArgumentException ex)
{
var message = string.Format (
"Cannot parse expression '{0}' as it has an unsupported type. Only query sources (that is, expressions that implement IEnumerable) "
+ "and query operators can be parsed.",
FormattingExpressionTreeVisitor.Format (preprocessedExpression));
throw new NotSupportedException (message, ex);
}
}
/// <summary>
/// Infers the associated identifier for the source expression node contained in methodCallExpression.Arguments[0]. For example, for the
/// call chain "<c>source.Where (i => i > 5)</c>" (which actually reads "<c>Where (source, i => i > 5</c>"), the identifier "i" is associated
/// with the node generated for "source". If no identifier can be inferred, <see langword="null"/> is returned.
/// </summary>
private string InferAssociatedIdentifierForSource (MethodCallExpression methodCallExpression)
{
var lambdaExpression = GetLambdaArgument (methodCallExpression);
if (lambdaExpression != null && lambdaExpression.Parameters.Count == 1)
return lambdaExpression.Parameters[0].Name;
else
return null;
}
private LambdaExpression GetLambdaArgument (MethodCallExpression methodCallExpression)
{
return methodCallExpression.Arguments
.Select (argument => GetLambdaExpression (argument))
.FirstOrDefault (lambdaExpression => lambdaExpression != null);
}
private LambdaExpression GetLambdaExpression (Expression expression)
{
var lambdaExpression = expression as LambdaExpression;
if (lambdaExpression != null)
return lambdaExpression;
else
{
var unaryExpression = expression as UnaryExpression;
if (unaryExpression != null)
return unaryExpression.Operand as LambdaExpression;
else
return null;
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
#if DEBUG
#define TRACK_DATADESCRIPTOR_IDENTITY
#else
//#define TRACK_DATADESCRIPTOR_IDENTITY
#endif
namespace Microsoft.Zelig.CodeGeneration.IR
{
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Microsoft.Zelig.Runtime.TypeSystem;
public class DataManager
{
[Flags]
public enum Attributes
{
Constant = 0x00000000,
Mutable = 0x00000001,
SuitableForConstantPropagation = 0x00000002,
}
public abstract class DataDescriptor
{
//
// State
//
#if TRACK_DATADESCRIPTOR_IDENTITY
protected static int s_identity;
#endif
public int m_identity;
//--//
protected DataManager m_owner;
protected TypeRepresentation m_context;
protected Attributes m_flags;
protected Abstractions.PlacementRequirements m_placementRequirements;
protected DataDescriptor m_nestingDd;
protected InstanceFieldRepresentation m_nestingFd;
protected int m_nestingPos;
//
// Constructor Methods
//
protected DataDescriptor() // Default constructor required by TypeSystemSerializer.
{
}
protected DataDescriptor( DataManager owner ,
TypeRepresentation context ,
Attributes flags ,
Abstractions.PlacementRequirements pr )
{
#if TRACK_DATADESCRIPTOR_IDENTITY
m_identity = s_identity++;
#endif
m_owner = owner;
m_context = context;
m_flags = flags;
m_placementRequirements = pr;
}
//
// Helper Methods
//
internal void SetNesting( DataDescriptor nestingDd ,
InstanceFieldRepresentation nestingFd ,
int nestingPos )
{
m_nestingDd = nestingDd;
m_nestingFd = nestingFd;
m_nestingPos = nestingPos;
}
protected void ApplyTransformationInner( TransformationContextForCodeTransformation context )
{
context.Transform ( ref m_owner );
context.Transform ( ref m_context );
context.Transform ( ref m_flags );
context.Transform ( ref m_placementRequirements );
context.TransformGeneric( ref m_nestingDd );
context.Transform ( ref m_nestingFd );
context.Transform ( ref m_nestingPos );
}
//--//
internal virtual void IncludeExtraTypes( TypeSystem.Reachability reachability ,
CompilationSteps.PhaseDriver phase )
{
RefreshValues( phase );
reachability.ExpandPending( m_context );
if(m_context is ReferenceTypeRepresentation)
{
object valVt = m_owner.GetObjectDescriptor( m_context.VirtualTable );
reachability.ExpandPending( valVt );
}
}
internal abstract void Reduce( GrowOnlySet< DataDescriptor > visited ,
TypeSystem.Reachability reachability ,
bool fApply );
internal abstract void RefreshValues( CompilationSteps.PhaseDriver phase );
internal abstract void Write( ImageBuilders.SequentialRegion region );
public abstract object GetDataAtOffset( FieldRepresentation[] accessPath ,
int accessPathIndex ,
int offset );
//--//
protected void WriteHeader( ImageBuilders.SequentialRegion region ,
TypeRepresentation context )
{
if(context is ValueTypeRepresentation)
{
//
// Value types don't have headers.
//
return;
}
WellKnownTypes wkt = m_owner.m_typeSystem.WellKnownTypes;
TypeRepresentation tdHeader = wkt.Microsoft_Zelig_Runtime_ObjectHeader;
if(tdHeader != null)
{
WellKnownFields wkf = m_owner.m_typeSystem.WellKnownFields;
ImageBuilders.SequentialRegion.Section sec = region.GetSectionOfFixedSize( tdHeader.Size );
FieldRepresentation fd;
region.PointerOffset = region.Position;
fd = wkf.ObjectHeader_VirtualTable;
if(fd != null)
{
DataManager.DataDescriptor vTable = (DataManager.DataDescriptor)m_owner.GetObjectDescriptor( context.VirtualTable );
sec.Offset = (uint)fd.Offset;
sec.AddImageAnnotation( fd.FieldType.SizeOfHoldingVariable, fd );
sec.WritePointerToDataDescriptor( vTable );
}
fd = wkf.ObjectHeader_MultiUseWord;
if(fd != null)
{
sec.Offset = (uint)fd.Offset;
sec.AddImageAnnotation( fd.FieldType.SizeOfHoldingVariable, fd );
Runtime.ObjectHeader.GarbageCollectorFlags flags;
if(this.IsMutable)
{
flags = Runtime.ObjectHeader.GarbageCollectorFlags.UnreclaimableObject;
}
else
{
flags = Runtime.ObjectHeader.GarbageCollectorFlags.ReadOnlyObject;
}
sec.Write( (uint)flags );
}
}
}
//
// Access Methods
//
public TypeRepresentation Context
{
get
{
return m_context;
}
}
public DataManager Owner
{
get
{
return m_owner;
}
}
public bool IsMutable
{
get
{
return (m_flags & Attributes.Mutable) != 0;
}
}
public bool CanPropagate
{
get
{
return (m_flags & Attributes.SuitableForConstantPropagation) != 0;
}
}
public DataDescriptor Nesting
{
get
{
return m_nestingDd;
}
}
public InstanceFieldRepresentation NestingField
{
get
{
return m_nestingFd;
}
}
public int NestingIndex
{
get
{
return m_nestingPos;
}
}
public Abstractions.PlacementRequirements PlacementRequirements
{
get
{
return m_placementRequirements;
}
set
{
m_placementRequirements = value;
}
}
//
// Debug Methods
//
public override string ToString()
{
return ToString( false );
}
internal string ToStringVerbose()
{
return ToString( true );
}
protected abstract string ToString( bool fVerbose );
}
//--//--//--//--//--//--//--//--//--//
public class ObjectDescriptor : DataDescriptor
{
//
// State
//
private object m_source;
private GrowOnlyHashTable< InstanceFieldRepresentation, object > m_values;
//
// Constructor Methods
//
private ObjectDescriptor() // Default constructor required by TypeSystemSerializer.
{
m_values = HashTableFactory.New< InstanceFieldRepresentation, object >();
}
internal ObjectDescriptor( DataManager owner ,
TypeRepresentation context ,
Attributes flags ,
Abstractions.PlacementRequirements pr ,
object source ) : base( owner, context, flags, pr )
{
m_source = source;
m_values = HashTableFactory.New< InstanceFieldRepresentation, object >();
}
//
// Helper Methods
//
public void ApplyTransformation( TransformationContextForCodeTransformation context )
{
context.Push( this );
ApplyTransformationInner( context );
context.Transform( ref m_source );
context.Transform( ref m_values );
context.Pop();
}
//--//
internal override void IncludeExtraTypes( TypeSystem.Reachability reachability ,
CompilationSteps.PhaseDriver phase )
{
base.IncludeExtraTypes( reachability, phase );
if(m_source != null)
{
reachability.ExpandPending( m_source );
}
foreach(InstanceFieldRepresentation fd in m_values.Keys)
{
object val = m_values[fd];
if(val != null && reachability.Contains( fd ))
{
if(val is DataDescriptor)
{
reachability.ExpandPending( val );
}
}
}
}
internal override void Reduce( GrowOnlySet< DataDescriptor > visited ,
TypeSystem.Reachability reachability ,
bool fApply )
{
if(visited.Insert( this ) == false)
{
CHECKS.ASSERT( reachability.Contains( m_context ), "The type of {0} is not included in the globalReachabilitySet: {1}", this, m_context );
GrowOnlyHashTable< InstanceFieldRepresentation, object > valuesNew = m_values.CloneSettings();
foreach(InstanceFieldRepresentation fd in m_values.Keys)
{
if(reachability.Contains( fd ))
{
object val = m_values[fd];
if(val == null || reachability.IsProhibited( val ) == false)
{
valuesNew[fd] = val;
if(val is DataDescriptor)
{
DataDescriptor dd = (DataDescriptor)val;
dd.Reduce( visited, reachability, fApply );
}
}
}
}
if(fApply)
{
m_values = valuesNew;
}
}
}
//--//
internal void UpdateSource( object source ,
CompilationSteps.PhaseDriver phase )
{
m_source = source;
RefreshValues( phase );
}
internal override void RefreshValues( CompilationSteps.PhaseDriver phase )
{
if(m_source != null)
{
const System.Reflection.BindingFlags bindingFlags = System.Reflection.BindingFlags.DeclaredOnly |
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance;
Type typeSrc = m_source.GetType();
TypeRepresentation typeDst = m_context;
TypeSystemForCodeTransformation typeSystem = m_owner.m_typeSystem;
WellKnownTypes wkt = typeSystem.WellKnownTypes;
WellKnownFields wkf = typeSystem.WellKnownFields;
FieldRepresentation fdStringImpl_FirstChar = wkf.StringImpl_FirstChar;
FieldRepresentation fdVTable_Type = wkf.VTable_Type;
GrowOnlyHashTable< InstanceFieldRepresentation, object > values = m_values;
m_values = values.CloneSettingsAndSize();
while(typeDst != null)
{
foreach(FieldRepresentation fdIn in typeDst.Fields)
{
InstanceFieldRepresentation fd = fdIn as InstanceFieldRepresentation;
if(fd != null)
{
object valOld;
values.TryGetValue( fd, out valOld );
if(fd == fdStringImpl_FirstChar)
{
//
// Special case for strings: store the whole content as an array of chars.
//
Set( fd, ((string)m_source).ToCharArray() );
}
else if(fd == wkf.StringImpl_ArrayLength)
{
Set(fd, ((string)m_source).ToCharArray().Length);
}
else if(fd == wkf.StringImpl_StringLength)
{
Set(fd, ((string)m_source).Length);
}
else if(fd == fdVTable_Type)
{
//
// Special case for virtual tables: create a TypeImpl on the fly.
//
if(valOld == null)
{
TypeRepresentation valTd = wkt.Microsoft_Zelig_Runtime_RuntimeTypeImpl;
if(valTd != null)
{
ObjectDescriptor od = m_owner.BuildObjectDescriptor( valTd, Attributes.Constant | Attributes.SuitableForConstantPropagation, null );
InstanceFieldRepresentation fdTarget = (InstanceFieldRepresentation)wkf.RuntimeTypeImpl_m_handle;
VTable vTable = (VTable)m_source;
ObjectDescriptor odSub = typeSystem.CreateDescriptorForRuntimeHandle( vTable.TypeInfo );
odSub.SetNesting( od, fdTarget, -1 );
odSub.RefreshValues( phase );
od.Set( fdTarget, odSub );
valOld = od;
}
}
Set( fd, valOld );
}
else
{
System.Reflection.FieldInfo fi = typeSrc.GetField( fd.Name, bindingFlags );
if(fi != null)
{
object val = fi.GetValue( m_source );
ObjectDescriptor oldOD = valOld as ObjectDescriptor;
if(fi.FieldType.IsValueType && oldOD != null)
{
oldOD.UpdateSource( val, phase );
Set( fd, oldOD );
}
else
{
Set( fd, m_owner.ConvertToObjectDescriptor( fd.FieldType, m_flags, m_placementRequirements, val, this, fd, -1, phase ) );
}
}
else
{
throw TypeConsistencyErrorException.Create( "Cannot create ObjectDescriptor, field '{0}' is missing in source object", fd );
}
}
}
}
typeSrc = typeSrc.BaseType;
typeDst = typeDst.Extends;
}
}
}
//--//
internal override void Write( ImageBuilders.SequentialRegion region )
{
WriteHeader( region, m_context );
string text = m_source as string;
int arrayLength = text != null ? (text.Length+1) : 0;
VTable vtable = m_context.VirtualTable;
ImageBuilders.SequentialRegion.Section sec = region.GetSectionOfFixedSize( vtable.BaseSize + vtable.ElementSize * (uint)arrayLength );
WriteFields( sec, vtable );
}
internal void WriteFields( ImageBuilders.SequentialRegion.Section sec ,
VTable vtable )
{
WellKnownFields wkf = m_owner.m_typeSystem.WellKnownFields;
FieldRepresentation fdFirstChar = wkf.StringImpl_FirstChar;
FieldRepresentation fdCodePointer_Target = wkf.CodePointer_Target;
foreach(InstanceFieldRepresentation fd in m_values.Keys)
{
object val = m_values[fd];
sec.Offset = (uint)fd.Offset;
sec.AddImageAnnotation( fd.FieldType.SizeOfHoldingVariable, fd );
if(fd == fdFirstChar)
{
//
// Special case for strings: store the whole content as an array of chars.
//
sec.Write( (char[])val );
}
else if(fd == fdCodePointer_Target)
{
//
// Special case for code pointers: substitute with actual code pointers.
//
IntPtr id = (IntPtr)val;
object ptr = m_owner.GetCodePointerFromUniqueID( id );
if(ptr is MethodRepresentation)
{
MethodRepresentation md = (MethodRepresentation)ptr;
ControlFlowGraphStateForCodeTransformation cfg = TypeSystemForCodeTransformation.GetCodeForMethod( md );
if(cfg == null)
{
sec.WriteNullPointer();
}
else
{
sec.WritePointerToBasicBlock( cfg.EntryBasicBlock );
}
}
else if(ptr is ExceptionHandlerBasicBlock)
{
ExceptionHandlerBasicBlock ehBB = (ExceptionHandlerBasicBlock)ptr;
sec.WritePointerToBasicBlock( ehBB );
}
else
{
sec.Write( id );
}
}
else if(val == null)
{
sec.WriteNullPointer();
}
else if(val is DataDescriptor)
{
DataDescriptor dd = (DataDescriptor)val;
if(dd.Nesting != null)
{
ObjectDescriptor od = (ObjectDescriptor)dd;
od.WriteFields( sec.GetSubSection( dd.Context.Size ), dd.Context.VirtualTable );
}
else
{
sec.WritePointerToDataDescriptor( dd );
}
}
else if(fd.FieldType is ScalarTypeRepresentation)
{
if(sec.WriteGeneric( val ) == false)
{
throw TypeConsistencyErrorException.Create( "Can't write scalar value {0}", val );
}
}
else
{
throw TypeConsistencyErrorException.Create( "Don't know how to write {0}", val );
}
}
}
//--//
public override object GetDataAtOffset( FieldRepresentation[] accessPath ,
int accessPathIndex ,
int offset )
{
if(!this.CanPropagate)
{
return null;
}
lock(TypeSystemForCodeTransformation.Lock)
{
if(accessPath != null && accessPathIndex < accessPath.Length)
{
var fd = (InstanceFieldRepresentation)accessPath[accessPathIndex++];
object val;
if(m_values.TryGetValue( fd, out val ) == false)
{
return null;
}
offset -= fd.Offset;
if(accessPathIndex == accessPath.Length)
{
return val;
}
var dd = val as DataDescriptor;
if(dd == null)
{
return null;
}
return dd.GetDataAtOffset( accessPath, accessPathIndex, offset );
}
foreach(InstanceFieldRepresentation fd in m_values.Keys)
{
if(fd.Offset == offset)
{
return m_values[fd];
}
}
return null;
}
}
//--//
public void ConvertAndSet( InstanceFieldRepresentation fd ,
Attributes flags ,
Abstractions.PlacementRequirements pr ,
object val )
{
lock(TypeSystemForCodeTransformation.Lock)
{
Set( fd, m_owner.ConvertToObjectDescriptor( fd.FieldType, flags, pr, val ) );
}
}
public void Set( InstanceFieldRepresentation fd ,
object val )
{
lock(TypeSystemForCodeTransformation.Lock)
{
m_values[fd] = val;
}
}
public object Get( InstanceFieldRepresentation fd )
{
lock(TypeSystemForCodeTransformation.Lock)
{
object res;
m_values.TryGetValue( fd, out res );
return res;
}
}
public bool Has( InstanceFieldRepresentation fd )
{
lock(TypeSystemForCodeTransformation.Lock)
{
return m_values.ContainsKey( fd );
}
}
//--//
//
// Access Methods
//
public object Source
{
get
{
return m_source;
}
}
public GrowOnlyHashTable< InstanceFieldRepresentation, object > Values
{
get
{
return m_values;
}
}
//
// Debug Methods
//
protected override string ToString( bool fVerbose )
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendFormat( "$Object({0}", m_context.FullName );
if(m_source != null)
{
sb.AppendFormat( " => {0}", m_source );
}
if(fVerbose)
{
bool fFirst = true;
foreach(InstanceFieldRepresentation fd in m_values.Keys)
{
object val = m_values[fd];
if(val != null)
{
if(fFirst)
{
sb.Append( " -> " );
fFirst = false;
}
else
{
sb.Append( ", " );
}
if(val is DataDescriptor)
{
DataDescriptor dd = (DataDescriptor)val;
val = dd.Context;
}
sb.AppendFormat( "{0}::{1} = {2}", fd.OwnerType.FullNameWithAbbreviation, fd.Name, val );
}
}
}
sb.Append( ")" );
if(m_nestingDd != null)
{
sb.AppendFormat( " => {0}", fVerbose ? m_nestingDd.ToStringVerbose() : m_nestingDd.ToString() );
}
return sb.ToString();
}
}
//--//--//--//--//--//--//--//--//--//
public class ArrayDescriptor : DataDescriptor
{
//
// State
//
private Array m_source;
private int m_length;
private object[] m_values;
//
// Constructor Methods
//
internal ArrayDescriptor( DataManager owner ,
ArrayReferenceTypeRepresentation context ,
Attributes flags ,
Abstractions.PlacementRequirements pr ,
Array source ,
int len ) : base( owner, context, flags, pr )
{
m_source = source;
m_length = len;
if(source == null || source.GetType().GetElementType().IsPrimitive == false)
{
m_values = new object[len];
}
}
//
// Helper Methods
//
public void ApplyTransformation( TransformationContextForCodeTransformation context )
{
context.Push( this );
ApplyTransformationInner( context );
context.TransformGeneric( ref m_source );
context.Transform ( ref m_values );
context.Pop();
}
//--//
internal override void IncludeExtraTypes( TypeSystem.Reachability reachability ,
CompilationSteps.PhaseDriver phase )
{
base.IncludeExtraTypes( reachability, phase );
if(m_values != null)
{
foreach(object obj in m_values)
{
if(obj is DataDescriptor)
{
DataDescriptor dd = (DataDescriptor)obj;
if(reachability.Contains( dd.Context ))
{
reachability.ExpandPending( obj );
}
}
}
}
}
internal override void Reduce( GrowOnlySet< DataDescriptor > visited ,
TypeSystem.Reachability reachability ,
bool fApply )
{
if(visited.Insert( this ) == false)
{
CHECKS.ASSERT( reachability.Contains( m_context ), "The type of {0} is not included in the globalReachabilitySet: {1}", this, m_context );
if(m_values != null)
{
foreach(object val in m_values)
{
if(val is DataDescriptor)
{
DataDescriptor dd = (DataDescriptor)val;
dd.Reduce( visited, reachability, fApply );
}
}
}
}
}
//--//
internal override void RefreshValues( CompilationSteps.PhaseDriver phase )
{
if(m_source != null && m_values != null)
{
TypeRepresentation typeDst = m_context.UnderlyingType.ContainedType;
for(int i = 0; i < m_length; i++)
{
object val = m_source.GetValue( i );
ObjectDescriptor oldOD = Get( i ) as ObjectDescriptor;
if(typeDst is ValueTypeRepresentation && oldOD != null)
{
oldOD.UpdateSource( val, phase );
}
else
{
Set( i, m_owner.ConvertToObjectDescriptor( typeDst, m_flags, m_placementRequirements, val, this, null, i, phase ) );
}
}
}
}
//--//
internal override void Write( ImageBuilders.SequentialRegion region )
{
WriteHeader( region, m_context );
uint arrayLength = (uint)m_length;
VTable vtable = m_context.VirtualTable;
ImageBuilders.SequentialRegion.Section sec = region.GetSectionOfFixedSize( vtable.BaseSize + vtable.ElementSize * arrayLength );
FieldRepresentation fd = m_owner.m_typeSystem.WellKnownFields.ArrayImpl_m_numElements;
if(fd != null)
{
sec.Offset = (uint)fd.Offset;
sec.AddImageAnnotation( fd.FieldType.SizeOfHoldingVariable, fd );
sec.Write( arrayLength );
}
if(region.PlacementRequirements.ContentsUninitialized)
{
region.PayloadCutoff = sec.Position;
}
else
{
//
// Special case for common scalar arrays.
//
if(m_values == null)
{
if(m_source is byte[])
{
sec.Write( (byte[])m_source );
return;
}
if(m_source is char[])
{
sec.Write( (char[])m_source );
return;
}
if(m_source is int[])
{
sec.Write( (int[])m_source );
return;
}
if(m_source is uint[])
{
sec.Write( (uint[])m_source );
return;
}
}
for(uint i = 0; i < arrayLength; i++)
{
object val = GetDirect( (int)i );
sec.Offset = vtable.BaseSize + vtable.ElementSize * i;
if(val == null)
{
sec.WriteNullPointer();
}
else if(val is DataDescriptor)
{
DataDescriptor dd = (DataDescriptor)val;
if(dd.Nesting != null)
{
ObjectDescriptor od = (ObjectDescriptor)dd;
od.WriteFields( sec.GetSubSection( vtable.ElementSize ), dd.Context.VirtualTable );
}
else
{
sec.WritePointerToDataDescriptor( dd );
}
}
else if(m_context.ContainedType is ScalarTypeRepresentation)
{
if(sec.WriteGeneric( val ) == false)
{
throw TypeConsistencyErrorException.Create( "Can't write scalar value {0}", val );
}
}
else
{
throw TypeConsistencyErrorException.Create( "Don't know how to write {0}", val );
}
}
}
}
//--//
public override object GetDataAtOffset( FieldRepresentation[] accessPath ,
int accessPathIndex ,
int offset )
{
if(!this.CanPropagate)
{
return null;
}
lock(TypeSystemForCodeTransformation.Lock)
{
uint arrayLength = (uint)m_length;
if(offset == 0)
{
return arrayLength;
}
else
{
VTable vtable = m_context.VirtualTable;
offset -= (int)vtable.BaseSize;
offset /= (int)vtable.ElementSize;
if(offset >= 0 && offset < m_length)
{
return GetDirect( offset );
}
return null;
}
}
}
//--//
public void Set( int pos ,
object val )
{
lock(TypeSystemForCodeTransformation.Lock)
{
m_values[pos] = val;
}
}
public object Get( int pos )
{
lock(TypeSystemForCodeTransformation.Lock)
{
return GetDirect( pos );
}
}
private object GetDirect( int pos )
{
return m_values != null ? m_values[pos] : m_source.GetValue( pos );
}
//--//
//
// Access Methods
//
public Array Source
{
get
{
return m_source;
}
}
//ZELIG2LLVM: Added Length public getter
public int Length
{
get
{
return m_length;
}
}
public object[] Values
{
get
{
return m_values;
}
}
//--//
//
// Debug Methods
//
protected override string ToString( bool fVerbose )
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendFormat( "$Array({0}", m_context.FullName );
if(m_source != null)
{
sb.AppendFormat( " => {0}", m_source );
}
if(fVerbose)
{
sb.Append( " -> [" );
for(int i = 0; i < m_length; i++)
{
object val = GetDirect( i );
if(val != null)
{
if(i != 0)
{
sb.Append( ", " );
}
if(val is DataDescriptor)
{
DataDescriptor dd = (DataDescriptor)val;
val = dd.Context;
}
sb.AppendFormat( "{0} = {1}", i, val );
}
}
sb.Append( "]" );
}
sb.Append( ")" );
if(m_nestingDd != null)
{
sb.AppendFormat( " => {0}", fVerbose ? m_nestingDd.ToStringVerbose() : m_nestingDd.ToString() );
}
return sb.ToString();
}
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//
// State
//
TypeSystemForCodeTransformation m_typeSystem;
GrowOnlyHashTable< object, DataDescriptor > m_data;
GrowOnlyHashTable< object, int > m_codePointers;
GrowOnlyHashTable< int , object > m_codePointersReverse; // Not persisted, rebuilt if needed.
int m_nextCodePointerId;
//
// Constructor Methods
//
private DataManager() // Default constructor required by TypeSystemSerializer.
{
m_data = HashTableFactory.NewWithWeakEquality < object, DataDescriptor >();
m_codePointers = HashTableFactory.NewWithReferenceEquality< object, int >();
}
internal DataManager( TypeSystemForCodeTransformation typeSystem ) : this()
{
m_typeSystem = typeSystem;
}
//
// Helper Methods
//
public void ApplyTransformation( TransformationContextForCodeTransformation context )
{
context.Push( this );
context.Transform( ref m_typeSystem );
context.Transform( ref m_data );
context.Transform( ref m_codePointers );
context.Transform( ref m_nextCodePointerId );
context.Pop();
}
//--//
internal void Reduce( TypeSystem.Reachability reachability ,
bool fApply )
{
GrowOnlyHashTable< object, DataDescriptor > dataNew = m_data.CloneSettings();
GrowOnlySet< DataDescriptor > visited = SetFactory.NewWithReferenceEquality< DataDescriptor >();
foreach(object obj in m_data.Keys)
{
DataDescriptor dd = m_data[obj];
if(reachability.IsProhibited( obj ) == false)
{
if(reachability.Contains( dd ))
{
dd.Reduce( visited, reachability, fApply );
dataNew[obj] = dd;
dd = null;
}
}
if(dd != null)
{
CHECKS.ASSERT( reachability.Contains( dd ) == false, "{0} cannot belong both to globalReachabilitySet and useProhibited", dd );
reachability.ExpandProhibition( dd );
}
}
if(fApply)
{
m_data = dataNew;
}
//--//
if(fApply)
{
GrowOnlyHashTable< object, int > codePointers = m_codePointers.CloneSettings();
foreach(object obj in m_codePointers.Keys)
{
if(reachability.IsProhibited( obj ) == false)
{
codePointers[obj] = m_codePointers[obj];
}
}
m_codePointers = codePointers;
m_codePointersReverse = null;
}
}
//--//
public object GetObjectDescriptor( object obj )
{
if(obj == null)
{
return null;
}
else if(obj is DataDescriptor)
{
return (DataDescriptor)obj;
}
else if(obj.GetType().IsPrimitive)
{
return obj;
}
else if(obj is Enum)
{
return obj;
}
else
{
lock(TypeSystemForCodeTransformation.Lock) // It's called from multiple threads during parallel phase executions.
{
DataDescriptor res;
if(m_data.TryGetValue( obj, out res ))
{
return res;
}
}
return null;
}
}
internal object ConvertToObjectDescriptor( object value ,
out TypeRepresentation tdTarget )
{
tdTarget = m_typeSystem.GetTypeRepresentationFromObject( value );
return ConvertToObjectDescriptor( tdTarget, DataManager.Attributes.Constant | DataManager.Attributes.SuitableForConstantPropagation, null, value );
}
internal object ConvertToObjectDescriptor( TypeRepresentation td ,
Attributes flags ,
Abstractions.PlacementRequirements pr ,
object obj )
{
return ConvertToObjectDescriptor( td, flags, pr, obj, null, null, 0, null );
}
private object ConvertToObjectDescriptor( TypeRepresentation td ,
Attributes flags ,
Abstractions.PlacementRequirements pr ,
object obj ,
DataDescriptor nestingDd ,
InstanceFieldRepresentation nestingFd ,
int nestingPos ,
CompilationSteps.PhaseDriver phase )
{
if(obj == null)
{
return null;
}
else if(obj is DataDescriptor)
{
return (DataDescriptor)obj;
}
else if(obj.GetType().IsPrimitive)
{
return obj;
}
else if(obj is Enum)
{
return obj;
}
else
{
TypeRepresentation tdObj = m_typeSystem.GetTypeRepresentationFromType( obj.GetType() );
if(td.CanBeAssignedFrom( tdObj, null ) == false)
{
throw TypeConsistencyErrorException.Create( "Cannot create a DataDescriptor of type {0} with a value of type {1}", td, tdObj );
}
lock(TypeSystemForCodeTransformation.Lock) // It's called from multiple threads during parallel phase executions.
{
DataDescriptor res;
if(obj is ValueType || m_data.TryGetValue( obj, out res ) == false)
{
if(nestingFd != null)
{
bool fSkip = false;
WellKnownFields wkf = m_typeSystem.WellKnownFields;
if(CompilationSteps.PhaseDriver.CompareOrder( phase, typeof(CompilationSteps.Phases.ReduceTypeSystem) ) <= 0)
{
if(nestingFd == wkf.TypeRepresentation_MethodTable ||
nestingFd == wkf.TypeRepresentation_InterfaceMethodTables ||
nestingFd == wkf.VTable_MethodPointers ||
nestingFd == wkf.VTable_InterfaceMap )
{
fSkip = true;
}
}
// Note that we only want to skip GCInfo before the LayoutTypes phase, but not in LayoutType phase,
// so GCInfo will be corrected during the call to RefreshValues as part of the LayoutTypes phase.
if (CompilationSteps.PhaseDriver.CompareOrder( phase, typeof(CompilationSteps.Phases.LayoutTypes) ) < 0)
{
if(nestingFd == wkf.VTable_GCInfo)
{
fSkip = true;
}
}
if(fSkip)
{
//
// Don't generate a DataDescriptor for these items, they will be regenerated later.
//
return null;
}
}
if(obj is Array)
{
Array array = (Array)obj;
res = new ArrayDescriptor( this, (ArrayReferenceTypeRepresentation)tdObj, flags, pr, array, array.Length );
}
else
{
res = new ObjectDescriptor( this, tdObj, flags, pr, obj );
}
if(obj is ValueType)
{
res.SetNesting( nestingDd, nestingFd, nestingPos );
res.RefreshValues( phase );
}
else
{
m_data[obj] = res;
}
InstantiateVTable( res );
}
return res;
}
}
}
//--//
private object ConvertVirtualTable( VTable vTable )
{
TypeRepresentation tdVT = m_typeSystem.GetTypeRepresentationFromObject( vTable );
return ConvertToObjectDescriptor( tdVT, DataManager.Attributes.Constant | DataManager.Attributes.SuitableForConstantPropagation, null, vTable );
}
private void InstantiateVTable( DataDescriptor dd )
{
TypeRepresentation td = dd.Context;
if(td is ReferenceTypeRepresentation)
{
VTable vt = td.VirtualTable;
if(vt != null)
{
ConvertVirtualTable( vt );
}
}
}
internal ObjectDescriptor BuildObjectDescriptor( TypeRepresentation td ,
DataManager.Attributes flags ,
Abstractions.PlacementRequirements pr )
{
CHECKS.ASSERT( !(td is ArrayReferenceTypeRepresentation ), "Expecting an object, got an array: {0}", td );
CHECKS.ASSERT( !(td is AbstractReferenceTypeRepresentation), "Cannot instantiate abstract type: {0}", td );
lock(TypeSystemForCodeTransformation.Lock) // It's called from multiple threads during parallel phase executions.
{
ObjectDescriptor od = new ObjectDescriptor( this, td, flags, pr, null );
m_data[od] = od;
InstantiateVTable( od );
return od;
}
}
internal ArrayDescriptor BuildArrayDescriptor( ArrayReferenceTypeRepresentation td ,
DataManager.Attributes flags ,
Abstractions.PlacementRequirements pr ,
Array array ,
int len )
{
CHECKS.ASSERT( (td is ArrayReferenceTypeRepresentation), "Expecting an array, got an object: {0}", td );
ArrayDescriptor ad;
lock(TypeSystemForCodeTransformation.Lock) // It's called from multiple threads during parallel phase executions.
{
ad = new ArrayDescriptor( this, td, flags, pr, array, len );
m_data[ad] = ad;
InstantiateVTable( ad );
}
if(array == null)
{
var tdElement = td.ContainedType;
if(tdElement is ValueTypeRepresentation)
{
if(!(tdElement is ScalarTypeRepresentation))
{
for(int pos = 0; pos < len; pos++)
{
var od = BuildObjectDescriptor( tdElement, flags, pr );
od.SetNesting( ad, null, pos );
ad.Set( pos, od );
}
}
}
}
return ad;
}
//--//
internal CodePointer CreateCodePointer( object obj )
{
CodePointer res;
int id;
lock(TypeSystemForCodeTransformation.Lock) // It's called from multiple threads during parallel phase executions.
{
if(m_codePointers.TryGetValue( obj, out id ) == false)
{
id = m_nextCodePointerId++;
//
// To distinguish between real method pointers and placeholders,
// we use a non-word-aligned value, which is illegal for real methods.
//
id = (id * 2 + 1);
m_codePointers[obj] = id;
if(m_codePointersReverse != null)
{
m_codePointersReverse[id] = obj;
}
}
}
//
// To distinguish between real method pointers and placeholders,
// we use a non-word-aligned value, which is illegal for real methods.
//
res.Target = new IntPtr( id );
return res;
}
internal object GetCodePointerFromUniqueID( IntPtr val )
{
int id = val.ToInt32();
if((id & 1) != 0)
{
lock(TypeSystemForCodeTransformation.Lock) // It's called from multiple threads during parallel phase executions.
{
if(m_codePointersReverse == null)
{
m_codePointersReverse = HashTableFactory.New< int, object >();
object[] keys = m_codePointers.KeysToArray ();
int[] values = m_codePointers.ValuesToArray();
for(int i = 0; i < keys.Length; i++)
{
m_codePointersReverse[ values[i] ] = keys[i];
}
}
object obj;
if(m_codePointersReverse.TryGetValue( id, out obj ))
{
return obj;
}
}
}
return null;
}
internal void RefreshValues( CompilationSteps.PhaseDriver phase )
{
GrowOnlyHashTable< object, DataDescriptor > dataIncr = m_data.CloneSettings();
//
// Because the process of population can create new DataDescriptors, we need to keep iterating.
//
while(true)
{
object[] keys = m_data.KeysToArray();
bool fDone = true;
foreach(object obj in keys)
{
DataDescriptor dd = m_data[obj];
if(dataIncr.Update( obj, dd ) == false)
{
dd.RefreshValues( phase );
fDone = false;
}
}
if(fDone) break;
}
}
}
}
| |
namespace Macabresoft.Macabre2D.Framework;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Macabresoft.Core;
/// <summary>
/// The FilterSortCollection class provides efficient, reusable sorting and filtering based on a
/// configurable sort comparer, filter predicate, and associate change events. I stole all of
/// this code from the MonoGame source code. Theirs is private to Game, I wanted to reuse this
/// all over the place.
/// </summary>
public sealed class FilterSortCollection<T> : ICollection<T>, IReadOnlyCollection<T> where T : INotifyPropertyChanged {
private static readonly Comparison<int> RemoveJournalSortComparison =
(x, y) => Comparer<int>.Default.Compare(y, x);
private readonly List<AddJournalEntry> _addJournal = new();
private readonly Comparison<AddJournalEntry> _addJournalSortComparison;
private readonly List<T> _cachedFilteredItems = new();
private readonly Predicate<T> _filter;
private readonly string _filterPropertyName;
private readonly List<T> _items = new();
private readonly object _lock = new();
private readonly List<int> _removeJournal = new();
private readonly Comparison<T> _sort;
private readonly string _sortPropertyName;
private bool _shouldRebuildCache = true;
/// <summary>
/// Occurs when [collection changed].
/// </summary>
public event EventHandler<CollectionChangedEventArgs<T>>? CollectionChanged;
/// <summary>
/// Initializes a new instance of the <see cref="FilterSortCollection{T}" /> class.
/// </summary>
/// <param name="filter">The filter.</param>
/// <param name="filterPropertyName">Name of the filter property.</param>
/// <param name="sort">The sort.</param>
/// <param name="sortPropertName">Name of the sort propert.</param>
public FilterSortCollection(
Predicate<T> filter,
string filterPropertyName,
Comparison<T> sort,
string sortPropertName) {
this._filter = filter;
this._filterPropertyName = filterPropertyName;
this._sort = sort;
this._sortPropertyName = sortPropertName;
this._addJournalSortComparison = this.CompareAddJournalEntry;
}
/// <summary>
/// Gets the number of elements contained in the
/// <see
/// cref="T:System.Collections.Generic.ICollection`1" />
/// .
/// </summary>
public int Count => this._cachedFilteredItems.Count;
/// <summary>
/// Gets a value indicating whether the
/// <see
/// cref="T:System.Collections.Generic.ICollection`1" />
/// is read-only.
/// </summary>
public bool IsReadOnly => false;
/// <summary>
/// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1" />.
/// </summary>
/// <param name="item">
/// The object to add to the <see cref="T:System.Collections.Generic.ICollection`1" />.
/// </param>
public void Add(T item) {
lock (this._lock) {
this._addJournal.Add(new AddJournalEntry(this._addJournal.Count, item));
this.InvalidateCache();
this.CollectionChanged.SafeInvoke(this, new CollectionChangedEventArgs<T>(true, item));
}
}
/// <summary>
/// Adds the specified item. If the item is not the correct time, it gets ignored.
/// </summary>
/// <param name="item">The item.</param>
public void Add(object item) {
if (item is T x) {
this.Add(x);
}
}
/// <summary>
/// Adds the items.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(IEnumerable<T> items) {
lock (this._lock) {
foreach (var item in items) {
this._addJournal.Add(new AddJournalEntry(this._addJournal.Count, item));
}
this.InvalidateCache();
this.CollectionChanged.SafeInvoke(this, new CollectionChangedEventArgs<T>(true, items));
}
}
/// <summary>
/// Adds the items.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(IEnumerable<object> items) {
var castedItems = items.OfType<T>().ToList();
if (castedItems.Any()) {
this.AddRange(castedItems);
}
}
/// <summary>
/// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1" />.
/// </summary>
public void Clear() {
lock (this._lock) {
for (var i = 0; i < this._items.Count; ++i) {
this.UnsubscribeFromItemEvents(this._items[i]);
}
var items = this._items;
this._addJournal.Clear();
this._removeJournal.Clear();
this._items.Clear();
this.InvalidateCache();
this.CollectionChanged.SafeInvoke(this, new CollectionChangedEventArgs<T>(false, items));
}
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1" />
/// contains a specific value.
/// </summary>
/// <param name="item">
/// The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1" />.
/// </param>
/// <returns>
/// true if <paramref name="item" /> is found in the
/// <see
/// cref="T:System.Collections.Generic.ICollection`1" />
/// ; otherwise, false.
/// </returns>
public bool Contains(T item) {
return this._items.Contains(item);
}
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1" /> to
/// an <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index.
/// </summary>
/// <param name="array">
/// The one-dimensional <see cref="T:System.Array" /> that is the destination of the
/// elements copied from <see cref="T:System.Collections.Generic.ICollection`1" />. The
/// <see
/// cref="T:System.Array" />
/// must have zero-based indexing.
/// </param>
/// <param name="arrayIndex">
/// The zero-based index in <paramref name="array" /> at which copying begins.
/// </param>
public void CopyTo(T[] array, int arrayIndex) {
this._items.CopyTo(array, arrayIndex);
}
/// <summary>
/// Iterates through each filtered item.
/// </summary>
/// <param name="action">The action.</param>
public void ForEachFilteredItem(Action<T> action) {
this.RebuildCache();
for (var i = 0; i < this._cachedFilteredItems.Count; i++) {
action(this._cachedFilteredItems[i]);
}
// If the cache was invalidated as a result of processing items, now is a good time to
// clear it and give the GC (more of) a chance to do its thing.
if (this._shouldRebuildCache) {
this._cachedFilteredItems.Clear();
}
}
/// <summary>
/// Iterates through each filtered item.
/// </summary>
/// <typeparam name="TUserData">The type of the user data.</typeparam>
/// <param name="action">The action.</param>
/// <param name="userData">The user data.</param>
public void ForEachFilteredItem<TUserData>(Action<T, TUserData> action, TUserData userData) {
this.RebuildCache();
for (var i = 0; i < this._cachedFilteredItems.Count; i++) {
action(this._cachedFilteredItems[i], userData);
}
// If the cache was invalidated as a result of processing items, now is a good time to
// clear it and give the GC (more of) a chance to do its thing.
if (this._shouldRebuildCache) {
this._cachedFilteredItems.Clear();
}
}
/// <summary>
/// Iterates through each filtered item.
/// </summary>
/// <typeparam name="TUserData">The type of the user data.</typeparam>
/// <param name="action">The action.</param>
/// <param name="userData">The user data.</param>
public void ForEachFilteredItem<TUserData1, TUserData2>(Action<T, TUserData1, TUserData2> action, TUserData1 userData1, TUserData2 userData2) {
this.RebuildCache();
for (var i = 0; i < this._cachedFilteredItems.Count; i++) {
action(this._cachedFilteredItems[i], userData1, userData2);
}
// If the cache was invalidated as a result of processing items, now is a good time to
// clear it and give the GC (more of) a chance to do its thing.
if (this._shouldRebuildCache) {
this._cachedFilteredItems.Clear();
}
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1" /> that can be used to iterate
/// through the collection.
/// </returns>
public IEnumerator<T> GetEnumerator() {
this.RebuildCache();
return this._cachedFilteredItems.GetEnumerator();
}
/// <summary>
/// Rebuilds the cache.
/// </summary>
public void RebuildCache() {
lock (this._lock) {
if (this._shouldRebuildCache) {
this.ProcessRemoveJournal();
this.ProcessAddJournal();
// Rebuild the cache
this._cachedFilteredItems.Clear();
foreach (var item in this._items) {
if (this._filter(item)) {
this._cachedFilteredItems.Add(item);
}
}
this._shouldRebuildCache = false;
}
}
}
/// <summary>
/// Removes the first occurrence of a specific object from the
/// <see
/// cref="T:System.Collections.Generic.ICollection`1" />
/// .
/// </summary>
/// <param name="item">
/// The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1" />.
/// </param>
/// <returns>
/// true if <paramref name="item" /> was successfully removed from the
/// <see
/// cref="T:System.Collections.Generic.ICollection`1" />
/// ; otherwise, false. This method also
/// returns false if <paramref name="item" /> is not found in the original
/// <see
/// cref="T:System.Collections.Generic.ICollection`1" />
/// .
/// </returns>
public bool Remove(T item) {
lock (this._lock) {
if (this._addJournal.Remove(AddJournalEntry.CreateKey(item))) {
this.CollectionChanged.SafeInvoke(this, new CollectionChangedEventArgs<T>(false, item));
return true;
}
var index = this._items.IndexOf(item);
if (index >= 0) {
this.UnsubscribeFromItemEvents(item);
this._removeJournal.Add(index);
this.InvalidateCache();
this.CollectionChanged.SafeInvoke(this, new CollectionChangedEventArgs<T>(false, item));
return true;
}
return false;
}
}
/// <summary>
/// Removes the specified item.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>A value indicating whether or not the item was removed.</returns>
public bool Remove(object item) {
if (item is T x) {
return this.Remove(x);
}
return false;
}
private int CompareAddJournalEntry(AddJournalEntry x, AddJournalEntry y) {
var result = this._sort(x.Item, y.Item);
if (result != 0) {
return result;
}
return x.Order - y.Order;
}
/// <summary>
/// Gets the enumerator.
/// </summary>
/// <returns>The enumerator.</returns>
IEnumerator IEnumerable.GetEnumerator() {
return ((IEnumerable)this._items).GetEnumerator();
}
private void InvalidateCache() {
this._shouldRebuildCache = true;
}
private void Item_PropertyChanged(object? sender, PropertyChangedEventArgs e) {
if (e.PropertyName == this._sortPropertyName && sender is T item) {
lock (this._lock) {
var index = this._items.IndexOf(item);
this._addJournal.Add(new AddJournalEntry(this._addJournal.Count, item));
this._removeJournal.Add(index);
// Until the item is back in place, we don't care about its events. We will
// re-subscribe when this._addJournal is processed.
this.UnsubscribeFromItemEvents(item);
this.InvalidateCache();
}
}
else if (e.PropertyName == this._filterPropertyName) {
this.InvalidateCache();
}
}
private void ProcessAddJournal() {
if (this._addJournal.Count == 0) {
return;
}
// Prepare the this._addJournal to be merge-sorted with this._items. this._items is
// already sorted (because it is always sorted).
this._addJournal.Sort(this._addJournalSortComparison);
var iAddJournal = 0;
var iItems = 0;
while (iItems < this._items.Count && iAddJournal < this._addJournal.Count) {
var addJournalItem = this._addJournal[iAddJournal].Item;
// If addJournalItem is less than (belongs before) this._items[iItems], insert it.
if (this._sort(addJournalItem, this._items[iItems]) < 0) {
this.SubscribeToItemEvents(addJournalItem);
this._items.Insert(iItems, addJournalItem);
iAddJournal++;
}
// Always increment iItems, either because we inserted and need to move past the
// insertion, or because we didn't insert and need to consider the next element.
iItems++;
}
// If this._addJournal had any "tail" items, append them all now.
for (; iAddJournal < this._addJournal.Count; iAddJournal++) {
var addJournalItem = this._addJournal[iAddJournal].Item;
this.SubscribeToItemEvents(addJournalItem);
this._items.Add(addJournalItem);
}
this._addJournal.Clear();
}
private void ProcessRemoveJournal() {
if (this._removeJournal.Count == 0) {
return;
}
// Remove items in reverse. (Technically there exist faster ways to bulk-remove from a
// variable-length array, but List<T> does not provide such a method.)
this._removeJournal.Sort(RemoveJournalSortComparison);
for (var i = 0; i < this._removeJournal.Count; i++) {
var index = this._removeJournal[i];
if (index < this._items.Count) {
this._items.RemoveAt(this._removeJournal[i]);
}
}
this._removeJournal.Clear();
}
private void SubscribeToItemEvents(T item) {
item.PropertyChanged += this.Item_PropertyChanged;
}
private void UnsubscribeFromItemEvents(T item) {
item.PropertyChanged -= this.Item_PropertyChanged;
}
/// <summary>
/// Add journal entry.
/// </summary>
private struct AddJournalEntry {
/// <summary>
/// The item.
/// </summary>
public readonly T Item;
/// <summary>
/// The order.
/// </summary>
public readonly int Order;
/// <summary>
/// Initializes a new instance of the <see cref="AddJournalEntry" /> struct.
/// </summary>
/// <param name="order">Order.</param>
/// <param name="item">Item.</param>
public AddJournalEntry(int order, T item) {
this.Order = order;
this.Item = item;
}
/// <summary>
/// Creates the key.
/// </summary>
/// <returns>The key.</returns>
/// <param name="item">Item.</param>
public static AddJournalEntry CreateKey(T item) {
return new AddJournalEntry(-1, item);
}
/// <inheritdoc />
public override bool Equals(object? obj) {
if (!(obj is AddJournalEntry)) {
return false;
}
return Equals(this.Item, ((AddJournalEntry)obj).Item);
}
/// <inheritdoc />
public override int GetHashCode() {
return this.Item.GetHashCode();
}
}
}
| |
// 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.Collections.Immutable;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.NetCore.Analyzers.Runtime
{
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class SerializationRulesDiagnosticAnalyzer : DiagnosticAnalyzer
{
// Implement serialization constructors
internal const string RuleCA2229Id = "CA2229";
private static readonly LocalizableString s_localizableTitleCA2229 =
new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.ImplementSerializationConstructorsTitle),
MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
private static readonly LocalizableString s_localizableDescriptionCA2229 =
new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.ImplementSerializationConstructorsDescription),
MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
internal static DiagnosticDescriptor RuleCA2229Default = DiagnosticDescriptorHelper.Create(RuleCA2229Id,
s_localizableTitleCA2229,
MicrosoftNetCoreAnalyzersResources.ImplementSerializationConstructorsMessageCreateMagicConstructor,
DiagnosticCategory.Usage,
RuleLevel.IdeHidden_BulkConfigurable,
description: s_localizableDescriptionCA2229,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor RuleCA2229Sealed = DiagnosticDescriptorHelper.Create(RuleCA2229Id,
s_localizableTitleCA2229,
MicrosoftNetCoreAnalyzersResources.ImplementSerializationConstructorsMessageMakeSealedMagicConstructorPrivate,
DiagnosticCategory.Usage,
RuleLevel.IdeHidden_BulkConfigurable,
description: s_localizableDescriptionCA2229,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor RuleCA2229Unsealed = DiagnosticDescriptorHelper.Create(RuleCA2229Id,
s_localizableTitleCA2229,
MicrosoftNetCoreAnalyzersResources.ImplementSerializationConstructorsMessageMakeUnsealedMagicConstructorFamily,
DiagnosticCategory.Usage,
RuleLevel.IdeHidden_BulkConfigurable,
description: s_localizableDescriptionCA2229,
isPortedFxCopRule: true,
isDataflowRule: false);
// Mark ISerializable types with SerializableAttribute
internal const string RuleCA2237Id = "CA2237";
private static readonly LocalizableString s_localizableTitleCA2237 =
new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.MarkISerializableTypesWithSerializableTitle),
MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
private static readonly LocalizableString s_localizableMessageCA2237 =
new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.MarkISerializableTypesWithSerializableMessage),
MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
private static readonly LocalizableString s_localizableDescriptionCA2237 =
new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.MarkISerializableTypesWithSerializableDescription),
MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
internal static DiagnosticDescriptor RuleCA2237 = DiagnosticDescriptorHelper.Create(RuleCA2237Id,
s_localizableTitleCA2237,
s_localizableMessageCA2237,
DiagnosticCategory.Usage,
RuleLevel.CandidateForRemoval, // Cannot implement this for .NET Core: https://github.com/dotnet/roslyn-analyzers/issues/1775#issuecomment-518457308
description: s_localizableDescriptionCA2237,
isPortedFxCopRule: true,
isDataflowRule: false);
// Mark all non-serializable fields
internal const string RuleCA2235Id = "CA2235";
private static readonly LocalizableString s_localizableTitleCA2235 =
new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.MarkAllNonSerializableFieldsTitle),
MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
private static readonly LocalizableString s_localizableMessageCA2235 =
new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.MarkAllNonSerializableFieldsMessage),
MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
private static readonly LocalizableString s_localizableDescriptionCA2235 =
new LocalizableResourceString(
nameof(MicrosoftNetCoreAnalyzersResources.MarkAllNonSerializableFieldsDescription),
MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
internal static DiagnosticDescriptor RuleCA2235 = DiagnosticDescriptorHelper.Create(RuleCA2235Id,
s_localizableTitleCA2235,
s_localizableMessageCA2235,
DiagnosticCategory.Usage,
RuleLevel.CandidateForRemoval, // Cannot implement this for .NET Core: https://github.com/dotnet/roslyn-analyzers/issues/1775#issuecomment-518457308
description: s_localizableDescriptionCA2235,
isPortedFxCopRule: true,
isDataflowRule: false);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(RuleCA2229Default, RuleCA2229Sealed, RuleCA2229Unsealed, RuleCA2235, RuleCA2237);
public override void Initialize(AnalysisContext analysisContext)
{
analysisContext.EnableConcurrentExecution();
analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
analysisContext.RegisterCompilationStartAction(
(context) =>
{
INamedTypeSymbol? iserializableTypeSymbol = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationISerializable);
if (iserializableTypeSymbol == null)
{
return;
}
INamedTypeSymbol? serializationInfoTypeSymbol = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationSerializationInfo);
if (serializationInfoTypeSymbol == null)
{
return;
}
INamedTypeSymbol? streamingContextTypeSymbol = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationStreamingContext);
if (streamingContextTypeSymbol == null)
{
return;
}
INamedTypeSymbol? serializableAttributeTypeSymbol = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSerializableAttribute);
if (serializableAttributeTypeSymbol == null)
{
return;
}
INamedTypeSymbol? nonSerializedAttributeTypeSymbol = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNonSerializedAttribute);
if (nonSerializedAttributeTypeSymbol == null)
{
return;
}
var isNetStandardAssembly = !context.Compilation.TargetsDotNetFramework();
var symbolAnalyzer = new SymbolAnalyzer(iserializableTypeSymbol, serializationInfoTypeSymbol, streamingContextTypeSymbol, serializableAttributeTypeSymbol, nonSerializedAttributeTypeSymbol, isNetStandardAssembly);
context.RegisterSymbolAction(symbolAnalyzer.AnalyzeSymbol, SymbolKind.NamedType);
});
}
private sealed class SymbolAnalyzer
{
private readonly INamedTypeSymbol _iserializableTypeSymbol;
private readonly INamedTypeSymbol _serializationInfoTypeSymbol;
private readonly INamedTypeSymbol _streamingContextTypeSymbol;
private readonly INamedTypeSymbol _serializableAttributeTypeSymbol;
private readonly INamedTypeSymbol _nonSerializedAttributeTypeSymbol;
private readonly bool _isNetStandardAssembly;
public SymbolAnalyzer(
INamedTypeSymbol iserializableTypeSymbol,
INamedTypeSymbol serializationInfoTypeSymbol,
INamedTypeSymbol streamingContextTypeSymbol,
INamedTypeSymbol serializableAttributeTypeSymbol,
INamedTypeSymbol nonSerializedAttributeTypeSymbol,
bool isNetStandardAssembly)
{
_iserializableTypeSymbol = iserializableTypeSymbol;
_serializationInfoTypeSymbol = serializationInfoTypeSymbol;
_streamingContextTypeSymbol = streamingContextTypeSymbol;
_serializableAttributeTypeSymbol = serializableAttributeTypeSymbol;
_nonSerializedAttributeTypeSymbol = nonSerializedAttributeTypeSymbol;
_isNetStandardAssembly = isNetStandardAssembly;
}
public void AnalyzeSymbol(SymbolAnalysisContext context)
{
var namedTypeSymbol = (INamedTypeSymbol)context.Symbol;
if (namedTypeSymbol.TypeKind == TypeKind.Delegate || namedTypeSymbol.TypeKind == TypeKind.Interface)
{
return;
}
var implementsISerializable = namedTypeSymbol.AllInterfaces.Contains(_iserializableTypeSymbol);
var isSerializable = IsSerializable(namedTypeSymbol);
// If the type is public and implements ISerializable
if (namedTypeSymbol.DeclaredAccessibility == Accessibility.Public && implementsISerializable)
{
if (!isSerializable)
{
// CA2237 : Mark serializable types with the SerializableAttribute
if (namedTypeSymbol.BaseType.SpecialType == SpecialType.System_Object ||
IsSerializable(namedTypeSymbol.BaseType))
{
context.ReportDiagnostic(namedTypeSymbol.CreateDiagnostic(RuleCA2237, namedTypeSymbol.Name));
}
}
else
{
// Look for a serialization constructor.
// A serialization constructor takes two params of type SerializationInfo and StreamingContext.
IMethodSymbol serializationCtor = namedTypeSymbol.Constructors
.FirstOrDefault(c => c.IsSerializationConstructor(_serializationInfoTypeSymbol, _streamingContextTypeSymbol));
// There is no serialization ctor - issue a diagnostic.
if (serializationCtor == null)
{
context.ReportDiagnostic(namedTypeSymbol.CreateDiagnostic(RuleCA2229Default, namedTypeSymbol.Name));
}
else
{
// Check the accessibility
// The serialization ctor should be protected if the class is unsealed and private if the class is sealed.
if (namedTypeSymbol.IsSealed &&
serializationCtor.DeclaredAccessibility != Accessibility.Private)
{
context.ReportDiagnostic(serializationCtor.CreateDiagnostic(RuleCA2229Sealed, namedTypeSymbol.Name));
}
if (!namedTypeSymbol.IsSealed &&
serializationCtor.DeclaredAccessibility != Accessibility.Protected)
{
context.ReportDiagnostic(serializationCtor.CreateDiagnostic(RuleCA2229Unsealed, namedTypeSymbol.Name));
}
}
}
}
// If this is type is marked Serializable and doesn't implement ISerializable, check its fields' types as well
if (isSerializable && !implementsISerializable)
{
foreach (ISymbol member in namedTypeSymbol.GetMembers())
{
// Only process field members
if (!(member is IFieldSymbol field))
{
continue;
}
// Only process instance fields
if (field.IsStatic)
{
continue;
}
// Only process non-serializable fields
if (IsSerializable(field.Type))
{
continue;
}
// We bail out from reporting CA2235 in netstandard assemblies for types in metadata
// due to missing support: https://github.com/dotnet/roslyn-analyzers/issues/1775#issuecomment-519686818
if (_isNetStandardAssembly && field.Type.Locations.All(l => !l.IsInSource))
{
continue;
}
// Check for [NonSerialized]
if (field.GetAttributes().Any(x => x.AttributeClass.Equals(_nonSerializedAttributeTypeSymbol)))
{
continue;
}
// Handle compiler-generated fields (without source declaration) that have an associated symbol in code.
// For example, auto-property backing fields.
ISymbol targetSymbol = field.IsImplicitlyDeclared && field.AssociatedSymbol != null
? field.AssociatedSymbol
: field;
context.ReportDiagnostic(
targetSymbol.CreateDiagnostic(
RuleCA2235,
targetSymbol.Name,
namedTypeSymbol.Name,
field.Type));
}
}
}
private bool IsSerializable(ITypeSymbol type)
{
if (type.IsPrimitiveType())
{
return true;
}
switch (type.TypeKind)
{
case TypeKind.Array:
return IsSerializable(((IArrayTypeSymbol)type).ElementType);
case TypeKind.Enum:
return IsSerializable(((INamedTypeSymbol)type).EnumUnderlyingType);
case TypeKind.TypeParameter:
case TypeKind.Interface:
// The concrete type can't be determined statically,
// so we assume true to cut down on noise.
return true;
case TypeKind.Class:
case TypeKind.Struct:
// Check SerializableAttribute or Serializable flag from metadata.
return ((INamedTypeSymbol)type).IsSerializable;
case TypeKind.Delegate:
// delegates are always serializable, even if
// they aren't actually marked [Serializable]
return true;
default:
return type.GetAttributes().Any(a => a.AttributeClass.Equals(_serializableAttributeTypeSymbol));
}
}
}
}
}
| |
//-----------------------------------------------------------------------------
// 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.
//-----------------------------------------------------------------------------
/*
================================================================================
The DOFPostEffect API
================================================================================
DOFPostEffect::setFocalDist( %dist )
@summary
This method is for manually controlling the focus distance. It will have no
effect if auto focus is currently enabled. Makes use of the parameters set by
setFocusParams.
@param dist
float distance in meters
--------------------------------------------------------------------------------
DOFPostEffect::setAutoFocus( %enabled )
@summary
This method sets auto focus enabled or disabled. Makes use of the parameters set
by setFocusParams. When auto focus is enabled it determines the focal depth
by performing a raycast at the screen-center.
@param enabled
bool
--------------------------------------------------------------------------------
DOFPostEffect::setFocusParams( %nearBlurMax, %farBlurMax, %minRange, %maxRange, %nearSlope, %farSlope )
Set the parameters that control how the near and far equations are calculated
from the focal distance. If you are not using auto focus you will need to call
setFocusParams PRIOR to calling setFocalDist.
@param nearBlurMax
float between 0.0 and 1.0
The max allowed value of near blur.
@param farBlurMax
float between 0.0 and 1.0
The max allowed value of far blur.
@param minRange/maxRange
float in meters
The distance range around the focal distance that remains in focus is a lerp
between the min/maxRange using the normalized focal distance as the parameter.
The point is to allow the focal range to expand as you focus farther away since this is
visually appealing.
Note: since min/maxRange are lerped by the "normalized" focal distance it is
dependant on the visible distance set in your level.
@param nearSlope
float less than zero
The slope of the near equation. A small number causes bluriness to increase gradually
at distances closer than the focal distance. A large number causes bluriness to
increase quickly.
@param farSlope
float greater than zero
The slope of the far equation. A small number causes bluriness to increase gradually
at distances farther than the focal distance. A large number causes bluriness to
increase quickly.
Note: To rephrase, the min/maxRange parameters control how much area around the
focal distance is completely in focus where the near/farSlope parameters control
how quickly or slowly bluriness increases at distances outside of that range.
================================================================================
Examples
================================================================================
Example1: Turn on DOF while zoomed in with a weapon.
NOTE: These are not real callbacks! Hook these up to your code where appropriate!
function onSniperZoom()
{
// Parameterize how you want DOF to look.
DOFPostEffect.setFocusParams( 0.3, 0.3, 50, 500, -5, 5 );
// Turn on auto focus
DOFPostEffect.setAutoFocus( true );
// Turn on the PostEffect
DOFPostEffect.enable();
}
function onSniperUnzoom()
{
// Turn off the PostEffect
DOFPostEffect.disable();
}
Example2: Manually control DOF with the mouse wheel.
// Somewhere on startup...
// Parameterize how you want DOF to look.
DOFPostEffect.setFocusParams( 0.3, 0.3, 50, 500, -5, 5 );
// Turn off auto focus
DOFPostEffect.setAutoFocus( false );
// Turn on the PostEffect
DOFPostEffect.enable();
NOTE: These are not real callbacks! Hook these up to your code where appropriate!
function onMouseWheelUp()
{
// Since setFocalDist is really just a wrapper to assign to the focalDist
// dynamic field we can shortcut and increment it directly.
DOFPostEffect.focalDist += 8;
}
function onMouseWheelDown()
{
DOFPostEffect.focalDist -= 8;
}
*/
/// This method is for manually controlling the focal distance. It will have no
/// effect if auto focus is currently enabled. Makes use of the parameters set by
/// setFocusParams.
function DOFPostEffect::setFocalDist( %this, %dist )
{
%this.focalDist = %dist;
}
/// This method sets auto focus enabled or disabled. Makes use of the parameters set
/// by setFocusParams. When auto focus is enabled it determine the focal depth
/// by performing a raycast at the screen-center.
function DOFPostEffect::setAutoFocus( %this, %enabled )
{
%this.autoFocusEnabled = %enabled;
}
/// Set the parameters that control how the near and far equations are calculated
/// from the focal distance. If you are not using auto focus you will need to call
/// setFocusParams PRIOR to calling setFocalDist.
function DOFPostEffect::setFocusParams( %this, %nearBlurMax, %farBlurMax, %minRange, %maxRange, %nearSlope, %farSlope )
{
%this.nearBlurMax = %nearBlurMax;
%this.farBlurMax = %farBlurMax;
%this.minRange = %minRange;
%this.maxRange = %maxRange;
%this.nearSlope = %nearSlope;
%this.farSlope = %farSlope;
}
/*
More information...
This DOF technique is based on this paper:
http://http.developer.nvidia.com/GPUGems3/gpugems3_ch28.html
================================================================================
1. Overview of how we represent "Depth of Field"
================================================================================
DOF is expressed as an amount of bluriness per pixel according to its depth.
We represented this by a piecewise linear curve depicted below.
Note: we also refer to "bluriness" as CoC ( circle of confusion ) which is the term
used in the basis paper and in photography.
X-axis (depth)
x = 0.0----------------------------------------------x = 1.0
Y-axis (bluriness)
y = 1.0
|
| ____(x1,y1) (x4,y4)____
| (ns,nb)\ <--Line1 line2---> /(fe,fb)
| \ /
| \(x2,y2) (x3,y3)/
| (ne,0)------(fs,0)
y = 0.0
I have labeled the "corners" of this graph with (Xn,Yn) to illustrate that
this is in fact a collection of line segments where the x/y of each point
corresponds to the key below.
key:
ns - (n)ear blur (s)tart distance
nb - (n)ear (b)lur amount (max value)
ne - (n)ear blur (e)nd distance
fs - (f)ar blur (s)tart distance
fe - (f)ar blur (e)nd distance
fb - (f)ar (b)lur amount (max value)
Of greatest importance in this graph is Line1 and Line2. Where...
L1 { (x1,y1), (x2,y2) }
L2 { (x3,y3), (x4,y4) }
Line one represents the amount of "near" blur given a pixels depth and line two
represents the amount of "far" blur at that depth.
Both these equations are evaluated for each pixel and then the larger of the two
is kept. Also the output blur (for each equation) is clamped between 0 and its
maximum allowable value.
Therefore, to specify a DOF "qualify" you need to specify the near-blur-line,
far-blur-line, and maximum near and far blur value.
================================================================================
2. Abstracting a "focal depth"
================================================================================
Although the shader(s) work in terms of a near and far equation it is more
useful to express DOF as an adjustable focal depth and derive the other parameters
"under the hood".
Given a maximum near/far blur amount and a near/far slope we can calculate the
near/far equations for any focal depth. We extend this to also support a range
of depth around the focal depth that is also in focus and for that range to
shrink or grow as the focal depth moves closer or farther.
Keep in mind this is only one implementation and depending on the effect you
desire you may which to express the relationship between focal depth and
the shader paramaters different.
*/
//-----------------------------------------------------------------------------
// GFXStateBlockData / ShaderData
//-----------------------------------------------------------------------------
singleton GFXStateBlockData( PFX_DefaultDOFStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampPoint;
samplerStates[1] = SamplerClampPoint;
};
singleton GFXStateBlockData( PFX_DOFCalcCoCStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampLinear;
};
singleton GFXStateBlockData( PFX_DOFDownSampleStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampPoint;
};
singleton GFXStateBlockData( PFX_DOFBlurStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
};
singleton GFXStateBlockData( PFX_DOFFinalStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampLinear;
samplerStates[2] = SamplerClampLinear;
samplerStates[3] = SamplerClampPoint;
blendDefined = true;
blendEnable = true;
blendDest = GFXBlendInvSrcAlpha;
blendSrc = GFXBlendOne;
};
singleton ShaderData( PFX_DOFDownSampleShader )
{
DXVertexShaderFile = "shaders/common/postFx/dof/DOF_DownSample_V.hlsl";
DXPixelShaderFile = "shaders/common/postFx/dof/DOF_DownSample_P.hlsl";
OGLVertexShaderFile = "shaders/common/postFx/dof/gl/DOF_DownSample_V.glsl";
OGLPixelShaderFile = "shaders/common/postFx/dof/gl/DOF_DownSample_P.glsl";
samplerNames[0] = "$colorSampler";
samplerNames[1] = "$depthSampler";
pixVersion = 3.0;
};
singleton ShaderData( PFX_DOFBlurYShader )
{
DXVertexShaderFile = "shaders/common/postFx/dof/DOF_Gausian_V.hlsl";
DXPixelShaderFile = "shaders/common/postFx/dof/DOF_Gausian_P.hlsl";
OGLVertexShaderFile = "shaders/common/postFx/dof/gl/DOF_Gausian_V.glsl";
OGLPixelShaderFile = "shaders/common/postFx/dof/gl/DOF_Gausian_P.glsl";
samplerNames[0] = "$diffuseMap";
pixVersion = 2.0;
defines = "BLUR_DIR=float2(0.0,1.0)";
};
singleton ShaderData( PFX_DOFBlurXShader : PFX_DOFBlurYShader )
{
defines = "BLUR_DIR=float2(1.0,0.0)";
};
singleton ShaderData( PFX_DOFCalcCoCShader )
{
DXVertexShaderFile = "shaders/common/postFx/dof/DOF_CalcCoC_V.hlsl";
DXPixelShaderFile = "shaders/common/postFx/dof/DOF_CalcCoC_P.hlsl";
OGLVertexShaderFile = "shaders/common/postFx/dof/gl/DOF_CalcCoC_V.glsl";
OGLPixelShaderFile = "shaders/common/postFx/dof/gl/DOF_CalcCoC_P.glsl";
samplerNames[0] = "$shrunkSampler";
samplerNames[1] = "$blurredSampler";
pixVersion = 3.0;
};
singleton ShaderData( PFX_DOFSmallBlurShader )
{
DXVertexShaderFile = "shaders/common/postFx/dof/DOF_SmallBlur_V.hlsl";
DXPixelShaderFile = "shaders/common/postFx/dof/DOF_SmallBlur_P.hlsl";
OGLVertexShaderFile = "shaders/common/postFx/dof/gl/DOF_SmallBlur_V.glsl";
OGLPixelShaderFile = "shaders/common/postFx/dof/gl/DOF_SmallBlur_P.glsl";
samplerNames[0] = "$colorSampler";
pixVersion = 3.0;
};
singleton ShaderData( PFX_DOFFinalShader )
{
DXVertexShaderFile = "shaders/common/postFx/dof/DOF_Final_V.hlsl";
DXPixelShaderFile = "shaders/common/postFx/dof/DOF_Final_P.hlsl";
OGLVertexShaderFile = "shaders/common/postFx/dof/gl/DOF_Final_V.glsl";
OGLPixelShaderFile = "shaders/common/postFx/dof/gl/DOF_Final_P.glsl";
samplerNames[0] = "$colorSampler";
samplerNames[1] = "$smallBlurSampler";
samplerNames[2] = "$largeBlurSampler";
samplerNames[3] = "$depthSampler";
pixVersion = 3.0;
};
//-----------------------------------------------------------------------------
// PostEffects
//-----------------------------------------------------------------------------
function DOFPostEffect::onAdd( %this )
{
// The weighted distribution of CoC value to the three blur textures
// in the order small, medium, large. Most likely you will not need to
// change this value.
%this.setLerpDist( 0.2, 0.3, 0.5 );
// Fill out some default values but DOF really should not be turned on
// without actually specifying your own parameters!
%this.autoFocusEnabled = false;
%this.focalDist = 0.0;
%this.nearBlurMax = 0.5;
%this.farBlurMax = 0.5;
%this.minRange = 50;
%this.maxRange = 500;
%this.nearSlope = -5.0;
%this.farSlope = 5.0;
}
function DOFPostEffect::setLerpDist( %this, %d0, %d1, %d2 )
{
%this.lerpScale = -1.0 / %d0 SPC -1.0 / %d1 SPC -1.0 / %d2 SPC 1.0 / %d2;
%this.lerpBias = 1.0 SPC ( 1.0 - %d2 ) / %d1 SPC 1.0 / %d2 SPC ( %d2 - 1.0 ) / %d2;
}
singleton PostEffect( DOFPostEffect )
{
renderTime = "PFXAfterBin";
renderBin = "GlowBin";
renderPriority = 0.1;
shader = PFX_DOFDownSampleShader;
stateBlock = PFX_DOFDownSampleStateBlock;
texture[0] = "$backBuffer";
texture[1] = "#deferred";
target = "#shrunk";
targetScale = "0.25 0.25";
isEnabled = false;
};
singleton PostEffect( DOFBlurY )
{
shader = PFX_DOFBlurYShader;
stateBlock = PFX_DOFBlurStateBlock;
texture[0] = "#shrunk";
target = "$outTex";
};
DOFPostEffect.add( DOFBlurY );
singleton PostEffect( DOFBlurX )
{
shader = PFX_DOFBlurXShader;
stateBlock = PFX_DOFBlurStateBlock;
texture[0] = "$inTex";
target = "#largeBlur";
};
DOFPostEffect.add( DOFBlurX );
singleton PostEffect( DOFCalcCoC )
{
shader = PFX_DOFCalcCoCShader;
stateBlock = PFX_DOFCalcCoCStateBlock;
texture[0] = "#shrunk";
texture[1] = "#largeBlur";
target = "$outTex";
};
DOFPostEffect.add( DOFCalcCoc );
singleton PostEffect( DOFSmallBlur )
{
shader = PFX_DOFSmallBlurShader;
stateBlock = PFX_DefaultDOFStateBlock;
texture[0] = "$inTex";
target = "$outTex";
};
DOFPostEffect.add( DOFSmallBlur );
singleton PostEffect( DOFFinalPFX )
{
shader = PFX_DOFFinalShader;
stateBlock = PFX_DOFFinalStateBlock;
texture[0] = "$backBuffer";
texture[1] = "$inTex";
texture[2] = "#largeBlur";
texture[3] = "#deferred";
target = "$backBuffer";
};
DOFPostEffect.add( DOFFinalPFX );
//-----------------------------------------------------------------------------
// Scripts
//-----------------------------------------------------------------------------
function DOFPostEffect::setShaderConsts( %this )
{
if ( %this.autoFocusEnabled )
%this.autoFocus();
%fd = %this.focalDist / $Param::FarDist;
%range = mLerp( %this.minRange, %this.maxRange, %fd ) / $Param::FarDist * 0.5;
// We work in "depth" space rather than real-world units for the
// rest of this method...
// Given the focal distance and the range around it we want in focus
// we can determine the near-end-distance and far-start-distance
%ned = getMax( %fd - %range, 0.0 );
%fsd = getMin( %fd + %range, 1.0 );
// near slope
%nsl = %this.nearSlope;
// Given slope of near blur equation and the near end dist and amount (x2,y2)
// solve for the y-intercept
// y = mx + b
// so...
// y - mx = b
%b = 0.0 - %nsl * %ned;
%eqNear = %nsl SPC %b SPC 0.0;
// Do the same for the far blur equation...
%fsl = %this.farSlope;
%b = 0.0 - %fsl * %fsd;
%eqFar = %fsl SPC %b SPC 1.0;
%this.setShaderConst( "$dofEqWorld", %eqNear );
DOFFinalPFX.setShaderConst( "$dofEqFar", %eqFar );
%this.setShaderConst( "$maxWorldCoC", %this.nearBlurMax );
DOFFinalPFX.setShaderConst( "$maxFarCoC", %this.farBlurMax );
DOFFinalPFX.setShaderConst( "$dofLerpScale", %this.lerpScale );
DOFFinalPFX.setShaderConst( "$dofLerpBias", %this.lerpBias );
}
function DOFPostEffect::autoFocus( %this )
{
if ( !isObject( ServerConnection ) ||
!isObject( ServerConnection.getCameraObject() ) )
{
return;
}
%mask = $TypeMasks::StaticObjectType | $TypeMasks::TerrainObjectType;
%control = ServerConnection.getCameraObject();
%fvec = %control.getEyeVector();
%start = %control.getEyePoint();
%end = VectorAdd( %start, VectorScale( %fvec, $Param::FarDist ) );
// Use the client container for this ray cast.
%result = containerRayCast( %start, %end, %mask, %control, true );
%hitPos = getWords( %result, 1, 3 );
if ( %hitPos $= "" )
%focDist = $Param::FarDist;
else
%focDist = VectorDist( %hitPos, %start );
// For debuging
//$DOF::debug_dist = %focDist;
//$DOF::debug_depth = %focDist / $Param::FarDist;
//echo( "F: " @ %focDist SPC "D: " @ %delta );
%this.focalDist = %focDist;
}
// For debugging
/*
function reloadDOF()
{
exec( "./dof.cs" );
DOFPostEffect.reload();
DOFPostEffect.disable();
DOFPostEffect.enable();
}
function dofMetricsCallback()
{
return " | DOF |" @
" Dist: " @ $DOF::debug_dist @
" Depth: " @ $DOF::debug_depth;
}
*/
| |
//
// TagEntry.cs
//
// Author:
// Stephane Delcroix <stephane@delcroix.org>
// Joachim Breitner <mail@joachim-breitner.de>
// Ruben Vermeersch <ruben@savanne.be>
// Stephen Shaw <sshaw@decriptor.com>
//
// Copyright (C) 2006-2010 Novell, Inc.
// Copyright (C) 2006-2008 Stephane Delcroix
// Copyright (C) 2009 Joachim Breitner
// Copyright (C) 2010 Ruben Vermeersch
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Text;
using System.Collections.Generic;
using FSpot.Core;
using FSpot.Database;
namespace FSpot.Widgets
{
public delegate void TagsAttachedHandler (object sender, string [] tags);
public delegate void TagsRemovedHandler (object sender, Tag [] tags);
public class TagEntry : Gtk.Entry
{
public event TagsAttachedHandler TagsAttached;
public event TagsRemovedHandler TagsRemoved;
readonly TagStore tagStore;
protected TagEntry (System.IntPtr raw) : base(raw) { }
public TagEntry (TagStore tagStore, bool updateOnFocusOut = true)
{
this.tagStore = tagStore;
KeyPressEvent += HandleKeyPressEvent;
if (updateOnFocusOut)
FocusOutEvent += HandleFocusOutEvent;
}
List<string> selected_photos_tagnames;
public void UpdateFromSelection (IPhoto [] selection)
{
Dictionary<Tag,int> taghash = new Dictionary<Tag,int> ();
for (int i = 0; i < selection.Length; i++) {
foreach (Tag tag in selection [i].Tags) {
int count = 1;
if (taghash.ContainsKey (tag))
count = (taghash [tag]) + 1;
if (count <= i)
taghash.Remove (tag);
else
taghash [tag] = count;
}
if (taghash.Count == 0)
break;
}
selected_photos_tagnames = new List<string> ();
foreach (Tag tag in taghash.Keys)
if (taghash [tag] == selection.Length)
selected_photos_tagnames.Add (tag.Name);
Update ();
}
public void UpdateFromTagNames (string [] tagnames)
{
selected_photos_tagnames = new List<string> ();
foreach (string tagname in tagnames)
selected_photos_tagnames.Add (tagname);
Update ();
}
void Update ()
{
selected_photos_tagnames.Sort ();
StringBuilder sb = new StringBuilder ();
foreach (string tagname in selected_photos_tagnames) {
if (sb.Length > 0)
sb.Append (", ");
sb.Append (tagname);
}
Text = sb.ToString ();
ClearTagCompletions ();
}
void AppendComma ()
{
if (Text.Length != 0 && !Text.Trim ().EndsWith (",")) {
int pos = Text.Length;
InsertText (", ", ref pos);
Position = Text.Length;
}
}
public string [] GetTypedTagNames ()
{
string [] tagnames = Text.Split (new char [] {','});
List<string> list = new List<string> ();
for (int i = 0; i < tagnames.Length; i ++) {
string s = tagnames [i].Trim ();
if (s.Length > 0)
list.Add (s);
}
return list.ToArray ();
}
int tag_completion_index = -1;
Tag [] tag_completions;
public void ClearTagCompletions ()
{
tag_completion_index = -1;
tag_completions = null;
}
[GLib.ConnectBefore]
void HandleKeyPressEvent (object o, Gtk.KeyPressEventArgs args)
{
args.RetVal = false;
if (args.Event.Key == Gdk.Key.Escape) {
args.RetVal = false;
} else if (args.Event.Key == Gdk.Key.comma) {
if (tag_completion_index != -1) {
// If we are completing a tag, then finish that
FinishTagCompletion ();
args.RetVal = true;
} else
// Otherwise do not handle this event here
args.RetVal = false;
} else if (args.Event.Key == Gdk.Key.Return) {
// If we are completing a tag, then finish that
if (tag_completion_index != -1)
FinishTagCompletion ();
// And pass the event to Gtk.Entry in any case,
// which will call OnActivated
args.RetVal = false;
} else if (args.Event.Key == Gdk.Key.Tab) {
DoTagCompletion (true);
args.RetVal = true;
} else if (args.Event.Key == Gdk.Key.ISO_Left_Tab) {
DoTagCompletion (false);
args.RetVal = true;
}
}
bool tag_ignore_changes;
protected override void OnChanged ()
{
if (tag_ignore_changes)
return;
ClearTagCompletions ();
}
string tag_completion_typed_so_far;
int tag_completion_typed_position;
void DoTagCompletion (bool forward)
{
string completion;
if (tag_completion_index != -1) {
if (forward)
tag_completion_index = (tag_completion_index + 1) % tag_completions.Length;
else
tag_completion_index = (tag_completion_index + tag_completions.Length - 1) % tag_completions.Length;
} else {
tag_completion_typed_position = Position;
string right_of_cursor = Text.Substring (tag_completion_typed_position);
if (right_of_cursor.Length > 1)
return;
int last_comma = Text.LastIndexOf (',');
if (last_comma > tag_completion_typed_position)
return;
tag_completion_typed_so_far = Text.Substring (last_comma + 1).TrimStart (new char [] {' '});
if (tag_completion_typed_so_far == null || tag_completion_typed_so_far.Length == 0)
return;
tag_completions = tagStore.GetTagsByNameStart (tag_completion_typed_so_far);
if (tag_completions == null)
return;
if (forward)
tag_completion_index = 0;
else
tag_completion_index = tag_completions.Length - 1;
}
tag_ignore_changes = true;
completion = tag_completions [tag_completion_index].Name.Substring (tag_completion_typed_so_far.Length);
Text = Text.Substring (0, tag_completion_typed_position) + completion;
tag_ignore_changes = false;
Position = Text.Length;
SelectRegion (tag_completion_typed_position, Text.Length);
}
void FinishTagCompletion ()
{
if (tag_completion_index == -1)
return;
int sel_start, sel_end, pos;
pos = Position;
if (GetSelectionBounds (out sel_start, out sel_end)) {
pos = sel_end;
SelectRegion (-1, -1);
}
InsertText (", ", ref pos);
Position = pos + 2;
ClearTagCompletions ();
}
//Activated means the user pressed 'Enter'
protected override void OnActivated ()
{
string [] tagnames = GetTypedTagNames ();
if (tagnames == null)
return;
// Add any new tags to the selected photos
List<string> new_tags = new List<string> ();
for (int i = 0; i < tagnames.Length; i ++) {
if (tagnames [i].Length == 0)
continue;
if (selected_photos_tagnames.Contains (tagnames [i]))
continue;
Tag t = tagStore.GetTagByName (tagnames [i]);
if (t != null) // Correct for capitalization differences
tagnames [i] = t.Name;
new_tags.Add (tagnames [i]);
}
//Send event
if (new_tags.Count != 0 && TagsAttached != null)
TagsAttached (this, new_tags.ToArray ());
// Remove any removed tags from the selected photos
List<Tag> remove_tags = new List<Tag> ();
foreach (string tagname in selected_photos_tagnames) {
if (! IsTagInList (tagnames, tagname)) {
Tag tag = tagStore.GetTagByName (tagname);
remove_tags.Add (tag);
}
}
//Send event
if (remove_tags.Count != 0 && TagsRemoved != null)
TagsRemoved (this, remove_tags.ToArray ());
}
static bool IsTagInList (string [] tags, string tag)
{
foreach (string t in tags)
if (t == tag)
return true;
return false;
}
void HandleFocusOutEvent (object o, Gtk.FocusOutEventArgs args)
{
Update ();
}
protected override bool OnFocusInEvent (Gdk.EventFocus evnt)
{
AppendComma ();
return base.OnFocusInEvent (evnt);
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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 OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System.Text.RegularExpressions;
/*****************************************************
*
* ScriptsHttpRequests
*
* Implements the llHttpRequest and http_response
* callback.
*
* Some stuff was already in LSLLongCmdHandler, and then
* there was this file with a stub class in it. So,
* I am moving some of the objects and functions out of
* LSLLongCmdHandler, such as the HttpRequestClass, the
* start and stop methods, and setting up pending and
* completed queues. These are processed in the
* LSLLongCmdHandler polling loop. Similiar to the
* XMLRPCModule, since that seems to work.
*
* //TODO
*
* HTTPS support
*
* Configurable timeout?
* Configurable max response size?
* Configurable
*
* **************************************************/
namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
{
public class HttpRequestModule : IRegionModule, IHttpRequestModule
{
private Amib.Threading.SmartThreadPool _threadPool;
private Amib.Threading.SmartThreadPool _slowPool;
private readonly object m_httpListLock = new object();
private const int HTTP_TIMEOUT = 60 * 1000; // 60 seconds
private const string m_name = "HttpScriptRequests";
/// <summary>
/// The maximum number of inflight requests for the entire region before we start
/// returning null request IDs
/// </summary>
private const int MAX_REQUEST_QUEUE_SIZE = 200;
/// <summary>
/// The maximum number of slow HTTP requests we allow in the queue
/// </summary>
private const int MAX_SLOW_REQUEST_QUEUE_SIZE = 50;
/// <summary>
/// The maximum number of inflight requests for a single object before we start
/// returning null request IDs
/// </summary>
private const int MAX_SINGLE_OBJECT_QUEUE_SIZE = 10;
/// <summary>
/// The maximum number of threads to use for normal priority requests
/// </summary>
private const int MAX_NORMAL_THREADS = 24;
/// <summary>
/// The maximum number of threads to use for known slow requests
/// </summary>
private const int MAX_SLOW_THREADS = 8;
/// <summary>
/// The amount of time above which we consider a script to be slow (ms)
/// </summary>
private const int SLOW_SCRIPT_TIME = 3000;
/// <summary>
/// The amount of time above which we consider a script to be normal (ms)
/// Objects that respond faster than this time will have their priorities raised
/// if their priority is currently below normal
/// </summary>
private const int NORMAL_SCRIPT_TIME = 1000;
/// <summary>
/// The number of seconds we wait before checking the priority list for expired objects
/// </summary>
private const int PRIORITY_MAINT_SECS = 300;
/// <summary>
/// The number of seconds we remember the lower priority of misbehaving scripts
/// </summary>
private const int PRIORITY_TIMEOUT_SECS = 600;
private string m_proxyurl = "";
private string m_proxyexcepts = "";
// <request id, HttpRequestClass>
private Dictionary<UUID, HttpRequestObject> m_pendingRequests;
private Queue<HttpRequestObject> m_completedRequests;
private Scene m_scene;
/// <summary>
/// Tracks the number of http requests per script
/// </summary>
private Dictionary<UUID, short> m_objectQueueSize;
/// <summary>
/// A debugging log reporting level, 0 is off. See HttpRequestConsoleCommand().
/// </summary>
private int m_debugLevel = 0;
/// <summary>
/// Priorities for HTTP calls coming from an object based on the history of its behavior
/// </summary>
private Dictionary<UUID, TimestampedItem<Amib.Threading.WorkItemPriority>> m_objectPriorities;
/// <summary>
/// The last time in ticks that we maintained the priority list
/// </summary>
private ulong m_lastPriorityMaintenance;
/// <summary>
/// The number of low priority jobs that are currently queued
/// </summary>
private int m_numLowPriorityQueued;
public HttpRequestModule()
{
ServicePointManager.ServerCertificateValidationCallback += ValidateServerCertificate;
}
#region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IHttpRequestModule>(this);
m_proxyurl = config.Configs["Startup"].GetString("HttpProxy");
m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions");
m_pendingRequests = new Dictionary<UUID, HttpRequestObject>();
m_completedRequests = new Queue<HttpRequestObject>();
m_objectQueueSize = new Dictionary<UUID, short>();
m_objectPriorities = new Dictionary<UUID, TimestampedItem<Amib.Threading.WorkItemPriority>>();
m_lastPriorityMaintenance = Util.GetLongTickCount();
_threadPool = new Amib.Threading.SmartThreadPool(Amib.Threading.SmartThreadPool.DefaultIdleTimeout, MAX_NORMAL_THREADS, 2);
_threadPool.Name = "HttpRequestWorkerNormal";
_slowPool = new Amib.Threading.SmartThreadPool(Amib.Threading.SmartThreadPool.DefaultIdleTimeout, MAX_SLOW_THREADS, 0);
_slowPool.Name = "HttpRequestWorkerSlow";
ReadBlacklistFromConfig(config.Configs["HttpRequest"]);
MainConsole.Instance.Commands.AddCommand(
"Comms",
true,
"httprequest queuelength",
"httprequest queuelength",
"Report on the current size of the request queue.",
"Displays the current size of the request queue.",
HttpRequestConsoleCommand);
MainConsole.Instance.Commands.AddCommand(
"Comms",
true,
"httprequest debug",
"httprequest debug <debuglevel>",
"Enable/disable debugging of the request queue.",
"Enable/disable debugging of the request queue.",
HttpRequestConsoleCommand);
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return m_name; }
}
public bool IsSharedModule
{
get { return true; }
}
#endregion
#region IHttpRequestModule Members
public int OutstandingRequests
{
get { return m_pendingRequests.Count; }
}
public float RequestQueueFreeSpacePercentage
{
get
{
if (OutstandingRequests >= MAX_REQUEST_QUEUE_SIZE)
return 0.0f; // No space
else
return 1.0f - (float)OutstandingRequests / MAX_REQUEST_QUEUE_SIZE;
}
}
public UUID StartHttpRequest(UUID sogId, uint localID, UUID itemID, string url, string[] parms, Dictionary<string, string> headers, string body)
{
//if there are already too many requests globally, reject this one
if (RequestQueueFreeSpacePercentage == 0.0f) return UUID.Zero;
// fast exit for the common case of scripter error passing an empty URL
if (url == String.Empty) return UUID.Zero;
if (BlockedByBlacklist(url)) return UUID.Zero;
UUID reqID = UUID.Random();
HttpRequestObject htc = new HttpRequestObject();
// Partial implementation: support for parameter flags needed
// see http://wiki.secondlife.com/wiki/LlHTTPRequest
//
// Parameters are expected in {key, value, ... , key, value}
try
{
int i = 0;
while (i < parms.Length)
{
switch (Int32.Parse(parms[i++]))
{
case (int)HttpRequestConstants.HTTP_METHOD:
// This one was validated to be one of the valid values for method in LSLSystemAPI.cs
htc.HttpMethod = parms[i++];
break;
case (int)HttpRequestConstants.HTTP_MIMETYPE:
htc.HttpMIMEType = parms[i++];
break;
case (int)HttpRequestConstants.HTTP_BODY_MAXLENGTH:
htc.HttpBodyMaxLength = int.Parse(parms[i++]);
break;
case (int)HttpRequestConstants.HTTP_VERIFY_CERT:
htc.HttpVerifyCert = (int.Parse(parms[i++]) != 0);
break;
case (int)HttpRequestConstants.HTTP_VERBOSE_THROTTLE:
htc.HttpVerboseThrottle = (int.Parse(parms[i++]) != 0);
break;
case (int)HttpRequestConstants.HTTP_CUSTOM_HEADER:
string key = parms[i++];
string value = parms[i++];
// Don't overwrite values. Keeps us from clobbering
// The standard X-Secondlife params with user ones.
if (headers.ContainsKey(key) == false)
headers.Add(key, value);
break;
case (int)HttpRequestConstants.HTTP_PRAGMA_NO_CACHE:
// What if there is more than one pragma header defined?
bool noCache = (int.Parse(parms[i++]) != 0);
if (noCache == true)
headers.Add("Pragma", "no-cache");
else if (headers.ContainsKey("Pragma"))
headers.Remove("Pragma");
break;
default:
// Invalid Parameter Type. Log an error?
// Fail the request by returning a Null Key
return UUID.Zero;
}
}
}
catch (System.IndexOutOfRangeException)
{
// They passed us junk, we stepped past the end of the array.
// We'll fail the request by returning a NULL_KEY
return UUID.Zero;
}
if (m_debugLevel >= 1)
MainConsole.Instance.OutputFormat("httprequest: LocalID={0} URL={1}", localID, url);
htc.LocalID = localID;
htc.ItemID = itemID;
htc.SogID = sogId;
htc.Url = url;
htc.ReqID = reqID;
htc.HttpTimeout = HTTP_TIMEOUT;
htc.OutboundBody = body;
htc.ResponseHeaders = headers;
htc.proxyurl = m_proxyurl;
htc.proxyexcepts = m_proxyexcepts;
Amib.Threading.WorkItemPriority prio;
lock (m_httpListLock)
{
//if there are already too many requests for this script running, reject this one
if (!TryIncrementObjectQueue(sogId))
{
return UUID.Zero;
}
prio = GetObjectPriority(sogId);
if (prio == Amib.Threading.WorkItemPriority.Lowest)
{
if (m_numLowPriorityQueued < MAX_SLOW_REQUEST_QUEUE_SIZE)
{
htc.IsLowPriority = true;
++m_numLowPriorityQueued;
}
else
{
return UUID.Zero;
}
}
m_pendingRequests.Add(reqID, htc);
}
if (prio > Amib.Threading.WorkItemPriority.Lowest)
{
_threadPool.QueueWorkItem(() => this.ProcessRequest(htc));
}
else
{
_slowPool.QueueWorkItem(() => this.ProcessRequest(htc));
}
return reqID;
}
private bool TryIncrementObjectQueue(UUID sogId)
{
short size;
if (m_objectQueueSize.TryGetValue(sogId, out size))
{
if (size >= MAX_SINGLE_OBJECT_QUEUE_SIZE)
{
return false;
}
else
{
m_objectQueueSize[sogId] = ++size;
}
}
else
{
m_objectQueueSize.Add(sogId, 1);
}
return true;
}
private void ProcessRequest(HttpRequestObject req)
{
req.Process();
lock (m_httpListLock)
{
m_pendingRequests.Remove(req.ReqID);
m_completedRequests.Enqueue(req);
DecrementObjectQueue(req.SogID);
AdjustObjectPriority(req);
MaintainPriorityQueue();
}
}
private void MaintainPriorityQueue()
{
if (Util.GetLongTickCount() - m_lastPriorityMaintenance > PRIORITY_MAINT_SECS)
{
List<UUID> expiredObjects = new List<UUID>();
foreach (var kvp in m_objectPriorities)
{
if (kvp.Value.ElapsedSeconds >= PRIORITY_TIMEOUT_SECS)
{
expiredObjects.Add(kvp.Key);
}
}
foreach (var id in expiredObjects)
{
m_objectPriorities.Remove(id);
}
m_lastPriorityMaintenance = Util.GetLongTickCount();
}
}
/// <summary>
/// Based on the time it took a request to run, we adjust the priority
/// of future requests sent by an object
/// </summary>
/// <param name="req"></param>
private void AdjustObjectPriority(HttpRequestObject req)
{
Amib.Threading.WorkItemPriority prio = GetObjectPriority(req.SogID);
if (req.RequestDuration >= SLOW_SCRIPT_TIME)
{
if (prio > Amib.Threading.WorkItemPriority.Lowest)
{
prio--;
SetObjectPriority(req.SogID, prio);
}
}
else if (req.RequestDuration < NORMAL_SCRIPT_TIME)
{
if (prio < Amib.Threading.WorkItemPriority.Normal)
{
prio++;
SetObjectPriority(req.SogID, prio);
}
}
else
{
//just ping the timestamp if it exists
UpdatePriorityTimestamp(req.SogID);
}
//also if this request was low priority, maintain the counts
--m_numLowPriorityQueued;
}
private void UpdatePriorityTimestamp(UUID sogId)
{
TimestampedItem<Amib.Threading.WorkItemPriority> prio;
if (m_objectPriorities.TryGetValue(sogId, out prio))
{
prio.ResetTimestamp();
}
}
private void SetObjectPriority(UUID sogId, Amib.Threading.WorkItemPriority newPrio)
{
TimestampedItem<Amib.Threading.WorkItemPriority> prio;
if (m_objectPriorities.TryGetValue(sogId, out prio))
{
prio.Item = newPrio;
prio.ResetTimestamp();
}
else
{
m_objectPriorities[sogId] = new TimestampedItem<Amib.Threading.WorkItemPriority>(newPrio);
}
}
private Amib.Threading.WorkItemPriority GetObjectPriority(UUID sogId)
{
TimestampedItem<Amib.Threading.WorkItemPriority> prio;
if (! m_objectPriorities.TryGetValue(sogId, out prio))
{
return Amib.Threading.WorkItemPriority.Normal;
}
return prio.Item;
}
private void DecrementObjectQueue(UUID sogId)
{
short size;
if (m_objectQueueSize.TryGetValue(sogId, out size))
{
--size;
if (size == 0)
{
m_objectQueueSize.Remove(sogId);
}
else
{
m_objectQueueSize[sogId] = size;
}
}
}
public void StopHttpRequest(uint m_localID, UUID m_itemID)
{
if (m_pendingRequests != null)
{
lock (m_httpListLock)
{
m_objectQueueSize.Remove(m_itemID);
}
}
//The code below has been commented out because it doesn't work
//the problem is that m_itemID is not being used as the key for
//m_pendingRequests. m_pendingRequests key is the randomly generated
//request id generated in StartHttpRequestAbove
//TODO: Actually abort requests that haven't been started yet
/*
if (m_pendingRequests != null)
{
lock (HttpListLock)
{
HttpRequestClass tmpReq;
if (m_pendingRequests.TryGetValue(m_itemID, out tmpReq))
{
m_pendingRequests.Remove(m_itemID);
}
}
}
*/
}
/*
* TODO
* Not sure how important ordering is is here - the next first
* one completed in the list is returned, based soley on its list
* position, not the order in which the request was started or
* finsihed. I thought about setting up a queue for this, but
* it will need some refactoring and this works 'enough' right now
*/
public IServiceRequest GetNextCompletedRequest()
{
lock (m_httpListLock)
{
if (m_completedRequests.Count == 0) return null;
else return m_completedRequests.Dequeue();
}
}
#endregion
protected void HttpRequestConsoleCommand(string module, string[] args)
{
if (args.Length < 2)
return;
if (args[1] == "queuelength")
{
MainConsole.Instance.OutputFormat(
"Region {0} httprequest queue contains {1} requests",
m_scene.RegionInfo.RegionName,
OutstandingRequests);
return;
}
if (args[1] == "debug")
{
if (args.Length >= 3)
m_debugLevel = Convert.ToInt32(args[2]);
MainConsole.Instance.OutputFormat("httprequest debug level is {0}", m_debugLevel);
return;
}
}
public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
HttpWebRequest Request = (HttpWebRequest) sender;
if (Request.Headers.Get("NoVerifyCert") != null)
return true;
// If the certificate is a valid, signed certificate, return true.
if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
return true;
// If there are errors in the certificate chain, look at each error to determine the cause.
if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
{
if (chain != null && chain.ChainStatus != null)
{
foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
{
if ((certificate.Subject == certificate.Issuer) &&
(status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
{
// Self-signed certificates with an untrusted root are valid.
continue;
}
else
{
if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
{
// If there are any other errors in the certificate chain, the certificate is invalid,
// so the method returns false.
return false;
}
}
}
}
// When processing reaches this line, the only errors in the certificate chain are
// untrusted root errors for self-signed certificates. These certificates are valid
// for default Exchange server installations, so return true.
return true;
}
else
{
// In all other cases, return false.
return false;
}
}
#region Blacklist Checks
private List<string> _hostsBlacklist = new List<string>();
private List<int> _portsBlacklist = new List<int>();
private List<KeyValuePair<string, int>> _hostnameAndPortBlacklist = new List<KeyValuePair<string, int>>();
/// <summary>
/// Reads the blacklist config from the given configuration file
/// </summary>
/// <param name="config"></param>
private void ReadBlacklistFromConfig(IConfig config)
{
try
{
if (config == null)
return;
string hostBlacklist = config.GetString("HostBlacklist", "");
string portBlacklist = config.GetString("PortBlacklist", "");
string hostnameAndPortBlacklist = config.GetString("HostnameAndPortBlacklist", "");
if (!string.IsNullOrEmpty(hostBlacklist))
{
string[] hosts = hostBlacklist.Split(',');
foreach (string host in hosts)
_hostsBlacklist.Add(WildcardToRegex(host));
}
if (!string.IsNullOrEmpty(portBlacklist))
{
string[] ports = portBlacklist.Split(',');
foreach (string port in ports)
_portsBlacklist.Add(int.Parse(port));
}
if (!string.IsNullOrEmpty(hostnameAndPortBlacklist))
{
string[] hosts = hostnameAndPortBlacklist.Split(',');
foreach (string host in hosts)
{
string[] url = host.Split(':');
_hostnameAndPortBlacklist.Add(new KeyValuePair<string, int>(WildcardToRegex(url[0]), int.Parse(url[1])));
}
}
/*
Tests with config as follows
HostBlacklist = "10.0.0.1,20.0.0.*,google.com"
PortBlacklist = "8010,8020"
HostnameAndPortBlacklist = "192.168.1.*:80,yahoo.com:1234"
bool blocked;
blocked = BlockedByBlacklist("http://10.0.0.1:1234"); //true
blocked = BlockedByBlacklist("http://10.0.0.2:1234"); //false
blocked = BlockedByBlacklist("http://20.0.0.2:1234"); //true
blocked = BlockedByBlacklist("http://20.0.0.1:1234"); //true
blocked = BlockedByBlacklist("http://1.2.3.4:1234"); //false
blocked = BlockedByBlacklist("http://1.2.3.4:8010"); //true
blocked = BlockedByBlacklist("http://1.2.3.4:8020"); //true
blocked = BlockedByBlacklist("http://192.168.1.1:8080"); //false
blocked = BlockedByBlacklist("http://192.168.1.1:80"); //true
blocked = BlockedByBlacklist("http://192.168.1.1/test.html");
blocked = BlockedByBlacklist("http://google.com/test.html");//true
blocked = BlockedByBlacklist("http://yahoo.com/test.html");//false
blocked = BlockedByBlacklist("http://yahoo.com:1234/test.html");//true
*/
}
catch (Exception ex)
{
MainConsole.Instance.Output("[ScriptsHttpRequest]: Failed to parse blacklist config: " + ex.ToString());
}
}
/// <summary>
/// Checks to make sure that a url is allowed by the blacklist
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private bool BlockedByBlacklist(string url)
{
try
{
Uri uri = new Uri(url);
if (uri.Scheme != "http" && uri.Scheme != "https") return true;
//Port check
if (_portsBlacklist.Contains(uri.Port))
return true;
//Hostname check
if (_hostsBlacklist.Any((h) => Regex.IsMatch(uri.Host, h)))
return true;
//Hostname+port check
if (_hostnameAndPortBlacklist.Any((kvp) => Regex.IsMatch(uri.Host, kvp.Key) && kvp.Value == uri.Port))
return true;
return false;
}
catch (Exception ex)
{
MainConsole.Instance.Output("[ScriptsHttpRequest]: Failed to parse URL for blacklist check '" + url + "': " + ex.ToString());
}
return true;
}
/// <summary>
/// Converts a normal wildcard (e.g. 192.168.1.*) to a proper regular expression (^192\.168\.1\..*$)
/// </summary>
/// <param name="pattern"></param>
/// <returns></returns>
private string WildcardToRegex(string pattern)
{
return "^" + Regex.Escape(pattern)
.Replace(@"\*", ".*")
+ "$";
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void AddSingle()
{
var test = new SimpleBinaryOpTest__AddSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AddSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Single> _fld1;
public Vector128<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AddSingle testClass)
{
var result = AdvSimd.Add(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddSingle testClass)
{
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = AdvSimd.Add(
AdvSimd.LoadVector128((Single*)(pFld1)),
AdvSimd.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public SimpleBinaryOpTest__AddSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Add(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Add(
AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Single>* pClsVar1 = &_clsVar1)
fixed (Vector128<Single>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.Add(
AdvSimd.LoadVector128((Single*)(pClsVar1)),
AdvSimd.LoadVector128((Single*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = AdvSimd.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = AdvSimd.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddSingle();
var result = AdvSimd.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__AddSingle();
fixed (Vector128<Single>* pFld1 = &test._fld1)
fixed (Vector128<Single>* pFld2 = &test._fld2)
{
var result = AdvSimd.Add(
AdvSimd.LoadVector128((Single*)(pFld1)),
AdvSimd.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Add(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = AdvSimd.Add(
AdvSimd.LoadVector128((Single*)(pFld1)),
AdvSimd.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Add(
AdvSimd.LoadVector128((Single*)(&test._fld1)),
AdvSimd.LoadVector128((Single*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(left[0] + right[0]) != BitConverter.SingleToInt32Bits(result[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(left[i] + right[i]) != BitConverter.SingleToInt32Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Add)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/*
* Copyright (c) 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.Threading;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api.Plugins;
using Timer=OpenSim.Region.ScriptEngine.Shared.Api.Plugins.Timer;
using System.Reflection;
using log4net;
namespace OpenSim.Region.ScriptEngine.Shared.Api
{
/// <summary>
/// Handles LSL commands that takes long time and returns an event, for example timers, HTTP requests, etc.
/// </summary>
public class AsyncCommandManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static Thread cmdHandlerThread;
private static int cmdHandlerThreadCycleSleepms;
private static int numInstances;
/// <summary>
/// Lock for reading/writing static components of AsyncCommandManager.
/// </summary>
/// <remarks>
/// This lock exists so that multiple threads from different engines and/or different copies of the same engine
/// are prevented from running non-thread safe code (e.g. read/write of lists) concurrently.
/// </remarks>
private static object staticLock = new object();
private static List<IScriptEngine> m_ScriptEngines =
new List<IScriptEngine>();
public IScriptEngine m_ScriptEngine;
private static Dictionary<IScriptEngine, Dataserver> m_Dataserver =
new Dictionary<IScriptEngine, Dataserver>();
private static Dictionary<IScriptEngine, Timer> m_Timer =
new Dictionary<IScriptEngine, Timer>();
private static Dictionary<IScriptEngine, Listener> m_Listener =
new Dictionary<IScriptEngine, Listener>();
private static Dictionary<IScriptEngine, HttpRequest> m_HttpRequest =
new Dictionary<IScriptEngine, HttpRequest>();
private static Dictionary<IScriptEngine, SensorRepeat> m_SensorRepeat =
new Dictionary<IScriptEngine, SensorRepeat>();
private static Dictionary<IScriptEngine, XmlRequest> m_XmlRequest =
new Dictionary<IScriptEngine, XmlRequest>();
public Dataserver DataserverPlugin
{
get
{
lock (staticLock)
return m_Dataserver[m_ScriptEngine];
}
}
public Timer TimerPlugin
{
get
{
lock (staticLock)
return m_Timer[m_ScriptEngine];
}
}
public HttpRequest HttpRequestPlugin
{
get
{
lock (staticLock)
return m_HttpRequest[m_ScriptEngine];
}
}
public Listener ListenerPlugin
{
get
{
lock (staticLock)
return m_Listener[m_ScriptEngine];
}
}
public SensorRepeat SensorRepeatPlugin
{
get
{
lock (staticLock)
return m_SensorRepeat[m_ScriptEngine];
}
}
public XmlRequest XmlRequestPlugin
{
get
{
lock (staticLock)
return m_XmlRequest[m_ScriptEngine];
}
}
public IScriptEngine[] ScriptEngines
{
get
{
lock (staticLock)
return m_ScriptEngines.ToArray();
}
}
public AsyncCommandManager(IScriptEngine _ScriptEngine)
{
m_ScriptEngine = _ScriptEngine;
// If there is more than one scene in the simulator or multiple script engines are used on the same region
// then more than one thread could arrive at this block of code simultaneously. However, it cannot be
// executed concurrently both because concurrent list operations are not thread-safe and because of other
// race conditions such as the later check of cmdHandlerThread == null.
lock (staticLock)
{
if (m_ScriptEngines.Count == 0)
ReadConfig();
if (!m_ScriptEngines.Contains(m_ScriptEngine))
m_ScriptEngines.Add(m_ScriptEngine);
// Create instances of all plugins
if (!m_Dataserver.ContainsKey(m_ScriptEngine))
m_Dataserver[m_ScriptEngine] = new Dataserver(this);
if (!m_Timer.ContainsKey(m_ScriptEngine))
m_Timer[m_ScriptEngine] = new Timer(this);
if (!m_HttpRequest.ContainsKey(m_ScriptEngine))
m_HttpRequest[m_ScriptEngine] = new HttpRequest(this);
if (!m_Listener.ContainsKey(m_ScriptEngine))
m_Listener[m_ScriptEngine] = new Listener(this);
if (!m_SensorRepeat.ContainsKey(m_ScriptEngine))
m_SensorRepeat[m_ScriptEngine] = new SensorRepeat(this);
if (!m_XmlRequest.ContainsKey(m_ScriptEngine))
m_XmlRequest[m_ScriptEngine] = new XmlRequest(this);
numInstances++;
if (cmdHandlerThread == null)
{
cmdHandlerThread = WorkManager.StartThread(
CmdHandlerThreadLoop, "AsyncLSLCmdHandlerThread", ThreadPriority.Normal, true, true);
}
}
}
private void ReadConfig()
{
// cmdHandlerThreadCycleSleepms = m_ScriptEngine.Config.GetInt("AsyncLLCommandLoopms", 100);
// TODO: Make this sane again
cmdHandlerThreadCycleSleepms = 100;
}
/*
~AsyncCommandManager()
{
// Shut down thread
try
{
lock (staticLock)
{
numInstances--;
if(numInstances > 0)
return;
if (cmdHandlerThread != null)
{
if (cmdHandlerThread.IsAlive == true)
{
cmdHandlerThread.Abort();
//cmdHandlerThread.Join();
cmdHandlerThread = null;
}
}
}
}
catch
{
}
}
*/
/// <summary>
/// Main loop for the manager thread
/// </summary>
private static void CmdHandlerThreadLoop()
{
while (true)
{
try
{
Thread.Sleep(cmdHandlerThreadCycleSleepms);
Watchdog.UpdateThread();
DoOneCmdHandlerPass();
Watchdog.UpdateThread();
}
catch ( System.Threading.ThreadAbortException) { }
catch (Exception e)
{
m_log.Error("[ASYNC COMMAND MANAGER]: Exception in command handler pass: ", e);
}
}
}
private static void DoOneCmdHandlerPass()
{
lock (staticLock)
{
// Check HttpRequests
try { m_HttpRequest[m_ScriptEngines[0]].CheckHttpRequests(); } catch {}
// Check XMLRPCRequests
try { m_XmlRequest[m_ScriptEngines[0]].CheckXMLRPCRequests(); } catch {}
foreach (IScriptEngine s in m_ScriptEngines)
{
// Check Listeners
try { m_Listener[s].CheckListeners(); } catch {}
// Check timers
try { m_Timer[s].CheckTimerEvents(); } catch {}
// Check Sensors
try { m_SensorRepeat[s].CheckSenseRepeaterEvents(); } catch {}
// Check dataserver
try { m_Dataserver[s].ExpireRequests(); } catch {}
}
}
}
/// <summary>
/// Remove a specific script (and all its pending commands)
/// </summary>
/// <param name="localID"></param>
/// <param name="itemID"></param>
public static void RemoveScript(IScriptEngine engine, uint localID, UUID itemID)
{
// Remove a specific script
// m_log.DebugFormat("[ASYNC COMMAND MANAGER]: Removing facilities for script {0}", itemID);
lock (staticLock)
{
// Remove dataserver events
m_Dataserver[engine].RemoveEvents(localID, itemID);
// Remove from: Timers
m_Timer[engine].UnSetTimerEvents(localID, itemID);
if(engine.World != null)
{
// Remove from: HttpRequest
IHttpRequestModule iHttpReq = engine.World.RequestModuleInterface<IHttpRequestModule>();
if (iHttpReq != null)
iHttpReq.StopHttpRequest(localID, itemID);
IWorldComm comms = engine.World.RequestModuleInterface<IWorldComm>();
if (comms != null)
comms.DeleteListener(itemID);
IXMLRPC xmlrpc = engine.World.RequestModuleInterface<IXMLRPC>();
if (xmlrpc != null)
{
xmlrpc.DeleteChannels(itemID);
xmlrpc.CancelSRDRequests(itemID);
}
}
// Remove Sensors
m_SensorRepeat[engine].UnSetSenseRepeaterEvents(localID, itemID);
}
}
public static void StateChange(IScriptEngine engine, uint localID, UUID itemID)
{
// Remove a specific script
// Remove dataserver events
m_Dataserver[engine].RemoveEvents(localID, itemID);
IWorldComm comms = engine.World.RequestModuleInterface<IWorldComm>();
if (comms != null)
comms.DeleteListener(itemID);
IXMLRPC xmlrpc = engine.World.RequestModuleInterface<IXMLRPC>();
if (xmlrpc != null)
{
xmlrpc.DeleteChannels(itemID);
xmlrpc.CancelSRDRequests(itemID);
}
// Remove Sensors
m_SensorRepeat[engine].UnSetSenseRepeaterEvents(localID, itemID);
}
/// <summary>
/// Get the sensor repeat plugin for this script engine.
/// </summary>
/// <param name="engine"></param>
/// <returns></returns>
public static SensorRepeat GetSensorRepeatPlugin(IScriptEngine engine)
{
lock (staticLock)
{
if (m_SensorRepeat.ContainsKey(engine))
return m_SensorRepeat[engine];
else
return null;
}
}
/// <summary>
/// Get the dataserver plugin for this script engine.
/// </summary>
/// <param name="engine"></param>
/// <returns></returns>
public static Dataserver GetDataserverPlugin(IScriptEngine engine)
{
lock (staticLock)
{
if (m_Dataserver.ContainsKey(engine))
return m_Dataserver[engine];
else
return null;
}
}
/// <summary>
/// Get the timer plugin for this script engine.
/// </summary>
/// <param name="engine"></param>
/// <returns></returns>
public static Timer GetTimerPlugin(IScriptEngine engine)
{
lock (staticLock)
{
if (m_Timer.ContainsKey(engine))
return m_Timer[engine];
else
return null;
}
}
/// <summary>
/// Get the listener plugin for this script engine.
/// </summary>
/// <param name="engine"></param>
/// <returns></returns>
public static Listener GetListenerPlugin(IScriptEngine engine)
{
lock (staticLock)
{
if (m_Listener.ContainsKey(engine))
return m_Listener[engine];
else
return null;
}
}
public static Object[] GetSerializationData(IScriptEngine engine, UUID itemID)
{
List<Object> data = new List<Object>();
lock (staticLock)
{
Object[] listeners = m_Listener[engine].GetSerializationData(itemID);
if (listeners.Length > 0)
{
data.Add("listener");
data.Add(listeners.Length);
data.AddRange(listeners);
}
Object[] timers=m_Timer[engine].GetSerializationData(itemID);
if (timers.Length > 0)
{
data.Add("timer");
data.Add(timers.Length);
data.AddRange(timers);
}
Object[] sensors = m_SensorRepeat[engine].GetSerializationData(itemID);
if (sensors.Length > 0)
{
data.Add("sensor");
data.Add(sensors.Length);
data.AddRange(sensors);
}
}
return data.ToArray();
}
public static void CreateFromData(IScriptEngine engine, uint localID,
UUID itemID, UUID hostID, Object[] data)
{
int idx = 0;
int len;
while (idx < data.Length)
{
string type = data[idx].ToString();
len = (int)data[idx+1];
idx+=2;
if (len > 0)
{
Object[] item = new Object[len];
Array.Copy(data, idx, item, 0, len);
idx+=len;
lock (staticLock)
{
switch (type)
{
case "listener":
m_Listener[engine].CreateFromData(localID, itemID,
hostID, item);
break;
case "timer":
m_Timer[engine].CreateFromData(localID, itemID,
hostID, item);
break;
case "sensor":
m_SensorRepeat[engine].CreateFromData(localID,
itemID, hostID, item);
break;
}
}
}
}
}
}
}
| |
/*
* 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.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using log4net;
namespace OpenSim.Framework.Servers.HttpServer
{
public class RestSessionObject<TRequest>
{
private string sid;
private string aid;
private TRequest request_body;
public string SessionID
{
get { return sid; }
set { sid = value; }
}
public string AvatarID
{
get { return aid; }
set { aid = value; }
}
public TRequest Body
{
get { return request_body; }
set { request_body = value; }
}
}
public class SynchronousRestSessionObjectPoster<TRequest, TResponse>
{
public static TResponse BeginPostObject(string verb, string requestUrl, TRequest obj, string sid, string aid)
{
RestSessionObject<TRequest> sobj = new RestSessionObject<TRequest>();
sobj.SessionID = sid;
sobj.AvatarID = aid;
sobj.Body = obj;
Type type = typeof(RestSessionObject<TRequest>);
WebRequest request = WebRequest.Create(requestUrl);
request.Method = verb;
request.ContentType = "text/xml";
request.Timeout = 20000;
MemoryStream buffer = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
using (XmlWriter writer = XmlWriter.Create(buffer, settings))
{
XmlSerializer serializer = new XmlSerializer(type);
serializer.Serialize(writer, sobj);
writer.Flush();
}
int length = (int)buffer.Length;
request.ContentLength = length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer.ToArray(), 0, length);
buffer.Close();
requestStream.Close();
TResponse deserial = default(TResponse);
using (WebResponse resp = request.GetResponse())
{
XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
Stream respStream = null;
try
{
respStream = resp.GetResponseStream();
deserial = (TResponse)deserializer.Deserialize(respStream);
}
catch { }
finally
{
if (respStream != null)
respStream.Close();
resp.Close();
}
}
return deserial;
}
}
public class RestSessionObjectPosterResponse<TRequest, TResponse>
{
public ReturnResponse<TResponse> ResponseCallback;
public void BeginPostObject(string requestUrl, TRequest obj, string sid, string aid)
{
BeginPostObject("POST", requestUrl, obj, sid, aid);
}
public void BeginPostObject(string verb, string requestUrl, TRequest obj, string sid, string aid)
{
RestSessionObject<TRequest> sobj = new RestSessionObject<TRequest>();
sobj.SessionID = sid;
sobj.AvatarID = aid;
sobj.Body = obj;
Type type = typeof(RestSessionObject<TRequest>);
WebRequest request = WebRequest.Create(requestUrl);
request.Method = verb;
request.ContentType = "text/xml";
request.Timeout = 10000;
MemoryStream buffer = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
using (XmlWriter writer = XmlWriter.Create(buffer, settings))
{
XmlSerializer serializer = new XmlSerializer(type);
serializer.Serialize(writer, sobj);
writer.Flush();
}
buffer.Close();
int length = (int)buffer.Length;
request.ContentLength = length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer.ToArray(), 0, length);
requestStream.Close();
// IAsyncResult result = request.BeginGetResponse(AsyncCallback, request);
request.BeginGetResponse(AsyncCallback, request);
}
private void AsyncCallback(IAsyncResult result)
{
WebRequest request = (WebRequest)result.AsyncState;
using (WebResponse resp = request.EndGetResponse(result))
{
TResponse deserial;
XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
Stream stream = resp.GetResponseStream();
// This is currently a bad debug stanza since it gobbles us the response...
// StreamReader reader = new StreamReader(stream);
// m_log.DebugFormat("[REST OBJECT POSTER RESPONSE]: Received {0}", reader.ReadToEnd());
deserial = (TResponse)deserializer.Deserialize(stream);
if (stream != null)
stream.Close();
if (deserial != null && ResponseCallback != null)
{
ResponseCallback(deserial);
}
}
}
}
public delegate bool CheckIdentityMethod(string sid, string aid);
public class RestDeserialiseSecureHandler<TRequest, TResponse> : BaseRequestHandler, IStreamHandler
where TRequest : new()
{
private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private RestDeserialiseMethod<TRequest, TResponse> m_method;
private CheckIdentityMethod m_smethod;
public RestDeserialiseSecureHandler(
string httpMethod, string path,
RestDeserialiseMethod<TRequest, TResponse> method, CheckIdentityMethod smethod)
: base(httpMethod, path)
{
m_smethod = smethod;
m_method = method;
}
public void Handle(string path, Stream request, Stream responseStream,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
RestSessionObject<TRequest> deserial = default(RestSessionObject<TRequest>);
bool fail = false;
using (XmlTextReader xmlReader = new XmlTextReader(request))
{
try
{
XmlSerializer deserializer = new XmlSerializer(typeof(RestSessionObject<TRequest>));
deserial = (RestSessionObject<TRequest>)deserializer.Deserialize(xmlReader);
}
catch (Exception e)
{
m_log.Error("[REST]: Deserialization problem. Ignoring request. " + e);
fail = true;
}
}
TResponse response = default(TResponse);
if (!fail && m_smethod(deserial.SessionID, deserial.AvatarID))
{
response = m_method(deserial.Body);
}
using (XmlWriter xmlWriter = XmlTextWriter.Create(responseStream))
{
XmlSerializer serializer = new XmlSerializer(typeof(TResponse));
serializer.Serialize(xmlWriter, response);
}
}
}
public delegate bool CheckTrustedSourceMethod(IPEndPoint peer);
public class RestDeserialiseTrustedHandler<TRequest, TResponse> : BaseRequestHandler, IStreamHandler
where TRequest : new()
{
private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// The operation to perform once trust has been established.
/// </summary>
private RestDeserialiseMethod<TRequest, TResponse> m_method;
/// <summary>
/// The method used to check whether a request is trusted.
/// </summary>
private CheckTrustedSourceMethod m_tmethod;
public RestDeserialiseTrustedHandler(string httpMethod, string path, RestDeserialiseMethod<TRequest, TResponse> method, CheckTrustedSourceMethod tmethod)
: base(httpMethod, path)
{
m_tmethod = tmethod;
m_method = method;
}
public void Handle(string path, Stream request, Stream responseStream,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
TRequest deserial = default(TRequest);
bool fail = false;
using (XmlTextReader xmlReader = new XmlTextReader(request))
{
try
{
XmlSerializer deserializer = new XmlSerializer(typeof(TRequest));
deserial = (TRequest)deserializer.Deserialize(xmlReader);
}
catch (Exception e)
{
m_log.Error("[REST]: Deserialization problem. Ignoring request. " + e);
fail = true;
}
}
TResponse response = default(TResponse);
if (!fail && m_tmethod(httpRequest.RemoteIPEndPoint))
{
response = m_method(deserial);
}
using (XmlWriter xmlWriter = XmlTextWriter.Create(responseStream))
{
XmlSerializer serializer = new XmlSerializer(typeof(TResponse));
serializer.Serialize(xmlWriter, response);
}
}
}
}
| |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus Utilities SDK License Version 1.31 (the "License"); you may not use
the Utilities SDK except in compliance with the License, which is provided at the time of installation
or download, or which otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/utilities-1.31
Unless required by applicable law or agreed to in writing, the Utilities SDK distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
ANY KIND, either express or implied. See the License for the specific language governing
permissions and limitations under the License.
************************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;
/// <summary>
/// Extension of GraphicRaycaster to support ray casting with world space rays instead of just screen-space
/// pointer positions
/// </summary>
[RequireComponent(typeof(Canvas))]
public class OVRRaycaster : GraphicRaycaster, IPointerEnterHandler
{
[Tooltip("A world space pointer for this canvas")]
public GameObject pointer;
public int sortOrder = 0;
protected OVRRaycaster()
{ }
[NonSerialized]
private Canvas m_Canvas;
private Canvas canvas
{
get
{
if (m_Canvas != null)
return m_Canvas;
m_Canvas = GetComponent<Canvas>();
return m_Canvas;
}
}
public override Camera eventCamera
{
get
{
return canvas.worldCamera;
}
}
public override int sortOrderPriority
{
get
{
return sortOrder;
}
}
protected override void Start()
{
if(!canvas.worldCamera)
{
Debug.Log("Canvas does not have an event camera attached. Attaching OVRCameraRig.centerEyeAnchor as default.");
OVRCameraRig rig = FindObjectOfType<OVRCameraRig>();
canvas.worldCamera = rig.centerEyeAnchor.gameObject.GetComponent<Camera>();
}
}
/// <summary>
/// For the given ray, find graphics on this canvas which it intersects and are not blocked by other
/// world objects
/// </summary>
[NonSerialized]
private List<RaycastHit> m_RaycastResults = new List<RaycastHit>();
private void Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList, Ray ray, bool checkForBlocking)
{
//This function is closely based on
//void GraphicRaycaster.Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList)
if (canvas == null)
return;
float hitDistance = float.MaxValue;
if (checkForBlocking && blockingObjects != BlockingObjects.None)
{
float dist = eventCamera.farClipPlane;
if (blockingObjects == BlockingObjects.ThreeD || blockingObjects == BlockingObjects.All)
{
var hits = Physics.RaycastAll(ray, dist, m_BlockingMask);
if (hits.Length > 0 && hits[0].distance < hitDistance)
{
hitDistance = hits[0].distance;
}
}
if (blockingObjects == BlockingObjects.TwoD || blockingObjects == BlockingObjects.All)
{
var hits = Physics2D.GetRayIntersectionAll(ray, dist, m_BlockingMask);
if (hits.Length > 0 && hits[0].fraction * dist < hitDistance)
{
hitDistance = hits[0].fraction * dist;
}
}
}
m_RaycastResults.Clear();
GraphicRaycast(canvas, ray, m_RaycastResults);
for (var index = 0; index < m_RaycastResults.Count; index++)
{
var go = m_RaycastResults[index].graphic.gameObject;
bool appendGraphic = true;
if (ignoreReversedGraphics)
{
// If we have a camera compare the direction against the cameras forward.
var cameraFoward = ray.direction;
var dir = go.transform.rotation * Vector3.forward;
appendGraphic = Vector3.Dot(cameraFoward, dir) > 0;
}
// Ignore points behind us (can happen with a canvas pointer)
if (eventCamera.transform.InverseTransformPoint(m_RaycastResults[index].worldPos).z <= 0)
{
appendGraphic = false;
}
if (appendGraphic)
{
float distance = Vector3.Distance(ray.origin, m_RaycastResults[index].worldPos);
if (distance >= hitDistance)
{
continue;
}
var castResult = new RaycastResult
{
gameObject = go,
module = this,
distance = distance,
index = resultAppendList.Count,
depth = m_RaycastResults[index].graphic.depth,
worldPosition = m_RaycastResults[index].worldPos
};
resultAppendList.Add(castResult);
}
}
}
/// <summary>
/// Performs a raycast using eventData.worldSpaceRay
/// </summary>
/// <param name="eventData"></param>
/// <param name="resultAppendList"></param>
public override void Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList)
{
if (eventData.IsVRPointer())
{
Raycast(eventData, resultAppendList, eventData.GetRay(), true);
}
}
/// <summary>
/// Performs a raycast using the pointer object attached to this OVRRaycaster
/// </summary>
/// <param name="eventData"></param>
/// <param name="resultAppendList"></param>
public void RaycastPointer(PointerEventData eventData, List<RaycastResult> resultAppendList)
{
if (pointer != null && pointer.activeInHierarchy)
{
Raycast(eventData, resultAppendList, new Ray(eventCamera.transform.position, (pointer.transform.position - eventCamera.transform.position).normalized), false);
}
}
/// <summary>
/// Perform a raycast into the screen and collect all graphics underneath it.
/// </summary>
[NonSerialized]
static readonly List<RaycastHit> s_SortedGraphics = new List<RaycastHit>();
private void GraphicRaycast(Canvas canvas, Ray ray, List<RaycastHit> results)
{
//This function is based closely on :
// void GraphicRaycaster.Raycast(Canvas canvas, Camera eventCamera, Vector2 pointerPosition, List<Graphic> results)
// But modified to take a Ray instead of a canvas pointer, and also to explicitly ignore
// the graphic associated with the pointer
// Necessary for the event system
var foundGraphics = GraphicRegistry.GetGraphicsForCanvas(canvas);
s_SortedGraphics.Clear();
for (int i = 0; i < foundGraphics.Count; ++i)
{
Graphic graphic = foundGraphics[i];
// -1 means it hasn't been processed by the canvas, which means it isn't actually drawn
if (graphic.depth == -1 || (pointer == graphic.gameObject))
continue;
Vector3 worldPos;
if (RayIntersectsRectTransform(graphic.rectTransform, ray, out worldPos))
{
//Work out where this is on the screen for compatibility with existing Unity UI code
Vector2 screenPos = eventCamera.WorldToScreenPoint(worldPos);
// mask/image intersection - See Unity docs on eventAlphaThreshold for when this does anything
if (graphic.Raycast(screenPos, eventCamera))
{
RaycastHit hit;
hit.graphic = graphic;
hit.worldPos = worldPos;
hit.fromMouse = false;
s_SortedGraphics.Add(hit);
}
}
}
s_SortedGraphics.Sort((g1, g2) => g2.graphic.depth.CompareTo(g1.graphic.depth));
for (int i = 0; i < s_SortedGraphics.Count; ++i)
{
results.Add(s_SortedGraphics[i]);
}
}
/// <summary>
/// Get screen position of worldPosition contained in this RaycastResult
/// </summary>
/// <param name="worldPosition"></param>
/// <returns></returns>
public Vector2 GetScreenPosition(RaycastResult raycastResult)
{
// In future versions of Uinty RaycastResult will contain screenPosition so this will not be necessary
return eventCamera.WorldToScreenPoint(raycastResult.worldPosition);
}
/// <summary>
/// Detects whether a ray intersects a RectTransform and if it does also
/// returns the world position of the intersection.
/// </summary>
/// <param name="rectTransform"></param>
/// <param name="ray"></param>
/// <param name="worldPos"></param>
/// <returns></returns>
static bool RayIntersectsRectTransform(RectTransform rectTransform, Ray ray, out Vector3 worldPos)
{
Vector3[] corners = new Vector3[4];
rectTransform.GetWorldCorners(corners);
Plane plane = new Plane(corners[0], corners[1], corners[2]);
float enter;
if (!plane.Raycast(ray, out enter))
{
worldPos = Vector3.zero;
return false;
}
Vector3 intersection = ray.GetPoint(enter);
Vector3 BottomEdge = corners[3] - corners[0];
Vector3 LeftEdge = corners[1] - corners[0];
float BottomDot = Vector3.Dot(intersection - corners[0], BottomEdge);
float LeftDot = Vector3.Dot(intersection - corners[0], LeftEdge);
if (BottomDot < BottomEdge.sqrMagnitude && // Can use sqrMag because BottomEdge is not normalized
LeftDot < LeftEdge.sqrMagnitude &&
BottomDot >= 0 &&
LeftDot >= 0)
{
worldPos = corners[0] + LeftDot * LeftEdge / LeftEdge.sqrMagnitude + BottomDot * BottomEdge / BottomEdge.sqrMagnitude;
return true;
}
else
{
worldPos = Vector3.zero;
return false;
}
}
struct RaycastHit
{
public Graphic graphic;
public Vector3 worldPos;
public bool fromMouse;
};
/// <summary>
/// Is this the currently focussed Raycaster according to the InputModule
/// </summary>
/// <returns></returns>
public bool IsFocussed()
{
OVRInputModule inputModule = EventSystem.current.currentInputModule as OVRInputModule;
return inputModule && inputModule.activeGraphicRaycaster == this;
}
public void OnPointerEnter(PointerEventData e)
{
if (e.IsVRPointer())
{
// Gaze has entered this canvas. We'll make it the active one so that canvas-mouse pointer can be used.
OVRInputModule inputModule = EventSystem.current.currentInputModule as OVRInputModule;
if(inputModule != null)
{
inputModule.activeGraphicRaycaster = this;
}
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using SquabPie.Mono.Cecil.Metadata;
namespace SquabPie.Mono.Cecil {
struct Range {
public uint Start;
public uint Length;
public Range (uint index, uint length)
{
this.Start = index;
this.Length = length;
}
}
sealed class MetadataSystem {
internal AssemblyNameReference [] AssemblyReferences;
internal ModuleReference [] ModuleReferences;
internal TypeDefinition [] Types;
internal TypeReference [] TypeReferences;
internal FieldDefinition [] Fields;
internal MethodDefinition [] Methods;
internal MemberReference [] MemberReferences;
internal Dictionary<uint, uint []> NestedTypes;
internal Dictionary<uint, uint> ReverseNestedTypes;
internal Dictionary<uint, MetadataToken []> Interfaces;
internal Dictionary<uint, Row<ushort, uint>> ClassLayouts;
internal Dictionary<uint, uint> FieldLayouts;
internal Dictionary<uint, uint> FieldRVAs;
internal Dictionary<MetadataToken, uint> FieldMarshals;
internal Dictionary<MetadataToken, Row<ElementType, uint>> Constants;
internal Dictionary<uint, MetadataToken []> Overrides;
internal Dictionary<MetadataToken, Range []> CustomAttributes;
internal Dictionary<MetadataToken, Range []> SecurityDeclarations;
internal Dictionary<uint, Range> Events;
internal Dictionary<uint, Range> Properties;
internal Dictionary<uint, Row<MethodSemanticsAttributes, MetadataToken>> Semantics;
internal Dictionary<uint, Row<PInvokeAttributes, uint, uint>> PInvokes;
internal Dictionary<MetadataToken, Range []> GenericParameters;
internal Dictionary<uint, MetadataToken []> GenericConstraints;
static Dictionary<string, Row<ElementType, bool>> primitive_value_types;
static void InitializePrimitives ()
{
primitive_value_types = new Dictionary<string, Row<ElementType, bool>> (18, StringComparer.Ordinal) {
{ "Void", new Row<ElementType, bool> (ElementType.Void, false) },
{ "Boolean", new Row<ElementType, bool> (ElementType.Boolean, true) },
{ "Char", new Row<ElementType, bool> (ElementType.Char, true) },
{ "SByte", new Row<ElementType, bool> (ElementType.I1, true) },
{ "Byte", new Row<ElementType, bool> (ElementType.U1, true) },
{ "Int16", new Row<ElementType, bool> (ElementType.I2, true) },
{ "UInt16", new Row<ElementType, bool> (ElementType.U2, true) },
{ "Int32", new Row<ElementType, bool> (ElementType.I4, true) },
{ "UInt32", new Row<ElementType, bool> (ElementType.U4, true) },
{ "Int64", new Row<ElementType, bool> (ElementType.I8, true) },
{ "UInt64", new Row<ElementType, bool> (ElementType.U8, true) },
{ "Single", new Row<ElementType, bool> (ElementType.R4, true) },
{ "Double", new Row<ElementType, bool> (ElementType.R8, true) },
{ "String", new Row<ElementType, bool> (ElementType.String, false) },
{ "TypedReference", new Row<ElementType, bool> (ElementType.TypedByRef, false) },
{ "IntPtr", new Row<ElementType, bool> (ElementType.I, true) },
{ "UIntPtr", new Row<ElementType, bool> (ElementType.U, true) },
{ "Object", new Row<ElementType, bool> (ElementType.Object, false) },
};
}
public static void TryProcessPrimitiveTypeReference (TypeReference type)
{
if (type.Namespace != "System")
return;
var scope = type.scope;
if (scope == null || scope.MetadataScopeType != MetadataScopeType.AssemblyNameReference)
return;
Row<ElementType, bool> primitive_data;
if (!TryGetPrimitiveData (type, out primitive_data))
return;
type.etype = primitive_data.Col1;
type.IsValueType = primitive_data.Col2;
}
public static bool TryGetPrimitiveElementType (TypeDefinition type, out ElementType etype)
{
etype = ElementType.None;
if (type.Namespace != "System")
return false;
Row<ElementType, bool> primitive_data;
if (TryGetPrimitiveData (type, out primitive_data) && primitive_data.Col1.IsPrimitive ()) {
etype = primitive_data.Col1;
return true;
}
return false;
}
static bool TryGetPrimitiveData (TypeReference type, out Row<ElementType, bool> primitive_data)
{
if (primitive_value_types == null)
InitializePrimitives ();
return primitive_value_types.TryGetValue (type.Name, out primitive_data);
}
public void Clear ()
{
if (NestedTypes != null) NestedTypes.Clear ();
if (ReverseNestedTypes != null) ReverseNestedTypes.Clear ();
if (Interfaces != null) Interfaces.Clear ();
if (ClassLayouts != null) ClassLayouts.Clear ();
if (FieldLayouts != null) FieldLayouts.Clear ();
if (FieldRVAs != null) FieldRVAs.Clear ();
if (FieldMarshals != null) FieldMarshals.Clear ();
if (Constants != null) Constants.Clear ();
if (Overrides != null) Overrides.Clear ();
if (CustomAttributes != null) CustomAttributes.Clear ();
if (SecurityDeclarations != null) SecurityDeclarations.Clear ();
if (Events != null) Events.Clear ();
if (Properties != null) Properties.Clear ();
if (Semantics != null) Semantics.Clear ();
if (PInvokes != null) PInvokes.Clear ();
if (GenericParameters != null) GenericParameters.Clear ();
if (GenericConstraints != null) GenericConstraints.Clear ();
}
public TypeDefinition GetTypeDefinition (uint rid)
{
if (rid < 1 || rid > Types.Length)
return null;
return Types [rid - 1];
}
public void AddTypeDefinition (TypeDefinition type)
{
Types [type.token.RID - 1] = type;
}
public TypeReference GetTypeReference (uint rid)
{
if (rid < 1 || rid > TypeReferences.Length)
return null;
return TypeReferences [rid - 1];
}
public void AddTypeReference (TypeReference type)
{
TypeReferences [type.token.RID - 1] = type;
}
public FieldDefinition GetFieldDefinition (uint rid)
{
if (rid < 1 || rid > Fields.Length)
return null;
return Fields [rid - 1];
}
public void AddFieldDefinition (FieldDefinition field)
{
Fields [field.token.RID - 1] = field;
}
public MethodDefinition GetMethodDefinition (uint rid)
{
if (rid < 1 || rid > Methods.Length)
return null;
return Methods [rid - 1];
}
public void AddMethodDefinition (MethodDefinition method)
{
Methods [method.token.RID - 1] = method;
}
public MemberReference GetMemberReference (uint rid)
{
if (rid < 1 || rid > MemberReferences.Length)
return null;
return MemberReferences [rid - 1];
}
public void AddMemberReference (MemberReference member)
{
MemberReferences [member.token.RID - 1] = member;
}
public bool TryGetNestedTypeMapping (TypeDefinition type, out uint [] mapping)
{
return NestedTypes.TryGetValue (type.token.RID, out mapping);
}
public void SetNestedTypeMapping (uint type_rid, uint [] mapping)
{
NestedTypes [type_rid] = mapping;
}
public void RemoveNestedTypeMapping (TypeDefinition type)
{
NestedTypes.Remove (type.token.RID);
}
public bool TryGetReverseNestedTypeMapping (TypeDefinition type, out uint declaring)
{
return ReverseNestedTypes.TryGetValue (type.token.RID, out declaring);
}
public void SetReverseNestedTypeMapping (uint nested, uint declaring)
{
ReverseNestedTypes.Add (nested, declaring);
}
public void RemoveReverseNestedTypeMapping (TypeDefinition type)
{
ReverseNestedTypes.Remove (type.token.RID);
}
public bool TryGetInterfaceMapping (TypeDefinition type, out MetadataToken [] mapping)
{
return Interfaces.TryGetValue (type.token.RID, out mapping);
}
public void SetInterfaceMapping (uint type_rid, MetadataToken [] mapping)
{
Interfaces [type_rid] = mapping;
}
public void RemoveInterfaceMapping (TypeDefinition type)
{
Interfaces.Remove (type.token.RID);
}
public void AddPropertiesRange (uint type_rid, Range range)
{
Properties.Add (type_rid, range);
}
public bool TryGetPropertiesRange (TypeDefinition type, out Range range)
{
return Properties.TryGetValue (type.token.RID, out range);
}
public void RemovePropertiesRange (TypeDefinition type)
{
Properties.Remove (type.token.RID);
}
public void AddEventsRange (uint type_rid, Range range)
{
Events.Add (type_rid, range);
}
public bool TryGetEventsRange (TypeDefinition type, out Range range)
{
return Events.TryGetValue (type.token.RID, out range);
}
public void RemoveEventsRange (TypeDefinition type)
{
Events.Remove (type.token.RID);
}
public bool TryGetGenericParameterRanges (IGenericParameterProvider owner, out Range [] ranges)
{
return GenericParameters.TryGetValue (owner.MetadataToken, out ranges);
}
public void RemoveGenericParameterRange (IGenericParameterProvider owner)
{
GenericParameters.Remove (owner.MetadataToken);
}
public bool TryGetCustomAttributeRanges (ICustomAttributeProvider owner, out Range [] ranges)
{
return CustomAttributes.TryGetValue (owner.MetadataToken, out ranges);
}
public void RemoveCustomAttributeRange (ICustomAttributeProvider owner)
{
CustomAttributes.Remove (owner.MetadataToken);
}
public bool TryGetSecurityDeclarationRanges (ISecurityDeclarationProvider owner, out Range [] ranges)
{
return SecurityDeclarations.TryGetValue (owner.MetadataToken, out ranges);
}
public void RemoveSecurityDeclarationRange (ISecurityDeclarationProvider owner)
{
SecurityDeclarations.Remove (owner.MetadataToken);
}
public bool TryGetGenericConstraintMapping (GenericParameter generic_parameter, out MetadataToken [] mapping)
{
return GenericConstraints.TryGetValue (generic_parameter.token.RID, out mapping);
}
public void SetGenericConstraintMapping (uint gp_rid, MetadataToken [] mapping)
{
GenericConstraints [gp_rid] = mapping;
}
public void RemoveGenericConstraintMapping (GenericParameter generic_parameter)
{
GenericConstraints.Remove (generic_parameter.token.RID);
}
public bool TryGetOverrideMapping (MethodDefinition method, out MetadataToken [] mapping)
{
return Overrides.TryGetValue (method.token.RID, out mapping);
}
public void SetOverrideMapping (uint rid, MetadataToken [] mapping)
{
Overrides [rid] = mapping;
}
public void RemoveOverrideMapping (MethodDefinition method)
{
Overrides.Remove (method.token.RID);
}
public TypeDefinition GetFieldDeclaringType (uint field_rid)
{
return BinaryRangeSearch (Types, field_rid, true);
}
public TypeDefinition GetMethodDeclaringType (uint method_rid)
{
return BinaryRangeSearch (Types, method_rid, false);
}
static TypeDefinition BinaryRangeSearch (TypeDefinition [] types, uint rid, bool field)
{
int min = 0;
int max = types.Length - 1;
while (min <= max) {
int mid = min + ((max - min) / 2);
var type = types [mid];
var range = field ? type.fields_range : type.methods_range;
if (rid < range.Start)
max = mid - 1;
else if (rid >= range.Start + range.Length)
min = mid + 1;
else
return type;
}
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using CocosDenshion;
namespace Cocos2D
{
public delegate void CCBAnimationManagerDelegate(string name);
public class CCBAnimationManager
{
private Dictionary<CCNode, Dictionary<string, object>> _baseValues = new Dictionary<CCNode, Dictionary<string, object>>();
private readonly Dictionary<CCNode, Dictionary<int, Dictionary<string, CCBSequenceProperty>>> _nodeSequences =
new Dictionary<CCNode, Dictionary<int, Dictionary<string, CCBSequenceProperty>>>();
private List<CCBSequence> _sequences = new List<CCBSequence>();
private int _autoPlaySequenceId;
private CCBAnimationManagerDelegate _delegate;
private CCSize _rootContainerSize;
private CCNode _rootNode;
private CCBSequence _runningSequence;
private readonly List<string> _documentOutletNames = new List<string>();
private readonly List<CCNode> _documentOutletNodes = new List<CCNode>();
private readonly List<string> _documentCallbackNames = new List<string>();
private readonly List<CCNode> _documentCallbackNodes = new List<CCNode>();
private readonly List<string> _keyframeCallbacks = new List<string>();
private readonly Dictionary<string, CCAction> _keyframeCallFuncs = new Dictionary<string, CCAction>();
private string _documentControllerName;
private string _lastCompletedSequenceName;
private Action _animationCompleteCallbackFunc;
public bool _jsControlled;
public Object _owner;
public CCBAnimationManager()
{
Init();
}
public virtual bool Init()
{
return true;
}
public List<CCBSequence> Sequences
{
get { return _sequences; }
set { _sequences = value; }
}
public int AutoPlaySequenceId
{
set { _autoPlaySequenceId = value; }
get { return _autoPlaySequenceId; }
}
public CCNode RootNode
{
get { return _rootNode; }
set { _rootNode = value; }
}
public void AddDocumentCallbackNode(CCNode node)
{
_documentCallbackNodes.Add(node);
}
public void AddDocumentCallbackName(string name)
{
_documentCallbackNames.Add(name);
}
public void AddDocumentOutletNode(CCNode node)
{
_documentOutletNodes.Add(node);
}
public void AddDocumentOutletName(string name)
{
_documentOutletNames.Add(name);
}
public string DocumentControllerName
{
set { _documentControllerName = value; }
get { return _documentControllerName; }
}
public List<string> GetDocumentCallbackNames()
{
return _documentCallbackNames;
}
public List<CCNode> GetDocumentCallbackNodes()
{
return _documentCallbackNodes;
}
public List<string> GetDocumentOutletNames()
{
return _documentOutletNames;
}
public List<CCNode> GetDocumentOutletNodes()
{
return _documentOutletNodes;
}
public string GetLastCompletedSequenceName()
{
return _lastCompletedSequenceName;
}
public List<string> GetKeyframeCallbacks()
{
return _keyframeCallbacks;
}
public CCSize RootContainerSize
{
get { return _rootContainerSize; }
set { _rootContainerSize = value; }
}
public CCBAnimationManagerDelegate Delegate
{
get { return _delegate; }
set { _delegate = value; }
}
public string RunningSequenceName
{
get
{
if (_runningSequence != null)
{
return _runningSequence.Name;
}
return null;
}
}
public CCSize GetContainerSize(CCNode node)
{
if (node != null)
{
return node.ContentSize;
}
else
{
return _rootContainerSize;
}
}
public void AddNode(CCNode node, Dictionary<int, Dictionary<string, CCBSequenceProperty>> pSeq)
{
_nodeSequences.Add(node, pSeq);
}
public void SetBaseValue(object pValue, CCNode node, string pPropName)
{
Dictionary<string, object> props;
if (!_baseValues.TryGetValue(node, out props))
{
props = new Dictionary<string, object>();
_baseValues.Add(node, props);
}
props[pPropName] = pValue;
}
private object GetBaseValue(CCNode node, string pPropName)
{
return _baseValues[node][pPropName];
}
private int GetSequenceId(string pSequenceName)
{
for (int i = 0; i < _sequences.Count; i++)
{
if (_sequences[i].Name == pSequenceName)
{
return _sequences[i].SequenceId;
}
}
return -1;
}
private CCBSequence GetSequence(int nSequenceId)
{
for (int i = 0; i < _sequences.Count; i++)
{
if (_sequences[i].SequenceId == nSequenceId)
{
return _sequences[i];
}
}
return null;
}
public void MoveAnimationsFromNode(CCNode fromNode, CCNode toNode)
{
// Move base values
Dictionary<string, object> baseValue;
if (_baseValues.TryGetValue(fromNode, out baseValue))
{
_baseValues[toNode] = baseValue;
_baseValues.Remove(fromNode);
}
// Move seqs
Dictionary<int, Dictionary<string, CCBSequenceProperty>> seqs;
if (_nodeSequences.TryGetValue(fromNode, out seqs))
{
_nodeSequences[toNode] = seqs;
_nodeSequences.Remove(fromNode);
}
}
private CCActionInterval GetAction(CCBKeyframe pKeyframe0, CCBKeyframe pKeyframe1, string pPropName, CCNode node)
{
float duration = pKeyframe1.Time - (pKeyframe0 != null ? pKeyframe0.Time : 0);
switch (pPropName)
{
case "rotationX":
{
CCBValue value = (CCBValue) pKeyframe1.Value;
return new CCBRotateXTo(duration, value.GetFloatValue());
}
case "rotationY":
{
CCBValue value = (CCBValue) pKeyframe1.Value;
return new CCBRotateYTo(duration, value.GetFloatValue());
}
case "rotation":
{
var value = (CCBValue) pKeyframe1.Value;
return new CCBRotateTo(duration, value.GetFloatValue());
}
case "opacity":
{
var value = (CCBValue) pKeyframe1.Value;
return new CCFadeTo (duration, value.GetByteValue());
}
case "color":
{
var color = (CCColor3BWapper) pKeyframe1.Value;
CCColor3B c = color.Color;
return new CCTintTo (duration, c.R, c.G, c.B);
}
case "visible":
{
var value = (CCBValue) pKeyframe1.Value;
if (value.GetBoolValue())
{
return new CCSequence (new CCDelayTime (duration), new CCShow());
}
return new CCSequence (new CCDelayTime (duration), new CCHide());
}
case "displayFrame":
return new CCSequence (new CCDelayTime (duration), new CCBSetSpriteFrame((CCSpriteFrame) pKeyframe1.Value));
case "position":
{
// Get position type
var array = (List<CCBValue>) GetBaseValue(node, pPropName);
var type = (CCBPositionType) array[2].GetIntValue();
// Get relative position
var value = (List<CCBValue>) pKeyframe1.Value;
float x = value[0].GetFloatValue();
float y = value[1].GetFloatValue();
CCSize containerSize = GetContainerSize(node.Parent);
CCPoint absPos = CCBHelper.GetAbsolutePosition(new CCPoint(x, y), type, containerSize, pPropName);
return new CCMoveTo (duration, absPos);
}
case "scale":
{
// Get position type
var array = (List<CCBValue>) GetBaseValue(node, pPropName);
var type = (CCBScaleType) array[2].GetIntValue();
// Get relative scale
var value = (List<CCBValue>) pKeyframe1.Value;
float x = value[0].GetFloatValue();
float y = value[1].GetFloatValue();
if (type == CCBScaleType.MultiplyResolution)
{
float resolutionScale = CCBReader.ResolutionScale;
x *= resolutionScale;
y *= resolutionScale;
}
return new CCScaleTo(duration, x, y);
}
case "skew":
{
// Get relative skew
var value = (List<CCBValue>)pKeyframe1.Value;
float x = value[0].GetFloatValue();
float y = value[1].GetFloatValue();
return new CCSkewTo(duration, x, y);
}
default:
CCLog.Log("CCBReader: Failed to create animation for property: {0}", pPropName);
break;
}
return null;
}
private void SetAnimatedProperty(string pPropName, CCNode node, object pValue, float fTweenDuraion)
{
if (fTweenDuraion > 0)
{
// Create a fake keyframe to generate the action from
var kf1 = new CCBKeyframe();
kf1.Value = pValue;
kf1.Time = fTweenDuraion;
kf1.EasingType = CCBEasingType.Linear;
// Animate
CCActionInterval tweenAction = GetAction(null, kf1, pPropName, node);
node.RunAction(tweenAction);
}
else
{
// Just set the value
if (pPropName == "position")
{
// Get position type
var array = (List<CCBValue>) GetBaseValue(node, pPropName);
var type = (CCBPositionType) array[2].GetIntValue();
// Get relative position
var value = (List<CCBValue>) pValue;
float x = value[0].GetFloatValue();
float y = value[1].GetFloatValue();
node.Position = CCBHelper.GetAbsolutePosition(new CCPoint(x, y), type, GetContainerSize(node.Parent), pPropName);
}
else if (pPropName == "scale")
{
// Get scale type
var array = (List<CCBValue>) GetBaseValue(node, pPropName);
var type = (CCBScaleType) array[2].GetIntValue();
// Get relative scale
var value = (List<CCBValue>) pValue;
float x = value[0].GetFloatValue();
float y = value[1].GetFloatValue();
CCBHelper.SetRelativeScale(node, x, y, type, pPropName);
}
else if (pPropName == "skew")
{
// Get relative scale
var value = (List<CCBValue>)pValue;
float x = value[0].GetFloatValue();
float y = value[1].GetFloatValue();
node.SkewX = x;
node.SkewY = y;
}
else
{
// [node setValue:value forKey:name];
// TODO only handle rotation, opacity, displayFrame, color
if (pPropName == "rotation")
{
float rotate = ((CCBValue) pValue).GetFloatValue();
node.Rotation = rotate;
}
else if (pPropName == "rotationX")
{
float rotate = ((CCBValue)pValue).GetFloatValue();
node.RotationX = rotate;
}
else if (pPropName == "rotationY")
{
float rotate = ((CCBValue)pValue).GetFloatValue();
node.RotationY = rotate;
}
else if (pPropName == "opacity")
{
byte opacity = ((CCBValue) pValue).GetByteValue();
((ICCRGBAProtocol) node).Opacity = opacity;
}
else if (pPropName == "displayFrame")
{
((CCSprite) node).DisplayFrame = (CCSpriteFrame) pValue;
}
else if (pPropName == "color")
{
var color = (CCColor3BWapper) pValue;
((ICCRGBAProtocol) node).Color = color.Color;
}
else if (pPropName == "visible")
{
bool visible = ((CCBValue)pValue).GetBoolValue();
node.Visible = visible;
}
else
{
CCLog.Log("unsupported property name is {0}", pPropName);
Debug.Assert(false, "unsupported property now");
}
}
}
}
private void SetFirstFrame(CCNode node, CCBSequenceProperty pSeqProp, float fTweenDuration)
{
List<CCBKeyframe> keyframes = pSeqProp.Keyframes;
if (keyframes.Count == 0)
{
// Use base value (no animation)
object baseValue = GetBaseValue(node, pSeqProp.Name);
Debug.Assert(baseValue != null, "No baseValue found for property");
SetAnimatedProperty(pSeqProp.Name, node, baseValue, fTweenDuration);
}
else
{
// Use first keyframe
CCBKeyframe keyframe = keyframes[0];
SetAnimatedProperty(pSeqProp.Name, node, keyframe.Value, fTweenDuration);
}
}
private CCActionInterval GetEaseAction(CCActionInterval pAction, CCBEasingType nEasingTypeType, float fEasingOpt)
{
if (pAction is CCSequence)
{
return pAction;
}
switch (nEasingTypeType)
{
case CCBEasingType.Linear:
return pAction;
case CCBEasingType.Instant:
return new CCBEaseInstant(pAction);
case CCBEasingType.CubicIn:
return new CCEaseIn(pAction, fEasingOpt);
case CCBEasingType.CubicOut:
return new CCEaseOut(pAction, fEasingOpt);
case CCBEasingType.CubicInOut:
return new CCEaseInOut(pAction, fEasingOpt);
case CCBEasingType.BackIn:
return new CCEaseBackIn(pAction);
case CCBEasingType.BackOut:
return new CCEaseBackOut(pAction);
case CCBEasingType.BackInOut:
return new CCEaseBackInOut(pAction);
case CCBEasingType.BounceIn:
return new CCEaseBounceIn(pAction);
case CCBEasingType.BounceOut:
return new CCEaseBounceOut(pAction);
case CCBEasingType.BounceInOut:
return new CCEaseBounceInOut(pAction);
case CCBEasingType.ElasticIn:
return new CCEaseElasticIn(pAction, fEasingOpt);
case CCBEasingType.ElasticOut:
return new CCEaseElasticOut(pAction, fEasingOpt);
case CCBEasingType.ElasticInOut:
return new CCEaseElasticInOut(pAction, fEasingOpt);
default:
CCLog.Log("CCBReader: Unkown easing type {0}", nEasingTypeType);
return pAction;
}
}
public Object ActionForCallbackChannel(CCBSequenceProperty channel)
{
float lastKeyframeTime = 0;
var actions = new List<CCFiniteTimeAction>();
var keyframes = channel.Keyframes;
int numKeyframes = keyframes.Count;
for (int i = 0; i < numKeyframes; ++i)
{
CCBKeyframe keyframe = keyframes[i];
float timeSinceLastKeyframe = keyframe.Time - lastKeyframeTime;
lastKeyframeTime = keyframe.Time;
if (timeSinceLastKeyframe > 0)
{
actions.Add(new CCDelayTime(timeSinceLastKeyframe));
}
var keyVal = (List<CCBValue>)keyframe.Value;
string selectorName = keyVal[0].GetStringValue();
CCBTargetType selectorTarget =
(CCBTargetType) int.Parse(keyVal[1].GetStringValue());
if (_jsControlled)
{
string callbackName = string.Format("{0}:{1}", selectorTarget, selectorName);
CCCallFunc callback = (CCCallFunc) _keyframeCallFuncs[callbackName].Copy();
if (callback != null)
{
actions.Add(callback);
}
}
else
{
Object target = null;
if (selectorTarget == CCBTargetType.DocumentRoot)
target = _rootNode;
else if (selectorTarget == CCBTargetType.Owner)
target = _owner;
if (target != null)
{
if (selectorName.Length > 0)
{
Action<CCNode> selCallFunc = null;
ICCBSelectorResolver targetAsCCBSelectorResolver = target as ICCBSelectorResolver;
if (targetAsCCBSelectorResolver != null)
{
selCallFunc = targetAsCCBSelectorResolver.OnResolveCCBCCCallFuncSelector(target,
selectorName);
}
if (selCallFunc == null)
{
CCLog.Log("Skipping selector {0} since no CCBSelectorResolver is present.",
selectorName);
}
else
{
CCCallFuncN callback = new CCCallFuncN(selCallFunc);
actions.Add(callback);
}
}
else
{
CCLog.Log("Unexpected empty selector.");
}
}
}
}
if (actions.Capacity < 1) return null;
return new CCSequence(actions.ToArray());
}
public Object ActionForSoundChannel(CCBSequenceProperty channel)
{
float lastKeyframeTime = 0;
var actions = new List<CCFiniteTimeAction>();
var keyframes = channel.Keyframes;
int numKeyframes = keyframes.Count;
for (int i = 0; i < numKeyframes; ++i)
{
CCBKeyframe keyframe = keyframes[i];
float timeSinceLastKeyframe = keyframe.Time - lastKeyframeTime;
lastKeyframeTime = keyframe.Time;
if (timeSinceLastKeyframe > 0)
{
actions.Add(new CCDelayTime(timeSinceLastKeyframe));
}
var keyVal = (List<CCBValue>)keyframe.Value;
string soundFile = keyVal[0].GetStringValue();
float pitch, pan, gain;
pitch = float.Parse(keyVal[1].GetStringValue());
pan = float.Parse(keyVal[2].GetStringValue());
gain = float.Parse(keyVal[3].GetStringValue());
actions.Add(CCBSoundEffect.ActionWithSoundFile(soundFile, pitch, pan, gain));
}
if (actions.Count < 1) return null;
return new CCSequence(actions.ToArray());
}
private void RunAction(CCNode node, CCBSequenceProperty pSeqProp, float fTweenDuration)
{
List<CCBKeyframe> keyframes = pSeqProp.Keyframes;
int numKeyframes = keyframes.Count;
if (numKeyframes > 1)
{
// Make an animation!
var actions = new List<CCFiniteTimeAction>();
CCBKeyframe keyframeFirst = keyframes[0];
float timeFirst = keyframeFirst.Time + fTweenDuration;
if (timeFirst > 0)
{
actions.Add(new CCDelayTime (timeFirst));
}
for (int i = 0; i < numKeyframes - 1; ++i)
{
CCBKeyframe kf0 = keyframes[i];
CCBKeyframe kf1 = keyframes[i + 1];
CCActionInterval action = GetAction(kf0, kf1, pSeqProp.Name, node);
if (action != null)
{
// Apply easing
action = GetEaseAction(action, kf0.EasingType, kf0.EasingOpt);
actions.Add(action);
}
}
if (actions.Count > 1)
{
CCFiniteTimeAction seq = new CCSequence(actions.ToArray());
node.RunAction(seq);
}
else
{
node.RunAction(actions[0]);
}
}
}
public void RunAnimations(string pName, float fTweenDuration)
{
RunAnimationsForSequenceNamedTweenDuration(pName, fTweenDuration);
}
public void RunAnimations(string pName)
{
RunAnimationsForSequenceNamed(pName);
}
public void RunAnimations(int nSeqId, float fTweenDuraiton)
{
RunAnimationsForSequenceIdTweenDuration(nSeqId, fTweenDuraiton);
}
public void RunAnimationsForSequenceIdTweenDuration(int nSeqId, float fTweenDuration)
{
Debug.Assert(nSeqId != -1, "Sequence id couldn't be found");
_rootNode.StopAllActions();
foreach (var pElement in _nodeSequences)
{
CCNode node = pElement.Key;
node.StopAllActions();
// Refer to CCBReader::readKeyframe() for the real type of value
Dictionary<int, Dictionary<string, CCBSequenceProperty>> seqs = pElement.Value;
var seqNodePropNames = new List<string>();
Dictionary<string, CCBSequenceProperty> seqNodeProps;
if (seqs.TryGetValue(nSeqId, out seqNodeProps))
{
// Reset nodes that have sequence node properties, and run actions on them
foreach (var pElement1 in seqNodeProps)
{
string propName = pElement1.Key;
CCBSequenceProperty seqProp = pElement1.Value;
seqNodePropNames.Add(propName);
SetFirstFrame(node, seqProp, fTweenDuration);
RunAction(node, seqProp, fTweenDuration);
}
}
// Reset the nodes that may have been changed by other timelines
Dictionary<string, object> nodeBaseValues;
if (_baseValues.TryGetValue(node, out nodeBaseValues))
{
foreach (var pElement2 in nodeBaseValues)
{
if (!seqNodePropNames.Contains(pElement2.Key))
{
object value = pElement2.Value;
if (value != null)
{
SetAnimatedProperty(pElement2.Key, node, value, fTweenDuration);
}
}
}
}
}
// Make callback at end of sequence
CCBSequence seq = GetSequence(nSeqId);
CCAction completeAction = new CCSequence (
new CCDelayTime (seq.Duration + fTweenDuration),
new CCCallFunc(SequenceCompleted)
);
_rootNode.RunAction(completeAction);
// Set the running scene
if (seq.CallBackChannel != null)
{
CCAction action = (CCAction) ActionForCallbackChannel(seq.CallBackChannel);
if (action != null)
{
_rootNode.RunAction(action);
}
}
if (seq.SoundChannel != null)
{
CCAction action = (CCAction) ActionForSoundChannel(seq.SoundChannel);
if (action != null)
{
_rootNode.RunAction(action);
}
}
_runningSequence = GetSequence(nSeqId);
}
public void RunAnimationsForSequenceNamedTweenDuration(string pName, float fTweenDuration)
{
int seqId = GetSequenceId(pName);
RunAnimationsForSequenceIdTweenDuration(seqId, fTweenDuration);
}
public void RunAnimationsForSequenceNamed(string pName)
{
RunAnimationsForSequenceNamedTweenDuration(pName, 0);
}
public void SetAnimationCompletedCallback(Action callbackFunc)
{
_animationCompleteCallbackFunc = callbackFunc;
}
// Commented out for now as it does not seem to be used
//public void Debug()
//{
//}
public void SetCallFunc(CCAction callFunc, string callbackNamed)
{
_keyframeCallFuncs.Add(callbackNamed, callFunc);
}
private void SequenceCompleted()
{
string runningSequenceName = _runningSequence.Name;
int nextSeqId = _runningSequence.ChainedSequenceId;
_runningSequence = null;
if (_lastCompletedSequenceName != runningSequenceName)
{
_lastCompletedSequenceName = runningSequenceName;
}
if (_delegate != null)
{
_delegate(_runningSequence.Name);
}
if (_animationCompleteCallbackFunc != null)
{
_animationCompleteCallbackFunc();
}
if (nextSeqId != -1)
{
RunAnimations(nextSeqId, 0);
}
}
}
public class CCBSetSpriteFrame : CCActionInstant
{
private CCSpriteFrame _spriteFrame;
/** creates a Place action with a position */
public CCBSetSpriteFrame()
{
}
public CCBSetSpriteFrame(CCSpriteFrame pSpriteFrame)
{
InitWithSpriteFrame(pSpriteFrame);
}
protected virtual bool InitWithSpriteFrame(CCSpriteFrame pSpriteFrame)
{
_spriteFrame = pSpriteFrame;
return true;
}
public override void Update(float time)
{
((CCSprite) m_pTarget).DisplayFrame = _spriteFrame;
}
public override object Copy(ICCCopyable pZone)
{
CCBSetSpriteFrame pRet;
if (pZone != null)
{
pRet = (CCBSetSpriteFrame) (pZone);
}
else
{
pRet = new CCBSetSpriteFrame();
pZone = (pRet);
}
pRet.InitWithSpriteFrame(_spriteFrame);
base.Copy(pZone);
return pRet;
}
public override CCFiniteTimeAction Reverse()
{
return (CCFiniteTimeAction) this.Copy();
}
}
public class CCBSoundEffect : CCActionInstant
{
public static CCBSoundEffect ActionWithSoundFile(string file, float pitch, float pan, float gain)
{
CCBSoundEffect pRet = new CCBSoundEffect();
pRet.InitWithSoundFile(file, pitch, pan, gain);
return pRet;
}
public bool InitWithSoundFile(string file, float pitch, float pan, float gain)
{
_soundFile = file;
_pitch = pitch;
_pan = pan;
_gain = gain;
return true;
}
// Overrides
public override void Update(float time)
{
CCSimpleAudioEngine.SharedEngine.PlayEffect(_soundFile);
}
public override object Copy(ICCCopyable pZone)
{
CCBSoundEffect pRet;
if (pZone != null)
{
pRet = (CCBSoundEffect)(pZone);
}
else
{
pRet = new CCBSoundEffect();
pZone = (pRet);
}
pRet.InitWithSoundFile(_soundFile, _pitch, _pan, _gain);
base.Copy(pZone);
return pRet;
}
public override CCFiniteTimeAction Reverse()
{
return (CCFiniteTimeAction) this.Copy();
}
private string _soundFile;
private float _pitch, _pan, _gain;
}
public class CCBRotateTo : CCActionInterval
{
private float _diffAngle;
private float _dstAngle;
private float _startAngle;
public CCBRotateTo()
{
}
public CCBRotateTo(float fDuration, float fAngle) : base(fDuration)
{
InitWithDuration(fDuration, fAngle);
}
protected virtual bool InitWithDuration(float fDuration, float fAngle)
{
if (base.InitWithDuration(fDuration))
{
_dstAngle = fAngle;
return true;
}
return false;
}
public override void Update(float time)
{
m_pTarget.Rotation = _startAngle + (_diffAngle * time);
}
public override object Copy(ICCCopyable pZone)
{
CCBRotateTo pRet;
if (pZone != null)
{
pRet = (CCBRotateTo) (pZone);
}
else
{
pRet = new CCBRotateTo();
pZone = (pRet);
}
pRet.InitWithDuration(m_fDuration, _dstAngle);
base.Copy(pZone);
return pRet;
}
public override CCFiniteTimeAction Reverse()
{
Debug.Assert(false, "reverse() is not supported in CCBRotateTo");
return null;
}
protected internal override void StartWithTarget(CCNode node)
{
base.StartWithTarget(node);
_startAngle = m_pTarget.Rotation;
_diffAngle = _dstAngle - _startAngle;
}
}
public class CCBRotateXTo : CCActionInterval
{
public CCBRotateXTo()
{
}
public CCBRotateXTo(float fDuration, float fAngle)
{
InitWithDuration(fDuration, fAngle);
}
public bool InitWithDuration(float fDuration, float fAngle)
{
if (InitWithDuration(fDuration))
{
_dstAngle = fAngle;
return true;
}
return false;
}
// Overrides
protected internal override void StartWithTarget(CCNode target)
{
m_pOriginalTarget = target;
m_pTarget = target;
m_elapsed = 0.0f;
m_bFirstTick = true;
_startAngle = m_pTarget.RotationX;
_diffAngle = _dstAngle - _startAngle;
}
public override object Copy(ICCCopyable pZone)
{
CCBRotateXTo pRet;
if (pZone != null)
{
pRet = (CCBRotateXTo)(pZone);
}
else
{
pRet = new CCBRotateXTo();
pZone = (pRet);
}
pRet.InitWithDuration(m_fDuration, _dstAngle);
base.Copy(pZone);
return pRet;
}
public override CCFiniteTimeAction Reverse()
{
Debug.Assert(false, "reverse() is not supported in CCBRotateXTo");
return null;
}
public override void Update(float time)
{
m_pTarget.RotationX = _startAngle + (_diffAngle * time);
}
private float _startAngle;
private float _dstAngle;
private float _diffAngle;
}
public class CCBRotateYTo : CCActionInterval
{
public CCBRotateYTo()
{
}
public CCBRotateYTo(float fDuration, float fAngle)
{
InitWithDuration(fDuration, fAngle);
}
public bool InitWithDuration(float fDuration, float fAngle)
{
if (InitWithDuration(fDuration))
{
_dstAngle = fAngle;
return true;
}
return false;
}
// Overrides
protected internal override void StartWithTarget(CCNode target)
{
m_pOriginalTarget = target;
m_pTarget = target;
m_elapsed = 0.0f;
m_bFirstTick = true;
_startAngle = m_pTarget.RotationY;
_diffAngle = _dstAngle - _startAngle;
}
public override object Copy(ICCCopyable pZone)
{
CCBRotateYTo pRet;
if (pZone != null)
{
pRet = (CCBRotateYTo)(pZone);
}
else
{
pRet = new CCBRotateYTo();
pZone = (pRet);
}
pRet.InitWithDuration(m_fDuration, _dstAngle);
base.Copy(pZone);
return pRet;
}
public override CCFiniteTimeAction Reverse()
{
Debug.Assert(false, "reverse() is not supported in CCBRotateYTo");
return null;
}
public override void Update(float time)
{
m_pTarget.RotationY = _startAngle + (_diffAngle * time);
}
private float _startAngle;
private float _dstAngle;
private float _diffAngle;
}
class CCBEaseInstant : CCActionEase
{
public CCBEaseInstant()
{
}
public CCBEaseInstant(CCActionInterval pAction)
{
InitWithAction(pAction);
}
public override object Copy(ICCCopyable pZone)
{
CCBEaseInstant pRet;
if (pZone != null)
{
pRet = (CCBEaseInstant)(pZone);
}
else
{
pRet = new CCBEaseInstant();
pZone = (pRet);
}
pRet.InitWithAction(m_pInner);
base.Copy(pZone);
return pRet;
}
public override CCFiniteTimeAction Reverse()
{
return new CCBEaseInstant((CCActionInterval)m_pInner.Reverse());
}
public override void Update(float time)
{
if (time < 0)
{
m_pInner.Update(0);
}
else
{
m_pInner.Update(1);
}
}
}
}
| |
//------------------------------------------------------------------
//
// The following article discusses the mechanics behind this
// trackball implementation: http://viewport3d.com/trackball.htm
//
// Reading the article is not required to use this sample code,
// but skimming it might be useful.
//
// For licensing information and to get the latest version go to:
// http://workspaces.gotdotnet.com/3dtools
//
//------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Media3D;
namespace ModelViewer
{
/// <summary>
/// Trackball is a utility class which observes the mouse events
/// on a specified FrameworkElement and produces a Transform3D
/// with the resultant rotation and scale.
///
/// Example Usage:
///
/// Trackball trackball = new Trackball();
/// trackball.EventSource = myElement;
/// myViewport3D.Camera.Transform = trackball.Transform;
///
/// Because Viewport3Ds only raise events when the mouse is over the
/// rendered 3D geometry (as opposed to not when the mouse is within
/// the layout bounds) you usually want to use another element as
/// your EventSource. For example, a transparent border placed on
/// top of your Viewport3D works well:
///
/// <Grid>
/// <ColumnDefinition />
/// <RowDefinition />
/// <Viewport3D Name="myViewport" ClipToBounds="True" Grid.Row="0" Grid.Column="0" />
/// <Border Name="myElement" Background="Transparent" Grid.Row="0" Grid.Column="0" />
/// </Grid>
///
/// NOTE: The Transform property may be shared by multiple Cameras
/// if you want to have auxilary views following the trackball.
///
/// It can also be useful to share the Transform property with
/// models in the scene that you want to move with the camera.
/// (For example, the Trackport3D's headlight is implemented
/// this way.)
///
/// You may also use a Transform3DGroup to combine the
/// Transform property with additional Transforms.
/// </summary>
public class Trackball
{
private FrameworkElement _eventSource;
private Point _previousPosition2D;
private Vector3D _previousPosition3D = new Vector3D(0, 0, 1);
private Transform3DGroup _transform;
private ScaleTransform3D _scale = new ScaleTransform3D();
private AxisAngleRotation3D _rotation = new AxisAngleRotation3D();
private TranslateTransform3D _translate = new TranslateTransform3D();
public Trackball()
{
_transform = new Transform3DGroup();
_transform.Children.Add(_scale);
_transform.Children.Add(new RotateTransform3D(_rotation));
_transform.Children.Add(_translate);
}
/// <summary>
/// A transform to move the camera or scene to the trackball's
/// current orientation and scale.
/// </summary>
public Transform3D Transform
{
get { return _transform; }
}
#region Event Handling
/// <summary>
/// The FrameworkElement we listen to for mouse events.
/// </summary>
public FrameworkElement EventSource
{
get { return _eventSource; }
set
{
if (_eventSource != null)
{
_eventSource.MouseDown -= this.OnMouseDown;
_eventSource.MouseUp -= this.OnMouseUp;
_eventSource.MouseMove -= this.OnMouseMove;
}
_eventSource = value;
_eventSource.MouseDown += this.OnMouseDown;
_eventSource.MouseUp += this.OnMouseUp;
_eventSource.MouseMove += this.OnMouseMove;
}
}
private void OnMouseDown(object sender, MouseEventArgs e)
{
Mouse.Capture(EventSource, CaptureMode.Element);
_previousPosition2D = e.GetPosition(EventSource);
_previousPosition3D = ProjectToTrackball(
EventSource.ActualWidth,
EventSource.ActualHeight,
_previousPosition2D);
}
private void OnMouseUp(object sender, MouseEventArgs e)
{
Mouse.Capture(EventSource, CaptureMode.None);
}
private void OnMouseMove(object sender, MouseEventArgs e)
{
Point currentPosition = e.GetPosition(EventSource);
bool shiftDown = (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift));
if(e.LeftButton == MouseButtonState.Pressed && !shiftDown)
{
Look(currentPosition);
} else if(e.LeftButton == MouseButtonState.Pressed && shiftDown) {
Pan(currentPosition);
}
else if (e.RightButton == MouseButtonState.Pressed)
{
Zoom(currentPosition);
}
_previousPosition2D = currentPosition;
}
#endregion Event Handling
private void Look(Point currentPosition)
{
Vector3D currentPosition3D = ProjectToTrackball(
EventSource.ActualWidth, EventSource.ActualHeight, currentPosition);
Vector3D axis = Vector3D.CrossProduct(_previousPosition3D, currentPosition3D);
double angle = Vector3D.AngleBetween(_previousPosition3D, currentPosition3D);
Quaternion delta = new Quaternion(axis, -angle);
// Get the current orientantion from the RotateTransform3D
AxisAngleRotation3D r = _rotation;
Quaternion q = new Quaternion(_rotation.Axis, _rotation.Angle);
// Compose the delta with the previous orientation
q *= delta;
// Write the new orientation back to the Rotation3D
_rotation.Axis = q.Axis;
_rotation.Angle = q.Angle;
_previousPosition3D = currentPosition3D;
}
private void Pan(Point currentPosition)
{
Vector3D currentPosition3D = ProjectToTrackball(EventSource.ActualWidth, EventSource.ActualHeight, currentPosition);
Vector change = Point.Subtract(currentPosition, _previousPosition2D);
Vector3D changeVector = new Vector3D(change.X, change.Y, 0);
_translate.OffsetX += changeVector.X * .004;
_translate.OffsetY -= changeVector.Y * .004;
_translate.OffsetZ += changeVector.Z * .004;
_previousPosition3D = currentPosition3D;
}
private Vector3D ProjectToTrackball(double width, double height, Point point)
{
double x = point.X / (width / 2); // Scale so bounds map to [0,0] - [2,2]
double y = point.Y / (height / 2);
x = x - 1; // Translate 0,0 to the center
y = 1 - y; // Flip so +Y is up instead of down
double z2 = 1 - x * x - y * y; // z^2 = 1 - x^2 - y^2
double z = z2 > 0 ? Math.Sqrt(z2) : 0;
return new Vector3D(x, y, z);
}
private void Zoom(Point currentPosition)
{
double yDelta = currentPosition.Y - _previousPosition2D.Y;
double scale = Math.Exp(yDelta / 100); // e^(yDelta/100) is fairly arbitrary.
_scale.ScaleX *= scale;
_scale.ScaleY *= scale;
_scale.ScaleZ *= scale;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.