context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// 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 System.Threading;
using System.Diagnostics;
using System.IO;
using System.Collections.Specialized;
using System.Collections;
using System.Threading.Tasks;
using System.Globalization;
using System.Runtime.InteropServices;
namespace MICore
{
public class PipeTransport : StreamTransport
{
private Process _process;
private StreamReader _stdErrReader;
private int _remainingReaders;
private ManualResetEvent _allReadersDone = new ManualResetEvent(false);
private bool _killOnClose;
private bool _filterStderr;
private int _debuggerPid = -1;
private string _pipePath;
private string _cmdArgs;
public PipeTransport(bool killOnClose = false, bool filterStderr = false, bool filterStdout = false) : base(filterStdout)
{
_killOnClose = killOnClose;
_filterStderr = filterStderr;
}
public bool Interrupt(int pid)
{
if (_cmdArgs == null)
{
return false;
}
try
{
Process proc = new Process();
string killCmd = string.Format(CultureInfo.InvariantCulture, "kill -2 {0}", pid);
proc.StartInfo.FileName = _pipePath;
proc.StartInfo.Arguments = string.Format(CultureInfo.InvariantCulture, _cmdArgs, killCmd);
proc.StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(_pipePath);
proc.EnableRaisingEvents = false;
proc.StartInfo.RedirectStandardInput = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
AsyncReadFromStream(proc.StandardOutput, (s) => { if (!string.IsNullOrWhiteSpace(s)) this.Callback.OnStdOutLine(s); });
AsyncReadFromStream(proc.StandardError, (s) => { if (!string.IsNullOrWhiteSpace(s)) this.Callback.OnStdErrorLine(s); });
proc.WaitForExit();
if (proc.ExitCode != 0)
{
this.Callback.OnStdErrorLine(string.Format(CultureInfo.InvariantCulture, MICoreResources.Warn_ProcessExit, _pipePath, proc.ExitCode));
}
}
catch (Exception e)
{
this.Callback.OnStdErrorLine(string.Format(CultureInfo.InvariantCulture, MICoreResources.Warn_ProcessException, _pipePath, e.Message));
return false;
}
return true;
}
protected override string GetThreadName()
{
return "MI.PipeTransport";
}
/// <summary>
/// The value of this property reflects the pid for the debugger running
/// locally.
/// </summary>
public override int DebuggerPid
{
get
{
return _debuggerPid;
}
}
protected virtual void InitProcess(Process proc, out StreamReader stdout, out StreamWriter stdin)
{
_process = proc;
_process.EnableRaisingEvents = true;
_process.Exited += OnProcessExit;
_process.StartInfo.RedirectStandardInput = true;
_process.StartInfo.RedirectStandardOutput = true;
_process.StartInfo.RedirectStandardError = true;
_process.StartInfo.UseShellExecute = false;
_process.StartInfo.CreateNoWindow = true;
lock (_process)
{
this.Callback.AppendToInitializationLog(string.Format(CultureInfo.InvariantCulture, "Starting: \"{0}\" {1}", _process.StartInfo.FileName, _process.StartInfo.Arguments));
_process.Start();
_debuggerPid = _process.Id;
stdout = _process.StandardOutput;
stdin = _process.StandardInput;
_stdErrReader = _process.StandardError;
_remainingReaders = 2;
AsyncReadFromStdError();
}
}
public override void InitStreams(LaunchOptions options, out StreamReader reader, out StreamWriter writer)
{
PipeLaunchOptions pipeOptions = (PipeLaunchOptions)options;
_cmdArgs = pipeOptions.PipeCommandArguments;
Process proc = new Process();
_pipePath = pipeOptions.PipePath;
proc.StartInfo.FileName = pipeOptions.PipePath;
proc.StartInfo.Arguments = pipeOptions.PipeArguments;
proc.StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(pipeOptions.PipePath);
InitProcess(proc, out reader, out writer);
}
private void KillChildren(List<Tuple<int,int>> processes, int pid)
{
processes.ForEach((p) =>
{
if (p.Item2 == pid)
{
KillChildren(processes, p.Item1);
var k = Process.Start("/bin/kill", String.Format(CultureInfo.InvariantCulture, "-9 {0}", p.Item1));
k.WaitForExit();
}
});
}
private void KillProcess(Process p)
{
bool isLinux = PlatformUtilities.IsLinux();
bool isOSX = PlatformUtilities.IsOSX();
if (isLinux || isOSX)
{
// On linux run 'ps -x -o "%p %P"' (similarly on Mac), which generates a list of the process ids (%p) and parent process ids (%P).
// Using this list, issue a 'kill' command for each child process. Kill the children (recursively) to eliminate
// the entire process tree rooted at p.
Process ps = new Process();
ps.StartInfo.FileName ="/bin/ps";
ps.StartInfo.Arguments = isLinux ? "-x -o \"%p %P\"" : "-x -o \"pid ppid\"";
ps.StartInfo.RedirectStandardOutput = true;
ps.StartInfo.UseShellExecute = false;
ps.Start();
string line;
List<Tuple<int, int>> processAndParent = new List<Tuple<int, int>>();
char[] whitespace = new char[] { ' ', '\t' };
while ((line = ps.StandardOutput.ReadLine()) != null)
{
line = line.Trim();
int id, pid;
if (Int32.TryParse(line.Substring(0, line.IndexOfAny(whitespace)), NumberStyles.Integer, CultureInfo.InvariantCulture, out id)
&& Int32.TryParse(line.Substring(line.IndexOfAny(whitespace)).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out pid))
{
processAndParent.Add(new Tuple<int, int>(id, pid));
}
}
KillChildren(processAndParent, p.Id);
}
if (!p.HasExited)
{
p.Kill();
}
}
public override void Close()
{
if (_writer != null)
{
try
{
Echo("logout");
}
catch (Exception)
{
// Ignore errors if logout couldn't be written
}
}
base.Close();
if (_stdErrReader != null)
{
_stdErrReader.Dispose();
}
_allReadersDone.Set();
if (_process != null)
{
_process.EnableRaisingEvents = false;
_process.Exited -= OnProcessExit;
if (_killOnClose && !_process.HasExited)
{
try {
KillProcess(_process);
}
catch
{
}
}
_process.Dispose();
}
}
protected override void OnReadStreamAborted()
{
DecrementReaders();
try
{
if (_process.WaitForExit(1000))
{
// If the pipe process has already exited, or is just about to exit, we want to send the abort event from OnProcessExit
// instead of from here since that will have access to stderr
return;
}
}
catch (InvalidOperationException)
{
Debug.Assert(IsClosed);
return; // already closed
}
base.OnReadStreamAborted();
}
private async void AsyncReadFromStream(StreamReader stream, Action<string> lineHandler)
{
try
{
while (true)
{
string line = await stream.ReadLineAsync();
if (line == null)
break;
lineHandler(line);
}
}
catch (Exception)
{
// If anything goes wrong, don't crash VS
}
}
private async void AsyncReadFromStdError()
{
try
{
while (true)
{
string line = await _stdErrReader.ReadLineAsync();
if (line == null)
break;
if (_filterStderr)
{
line = FilterLine(line);
}
if (!string.IsNullOrWhiteSpace(line))
{
this.Callback.OnStdErrorLine(line);
}
}
}
catch (Exception)
{
// If anything goes wrong, don't crash VS
}
DecrementReaders();
}
/// <summary>
/// Called when either the stderr or the stdout reader exits. Used to synchronize between obtaining stderr/stdout content and the target process exiting.
/// </summary>
private void DecrementReaders()
{
if (Interlocked.Decrement(ref _remainingReaders) == 0)
{
_allReadersDone.Set();
}
}
private void OnProcessExit(object sender, EventArgs e)
{
// Wait until 'Init' gets a chance to set m_Reader/m_Writer before sending up the debugger exit event
if (_reader == null || _writer == null)
{
lock (_process)
{
if (_reader == null || _writer == null)
{
return; // something went wrong and these are still null, ignore process exit
}
}
}
// Wait for a bit to get all the stderr/stdout text. We can't wait too long on this since it is possble that
// this pipe might still be arround if the the process we started kicked off other processes that still have
// our pipe.
_allReadersDone.WaitOne(100);
if (!this.IsClosed)
{
// We are sometimes seeing m_process throw InvalidOperationExceptions by the time we get here.
// Attempt to get the real exit code, if we can't, still log the message with unknown exit code.
string exitCode = null;
try
{
exitCode = string.Format(CultureInfo.InvariantCulture, "{0} (0x{0:X})", _process.ExitCode);
}
catch (InvalidOperationException)
{
}
this.Callback.AppendToInitializationLog(string.Format(CultureInfo.InvariantCulture, "\"{0}\" exited with code {1}.", _process.StartInfo.FileName, exitCode ?? "???"));
try
{
this.Callback.OnDebuggerProcessExit(exitCode);
}
catch
{
// We have no exception back stop here, and we are trying to report failures. But if something goes wrong,
// lets not crash VS
}
}
}
}
}
| |
using System;
using Raksha.Crypto.Parameters;
using Raksha.Crypto.Utilities;
namespace Raksha.Crypto.Engines
{
/// <remarks>A class that provides a basic DES engine.</remarks>
public class DesEngine
: IBlockCipher
{
internal const int BLOCK_SIZE = 8;
private int[] workingKey;
public virtual int[] GetWorkingKey()
{
return workingKey;
}
/**
* initialise a DES cipher.
*
* @param forEncryption whether or not we are for encryption.
* @param parameters the parameters required to set up the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public virtual void Init(
bool forEncryption,
ICipherParameters parameters)
{
if (!(parameters is KeyParameter))
throw new ArgumentException("invalid parameter passed to DES init - " + parameters.GetType().ToString());
workingKey = GenerateWorkingKey(forEncryption, ((KeyParameter)parameters).GetKey());
}
public virtual string AlgorithmName
{
get { return "DES"; }
}
public bool IsPartialBlockOkay
{
get { return false; }
}
public virtual int GetBlockSize()
{
return BLOCK_SIZE;
}
public virtual int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
if (workingKey == null)
throw new InvalidOperationException("DES engine not initialised");
if ((inOff + BLOCK_SIZE) > input.Length)
throw new DataLengthException("input buffer too short");
if ((outOff + BLOCK_SIZE) > output.Length)
throw new DataLengthException("output buffer too short");
DesFunc(workingKey, input, inOff, output, outOff);
return BLOCK_SIZE;
}
public virtual void Reset()
{
}
/**
* what follows is mainly taken from "Applied Cryptography", by
* Bruce Schneier, however it also bears great resemblance to Richard
* Outerbridge's D3DES...
*/
// private static readonly short[] Df_Key =
// {
// 0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,
// 0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10,
// 0x89,0xab,0xcd,0xef,0x01,0x23,0x45,0x67
// };
private static readonly short[] bytebit =
{
128, 64, 32, 16, 8, 4, 2, 1
};
private static readonly int[] bigbyte =
{
0x800000, 0x400000, 0x200000, 0x100000,
0x80000, 0x40000, 0x20000, 0x10000,
0x8000, 0x4000, 0x2000, 0x1000,
0x800, 0x400, 0x200, 0x100,
0x80, 0x40, 0x20, 0x10,
0x8, 0x4, 0x2, 0x1
};
/*
* Use the key schedule specified in the Standard (ANSI X3.92-1981).
*/
private static readonly byte[] pc1 =
{
56, 48, 40, 32, 24, 16, 8, 0, 57, 49, 41, 33, 25, 17,
9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35,
62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21,
13, 5, 60, 52, 44, 36, 28, 20, 12, 4, 27, 19, 11, 3
};
private static readonly byte[] totrot =
{
1, 2, 4, 6, 8, 10, 12, 14,
15, 17, 19, 21, 23, 25, 27, 28
};
private static readonly byte[] pc2 =
{
13, 16, 10, 23, 0, 4, 2, 27, 14, 5, 20, 9,
22, 18, 11, 3, 25, 7, 15, 6, 26, 19, 12, 1,
40, 51, 30, 36, 46, 54, 29, 39, 50, 44, 32, 47,
43, 48, 38, 55, 33, 52, 45, 41, 49, 35, 28, 31
};
private static readonly uint[] SP1 =
{
0x01010400, 0x00000000, 0x00010000, 0x01010404,
0x01010004, 0x00010404, 0x00000004, 0x00010000,
0x00000400, 0x01010400, 0x01010404, 0x00000400,
0x01000404, 0x01010004, 0x01000000, 0x00000004,
0x00000404, 0x01000400, 0x01000400, 0x00010400,
0x00010400, 0x01010000, 0x01010000, 0x01000404,
0x00010004, 0x01000004, 0x01000004, 0x00010004,
0x00000000, 0x00000404, 0x00010404, 0x01000000,
0x00010000, 0x01010404, 0x00000004, 0x01010000,
0x01010400, 0x01000000, 0x01000000, 0x00000400,
0x01010004, 0x00010000, 0x00010400, 0x01000004,
0x00000400, 0x00000004, 0x01000404, 0x00010404,
0x01010404, 0x00010004, 0x01010000, 0x01000404,
0x01000004, 0x00000404, 0x00010404, 0x01010400,
0x00000404, 0x01000400, 0x01000400, 0x00000000,
0x00010004, 0x00010400, 0x00000000, 0x01010004
};
private static readonly uint[] SP2 =
{
0x80108020, 0x80008000, 0x00008000, 0x00108020,
0x00100000, 0x00000020, 0x80100020, 0x80008020,
0x80000020, 0x80108020, 0x80108000, 0x80000000,
0x80008000, 0x00100000, 0x00000020, 0x80100020,
0x00108000, 0x00100020, 0x80008020, 0x00000000,
0x80000000, 0x00008000, 0x00108020, 0x80100000,
0x00100020, 0x80000020, 0x00000000, 0x00108000,
0x00008020, 0x80108000, 0x80100000, 0x00008020,
0x00000000, 0x00108020, 0x80100020, 0x00100000,
0x80008020, 0x80100000, 0x80108000, 0x00008000,
0x80100000, 0x80008000, 0x00000020, 0x80108020,
0x00108020, 0x00000020, 0x00008000, 0x80000000,
0x00008020, 0x80108000, 0x00100000, 0x80000020,
0x00100020, 0x80008020, 0x80000020, 0x00100020,
0x00108000, 0x00000000, 0x80008000, 0x00008020,
0x80000000, 0x80100020, 0x80108020, 0x00108000
};
private static readonly uint[] SP3 =
{
0x00000208, 0x08020200, 0x00000000, 0x08020008,
0x08000200, 0x00000000, 0x00020208, 0x08000200,
0x00020008, 0x08000008, 0x08000008, 0x00020000,
0x08020208, 0x00020008, 0x08020000, 0x00000208,
0x08000000, 0x00000008, 0x08020200, 0x00000200,
0x00020200, 0x08020000, 0x08020008, 0x00020208,
0x08000208, 0x00020200, 0x00020000, 0x08000208,
0x00000008, 0x08020208, 0x00000200, 0x08000000,
0x08020200, 0x08000000, 0x00020008, 0x00000208,
0x00020000, 0x08020200, 0x08000200, 0x00000000,
0x00000200, 0x00020008, 0x08020208, 0x08000200,
0x08000008, 0x00000200, 0x00000000, 0x08020008,
0x08000208, 0x00020000, 0x08000000, 0x08020208,
0x00000008, 0x00020208, 0x00020200, 0x08000008,
0x08020000, 0x08000208, 0x00000208, 0x08020000,
0x00020208, 0x00000008, 0x08020008, 0x00020200
};
private static readonly uint[] SP4 =
{
0x00802001, 0x00002081, 0x00002081, 0x00000080,
0x00802080, 0x00800081, 0x00800001, 0x00002001,
0x00000000, 0x00802000, 0x00802000, 0x00802081,
0x00000081, 0x00000000, 0x00800080, 0x00800001,
0x00000001, 0x00002000, 0x00800000, 0x00802001,
0x00000080, 0x00800000, 0x00002001, 0x00002080,
0x00800081, 0x00000001, 0x00002080, 0x00800080,
0x00002000, 0x00802080, 0x00802081, 0x00000081,
0x00800080, 0x00800001, 0x00802000, 0x00802081,
0x00000081, 0x00000000, 0x00000000, 0x00802000,
0x00002080, 0x00800080, 0x00800081, 0x00000001,
0x00802001, 0x00002081, 0x00002081, 0x00000080,
0x00802081, 0x00000081, 0x00000001, 0x00002000,
0x00800001, 0x00002001, 0x00802080, 0x00800081,
0x00002001, 0x00002080, 0x00800000, 0x00802001,
0x00000080, 0x00800000, 0x00002000, 0x00802080
};
private static readonly uint[] SP5 =
{
0x00000100, 0x02080100, 0x02080000, 0x42000100,
0x00080000, 0x00000100, 0x40000000, 0x02080000,
0x40080100, 0x00080000, 0x02000100, 0x40080100,
0x42000100, 0x42080000, 0x00080100, 0x40000000,
0x02000000, 0x40080000, 0x40080000, 0x00000000,
0x40000100, 0x42080100, 0x42080100, 0x02000100,
0x42080000, 0x40000100, 0x00000000, 0x42000000,
0x02080100, 0x02000000, 0x42000000, 0x00080100,
0x00080000, 0x42000100, 0x00000100, 0x02000000,
0x40000000, 0x02080000, 0x42000100, 0x40080100,
0x02000100, 0x40000000, 0x42080000, 0x02080100,
0x40080100, 0x00000100, 0x02000000, 0x42080000,
0x42080100, 0x00080100, 0x42000000, 0x42080100,
0x02080000, 0x00000000, 0x40080000, 0x42000000,
0x00080100, 0x02000100, 0x40000100, 0x00080000,
0x00000000, 0x40080000, 0x02080100, 0x40000100
};
private static readonly uint[] SP6 =
{
0x20000010, 0x20400000, 0x00004000, 0x20404010,
0x20400000, 0x00000010, 0x20404010, 0x00400000,
0x20004000, 0x00404010, 0x00400000, 0x20000010,
0x00400010, 0x20004000, 0x20000000, 0x00004010,
0x00000000, 0x00400010, 0x20004010, 0x00004000,
0x00404000, 0x20004010, 0x00000010, 0x20400010,
0x20400010, 0x00000000, 0x00404010, 0x20404000,
0x00004010, 0x00404000, 0x20404000, 0x20000000,
0x20004000, 0x00000010, 0x20400010, 0x00404000,
0x20404010, 0x00400000, 0x00004010, 0x20000010,
0x00400000, 0x20004000, 0x20000000, 0x00004010,
0x20000010, 0x20404010, 0x00404000, 0x20400000,
0x00404010, 0x20404000, 0x00000000, 0x20400010,
0x00000010, 0x00004000, 0x20400000, 0x00404010,
0x00004000, 0x00400010, 0x20004010, 0x00000000,
0x20404000, 0x20000000, 0x00400010, 0x20004010
};
private static readonly uint[] SP7 =
{
0x00200000, 0x04200002, 0x04000802, 0x00000000,
0x00000800, 0x04000802, 0x00200802, 0x04200800,
0x04200802, 0x00200000, 0x00000000, 0x04000002,
0x00000002, 0x04000000, 0x04200002, 0x00000802,
0x04000800, 0x00200802, 0x00200002, 0x04000800,
0x04000002, 0x04200000, 0x04200800, 0x00200002,
0x04200000, 0x00000800, 0x00000802, 0x04200802,
0x00200800, 0x00000002, 0x04000000, 0x00200800,
0x04000000, 0x00200800, 0x00200000, 0x04000802,
0x04000802, 0x04200002, 0x04200002, 0x00000002,
0x00200002, 0x04000000, 0x04000800, 0x00200000,
0x04200800, 0x00000802, 0x00200802, 0x04200800,
0x00000802, 0x04000002, 0x04200802, 0x04200000,
0x00200800, 0x00000000, 0x00000002, 0x04200802,
0x00000000, 0x00200802, 0x04200000, 0x00000800,
0x04000002, 0x04000800, 0x00000800, 0x00200002
};
private static readonly uint[] SP8 =
{
0x10001040, 0x00001000, 0x00040000, 0x10041040,
0x10000000, 0x10001040, 0x00000040, 0x10000000,
0x00040040, 0x10040000, 0x10041040, 0x00041000,
0x10041000, 0x00041040, 0x00001000, 0x00000040,
0x10040000, 0x10000040, 0x10001000, 0x00001040,
0x00041000, 0x00040040, 0x10040040, 0x10041000,
0x00001040, 0x00000000, 0x00000000, 0x10040040,
0x10000040, 0x10001000, 0x00041040, 0x00040000,
0x00041040, 0x00040000, 0x10041000, 0x00001000,
0x00000040, 0x10040040, 0x00001000, 0x00041040,
0x10001000, 0x00000040, 0x10000040, 0x10040000,
0x10040040, 0x10000000, 0x00040000, 0x10001040,
0x00000000, 0x10041040, 0x00040040, 0x10000040,
0x10040000, 0x10001000, 0x10001040, 0x00000000,
0x10041040, 0x00041000, 0x00041000, 0x00001040,
0x00001040, 0x00040040, 0x10000000, 0x10041000
};
/**
* Generate an integer based working key based on our secret key
* and what we processing we are planning to do.
*
* Acknowledgements for this routine go to James Gillogly and Phil Karn.
* (whoever, and wherever they are!).
*/
protected static int[] GenerateWorkingKey(
bool encrypting,
byte[] key)
{
int[] newKey = new int[32];
bool[] pc1m = new bool[56];
bool[] pcr = new bool[56];
for (int j = 0; j < 56; j++ )
{
int l = pc1[j];
pc1m[j] = ((key[(uint) l >> 3] & bytebit[l & 07]) != 0);
}
for (int i = 0; i < 16; i++)
{
int l, m, n;
if (encrypting)
{
m = i << 1;
}
else
{
m = (15 - i) << 1;
}
n = m + 1;
newKey[m] = newKey[n] = 0;
for (int j = 0; j < 28; j++)
{
l = j + totrot[i];
if ( l < 28 )
{
pcr[j] = pc1m[l];
}
else
{
pcr[j] = pc1m[l - 28];
}
}
for (int j = 28; j < 56; j++)
{
l = j + totrot[i];
if (l < 56 )
{
pcr[j] = pc1m[l];
}
else
{
pcr[j] = pc1m[l - 28];
}
}
for (int j = 0; j < 24; j++)
{
if (pcr[pc2[j]])
{
newKey[m] |= bigbyte[j];
}
if (pcr[pc2[j + 24]])
{
newKey[n] |= bigbyte[j];
}
}
}
//
// store the processed key
//
for (int i = 0; i != 32; i += 2)
{
int i1, i2;
i1 = newKey[i];
i2 = newKey[i + 1];
newKey[i] = (int) ( (uint) ((i1 & 0x00fc0000) << 6) |
(uint) ((i1 & 0x00000fc0) << 10) |
((uint) (i2 & 0x00fc0000) >> 10) |
((uint) (i2 & 0x00000fc0) >> 6));
newKey[i + 1] = (int) ( (uint) ((i1 & 0x0003f000) << 12) |
(uint) ((i1 & 0x0000003f) << 16) |
((uint) (i2 & 0x0003f000) >> 4) |
(uint) (i2 & 0x0000003f));
}
return newKey;
}
/**
* the DES engine.
*/
internal static void DesFunc(
int[] wKey,
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
uint left = Pack.BE_To_UInt32(input, inOff);
uint right = Pack.BE_To_UInt32(input, inOff + 4);
uint work;
work = ((left >> 4) ^ right) & 0x0f0f0f0f;
right ^= work;
left ^= (work << 4);
work = ((left >> 16) ^ right) & 0x0000ffff;
right ^= work;
left ^= (work << 16);
work = ((right >> 2) ^ left) & 0x33333333;
left ^= work;
right ^= (work << 2);
work = ((right >> 8) ^ left) & 0x00ff00ff;
left ^= work;
right ^= (work << 8);
right = (right << 1) | (right >> 31);
work = (left ^ right) & 0xaaaaaaaa;
left ^= work;
right ^= work;
left = (left << 1) | (left >> 31);
for (int round = 0; round < 8; round++)
{
uint fval;
work = (right << 28) | (right >> 4);
work ^= (uint)wKey[round * 4 + 0];
fval = SP7[work & 0x3f];
fval |= SP5[(work >> 8) & 0x3f];
fval |= SP3[(work >> 16) & 0x3f];
fval |= SP1[(work >> 24) & 0x3f];
work = right ^ (uint)wKey[round * 4 + 1];
fval |= SP8[ work & 0x3f];
fval |= SP6[(work >> 8) & 0x3f];
fval |= SP4[(work >> 16) & 0x3f];
fval |= SP2[(work >> 24) & 0x3f];
left ^= fval;
work = (left << 28) | (left >> 4);
work ^= (uint)wKey[round * 4 + 2];
fval = SP7[ work & 0x3f];
fval |= SP5[(work >> 8) & 0x3f];
fval |= SP3[(work >> 16) & 0x3f];
fval |= SP1[(work >> 24) & 0x3f];
work = left ^ (uint)wKey[round * 4 + 3];
fval |= SP8[ work & 0x3f];
fval |= SP6[(work >> 8) & 0x3f];
fval |= SP4[(work >> 16) & 0x3f];
fval |= SP2[(work >> 24) & 0x3f];
right ^= fval;
}
right = (right << 31) | (right >> 1);
work = (left ^ right) & 0xaaaaaaaa;
left ^= work;
right ^= work;
left = (left << 31) | (left >> 1);
work = ((left >> 8) ^ right) & 0x00ff00ff;
right ^= work;
left ^= (work << 8);
work = ((left >> 2) ^ right) & 0x33333333;
right ^= work;
left ^= (work << 2);
work = ((right >> 16) ^ left) & 0x0000ffff;
left ^= work;
right ^= (work << 16);
work = ((right >> 4) ^ left) & 0x0f0f0f0f;
left ^= work;
right ^= (work << 4);
Pack.UInt32_To_BE(right, outBytes, outOff);
Pack.UInt32_To_BE(left, outBytes, outOff + 4);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Collections;
using System.ComponentModel;
using System.Globalization;
using System.Collections.Generic;
namespace System.Data
{
/// <summary>
/// Represents the collection of tables for the <see cref='System.Data.DataSet'/>.
/// </summary>
[DefaultEvent(nameof(CollectionChanged))]
[ListBindable(false)]
public sealed class DataTableCollection : InternalDataCollectionBase
{
private readonly DataSet _dataSet = null;
private readonly ArrayList _list = new ArrayList();
private int _defaultNameIndex = 1;
private DataTable[] _delayedAddRangeTables = null;
private CollectionChangeEventHandler _onCollectionChangedDelegate = null;
private CollectionChangeEventHandler _onCollectionChangingDelegate = null;
private static int s_objectTypeCount; // Bid counter
private readonly int _objectID = System.Threading.Interlocked.Increment(ref s_objectTypeCount);
/// <summary>
/// DataTableCollection constructor. Used only by DataSet.
/// </summary>
internal DataTableCollection(DataSet dataSet)
{
DataCommonEventSource.Log.Trace("<ds.DataTableCollection.DataTableCollection|INFO> {0}, dataSet={1}", ObjectID, (dataSet != null) ? dataSet.ObjectID : 0);
_dataSet = dataSet;
}
/// <summary>
/// Gets the tables in the collection as an object.
/// </summary>
protected override ArrayList List => _list;
internal int ObjectID => _objectID;
/// <summary>
/// Gets the table specified by its index.
/// </summary>
public DataTable this[int index]
{
get
{
try
{
// Perf: use the readonly _list field directly and let ArrayList check the range
return (DataTable)_list[index];
}
catch (ArgumentOutOfRangeException)
{
throw ExceptionBuilder.TableOutOfRange(index);
}
}
}
/// <summary>
/// Gets the table in the collection with the given name (not case-sensitive).
/// </summary>
public DataTable this[string name]
{
get
{
int index = InternalIndexOf(name);
if (index == -2)
{
throw ExceptionBuilder.CaseInsensitiveNameConflict(name);
}
if (index == -3)
{
throw ExceptionBuilder.NamespaceNameConflict(name);
}
return (index < 0) ? null : (DataTable)_list[index];
}
}
public DataTable this[string name, string tableNamespace]
{
get
{
if (tableNamespace == null)
{
throw ExceptionBuilder.ArgumentNull(nameof(tableNamespace));
}
int index = InternalIndexOf(name, tableNamespace);
if (index == -2)
{
throw ExceptionBuilder.CaseInsensitiveNameConflict(name);
}
return (index < 0) ? null : (DataTable)_list[index];
}
}
// Case-sensitive search in Schema, data and diffgram loading
internal DataTable GetTable(string name, string ns)
{
for (int i = 0; i < _list.Count; i++)
{
DataTable table = (DataTable)_list[i];
if (table.TableName == name && table.Namespace == ns)
{
return table;
}
}
return null;
}
// Case-sensitive smart search: it will look for a table using the ns only if required to
// resolve a conflict
internal DataTable GetTableSmart(string name, string ns)
{
int fCount = 0;
DataTable fTable = null;
for (int i = 0; i < _list.Count; i++)
{
DataTable table = (DataTable)_list[i];
if (table.TableName == name)
{
if (table.Namespace == ns)
{
return table;
}
fCount++;
fTable = table;
}
}
// if we get here we didn't match the namespace
// so return the table only if fCount==1 (it's the only one)
return (fCount == 1) ? fTable : null;
}
/// <summary>
/// Adds the specified table to the collection.
/// </summary>
public void Add(DataTable table)
{
long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataTableCollection.Add|API> {0}, table={1}", ObjectID, (table != null) ? table.ObjectID : 0);
try
{
OnCollectionChanging(new CollectionChangeEventArgs(CollectionChangeAction.Add, table));
BaseAdd(table);
ArrayAdd(table);
if (table.SetLocaleValue(_dataSet.Locale, false, false) ||
table.SetCaseSensitiveValue(_dataSet.CaseSensitive, false, false))
{
table.ResetIndexes();
}
OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, table));
}
finally
{
DataCommonEventSource.Log.ExitScope(logScopeId);
}
}
public void AddRange(DataTable[] tables)
{
long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataTableCollection.AddRange|API> {0}", ObjectID);
try
{
if (_dataSet._fInitInProgress)
{
_delayedAddRangeTables = tables;
return;
}
if (tables != null)
{
foreach (DataTable table in tables)
{
if (table != null)
{
Add(table);
}
}
}
}
finally
{
DataCommonEventSource.Log.ExitScope(logScopeId);
}
}
/// <summary>
/// Creates a table with the given name and adds it to the collection.
/// </summary>
public DataTable Add(string name)
{
DataTable table = new DataTable(name);
Add(table);
return table;
}
public DataTable Add(string name, string tableNamespace)
{
DataTable table = new DataTable(name, tableNamespace);
Add(table);
return table;
}
/// <summary>
/// Creates a new table with a default name and adds it to the collection.
/// </summary>
public DataTable Add()
{
DataTable table = new DataTable();
Add(table);
return table;
}
/// <summary>
/// Occurs when the collection is changed.
/// </summary>
public event CollectionChangeEventHandler CollectionChanged
{
add
{
DataCommonEventSource.Log.Trace("<ds.DataTableCollection.add_CollectionChanged|API> {0}", ObjectID);
_onCollectionChangedDelegate += value;
}
remove
{
DataCommonEventSource.Log.Trace("<ds.DataTableCollection.remove_CollectionChanged|API> {0}", ObjectID);
_onCollectionChangedDelegate -= value;
}
}
public event CollectionChangeEventHandler CollectionChanging
{
add
{
DataCommonEventSource.Log.Trace("<ds.DataTableCollection.add_CollectionChanging|API> {0}", ObjectID);
_onCollectionChangingDelegate += value;
}
remove
{
DataCommonEventSource.Log.Trace("<ds.DataTableCollection.remove_CollectionChanging|API> {0}", ObjectID);
_onCollectionChangingDelegate -= value;
}
}
private void ArrayAdd(DataTable table) => _list.Add(table);
/// <summary>
/// Creates a new default name.
/// </summary>
internal string AssignName()
{
string newName = null;
while (Contains(newName = MakeName(_defaultNameIndex)))
{
_defaultNameIndex++;
}
return newName;
}
/// <summary>
/// Does verification on the table and it's name, and points the table at the dataSet that owns this collection.
/// An ArgumentNullException is thrown if this table is null. An ArgumentException is thrown if this table
/// already belongs to this collection, belongs to another collection.
/// A DuplicateNameException is thrown if this collection already has a table with the same
/// name (case insensitive).
/// </summary>
private void BaseAdd(DataTable table)
{
if (table == null)
{
throw ExceptionBuilder.ArgumentNull(nameof(table));
}
if (table.DataSet == _dataSet)
{
throw ExceptionBuilder.TableAlreadyInTheDataSet();
}
if (table.DataSet != null)
{
throw ExceptionBuilder.TableAlreadyInOtherDataSet();
}
if (table.TableName.Length == 0)
{
table.TableName = AssignName();
}
else
{
if (NamesEqual(table.TableName, _dataSet.DataSetName, false, _dataSet.Locale) != 0 && !table._fNestedInDataset)
{
throw ExceptionBuilder.DatasetConflictingName(_dataSet.DataSetName);
}
RegisterName(table.TableName, table.Namespace);
}
table.SetDataSet(_dataSet);
//must run thru the document incorporating the addition of this data table
//must make sure there is no other schema component which have the same
// identity as this table (for example, there must not be a table with the
// same identity as a column in this schema.
}
/// <summary>
/// BaseGroupSwitch will intelligently remove and add tables from the collection.
/// </summary>
private void BaseGroupSwitch(DataTable[] oldArray, int oldLength, DataTable[] newArray, int newLength)
{
// We're doing a smart diff of oldArray and newArray to find out what
// should be removed. We'll pass through oldArray and see if it exists
// in newArray, and if not, do remove work. newBase is an opt. in case
// the arrays have similar prefixes.
int newBase = 0;
for (int oldCur = 0; oldCur < oldLength; oldCur++)
{
bool found = false;
for (int newCur = newBase; newCur < newLength; newCur++)
{
if (oldArray[oldCur] == newArray[newCur])
{
if (newBase == newCur)
{
newBase++;
}
found = true;
break;
}
}
if (!found)
{
// This means it's in oldArray and not newArray. Remove it.
if (oldArray[oldCur].DataSet == _dataSet)
{
BaseRemove(oldArray[oldCur]);
}
}
}
// Now, let's pass through news and those that don't belong, add them.
for (int newCur = 0; newCur < newLength; newCur++)
{
if (newArray[newCur].DataSet != _dataSet)
{
BaseAdd(newArray[newCur]);
_list.Add(newArray[newCur]);
}
}
}
/// <summary>
/// Does verification on the table and it's name, and clears the table's dataSet pointer.
/// An ArgumentNullException is thrown if this table is null. An ArgumentException is thrown
/// if this table doesn't belong to this collection or if this table is part of a relationship.
/// </summary>
private void BaseRemove(DataTable table)
{
if (CanRemove(table, true))
{
UnregisterName(table.TableName);
table.SetDataSet(null);
}
_list.Remove(table);
_dataSet.OnRemovedTable(table);
}
/// <summary>
/// Verifies if a given table can be removed from the collection.
/// </summary>
public bool CanRemove(DataTable table) => CanRemove(table, false);
internal bool CanRemove(DataTable table, bool fThrowException)
{
long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataTableCollection.CanRemove|INFO> {0}, table={1}, fThrowException={2}", ObjectID, (table != null) ? table.ObjectID : 0, fThrowException);
try
{
if (table == null)
{
if (!fThrowException)
{
return false;
}
throw ExceptionBuilder.ArgumentNull(nameof(table));
}
if (table.DataSet != _dataSet)
{
if (!fThrowException)
{
return false;
}
throw ExceptionBuilder.TableNotInTheDataSet(table.TableName);
}
// allow subclasses to throw.
_dataSet.OnRemoveTable(table);
if (table.ChildRelations.Count != 0 || table.ParentRelations.Count != 0)
{
if (!fThrowException)
{
return false;
}
throw ExceptionBuilder.TableInRelation();
}
for (ParentForeignKeyConstraintEnumerator constraints = new ParentForeignKeyConstraintEnumerator(_dataSet, table); constraints.GetNext();)
{
ForeignKeyConstraint constraint = constraints.GetForeignKeyConstraint();
if (constraint.Table == table && constraint.RelatedTable == table) // we can go with (constraint.Table == constraint.RelatedTable)
{
continue;
}
if (!fThrowException)
{
return false;
}
else
{
throw ExceptionBuilder.TableInConstraint(table, constraint);
}
}
for (ChildForeignKeyConstraintEnumerator constraints = new ChildForeignKeyConstraintEnumerator(_dataSet, table); constraints.GetNext();)
{
ForeignKeyConstraint constraint = constraints.GetForeignKeyConstraint();
if (constraint.Table == table && constraint.RelatedTable == table)
{
continue;
}
if (!fThrowException)
{
return false;
}
else
{
throw ExceptionBuilder.TableInConstraint(table, constraint);
}
}
return true;
}
finally
{
DataCommonEventSource.Log.ExitScope(logScopeId);
}
}
/// <summary>
/// Clears the collection of any tables.
/// </summary>
public void Clear()
{
long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataTableCollection.Clear|API> {0}", ObjectID);
try
{
int oldLength = _list.Count;
DataTable[] tables = new DataTable[_list.Count];
_list.CopyTo(tables, 0);
OnCollectionChanging(s_refreshEventArgs);
if (_dataSet._fInitInProgress && _delayedAddRangeTables != null)
{
_delayedAddRangeTables = null;
}
BaseGroupSwitch(tables, oldLength, null, 0);
_list.Clear();
OnCollectionChanged(s_refreshEventArgs);
}
finally
{
DataCommonEventSource.Log.ExitScope(logScopeId);
}
}
/// <summary>
/// Checks if a table, specified by name, exists in the collection.
/// </summary>
public bool Contains(string name) => (InternalIndexOf(name) >= 0);
public bool Contains(string name, string tableNamespace)
{
if (name == null)
{
throw ExceptionBuilder.ArgumentNull(nameof(name));
}
if (tableNamespace == null)
{
throw ExceptionBuilder.ArgumentNull(nameof(tableNamespace));
}
return (InternalIndexOf(name, tableNamespace) >= 0);
}
internal bool Contains(string name, string tableNamespace, bool checkProperty, bool caseSensitive)
{
if (!caseSensitive)
{
return (InternalIndexOf(name) >= 0);
}
// Case-Sensitive compare
int count = _list.Count;
for (int i = 0; i < count; i++)
{
DataTable table = (DataTable)_list[i];
// this may be needed to check wether the cascading is creating some conflicts
string ns = checkProperty ? table.Namespace : table._tableNamespace;
if (NamesEqual(table.TableName, name, true, _dataSet.Locale) == 1 && (ns == tableNamespace))
{
return true;
}
}
return false;
}
internal bool Contains(string name, bool caseSensitive)
{
if (!caseSensitive)
{
return (InternalIndexOf(name) >= 0);
}
// Case-Sensitive compare
int count = _list.Count;
for (int i = 0; i < count; i++)
{
DataTable table = (DataTable)_list[i];
if (NamesEqual(table.TableName, name, true, _dataSet.Locale) == 1)
{
return true;
}
}
return false;
}
public void CopyTo(DataTable[] array, int index)
{
if (array == null)
{
throw ExceptionBuilder.ArgumentNull(nameof(array));
}
if (index < 0)
{
throw ExceptionBuilder.ArgumentOutOfRange(nameof(index));
}
if (array.Length - index < _list.Count)
{
throw ExceptionBuilder.InvalidOffsetLength();
}
for (int i = 0; i < _list.Count; ++i)
{
array[index + i] = (DataTable)_list[i];
}
}
/// <summary>
/// Returns the index of a specified <see cref='System.Data.DataTable'/>.
/// </summary>
public int IndexOf(DataTable table)
{
int tableCount = _list.Count;
for (int i = 0; i < tableCount; ++i)
{
if (table == (DataTable)_list[i])
{
return i;
}
}
return -1;
}
/// <summary>
/// Returns the index of the
/// table with the given name (case insensitive), or -1 if the table
/// doesn't exist in the collection.
/// </summary>
public int IndexOf(string tableName)
{
int index = InternalIndexOf(tableName);
return (index < 0) ? -1 : index;
}
public int IndexOf(string tableName, string tableNamespace) => IndexOf(tableName, tableNamespace, true);
internal int IndexOf(string tableName, string tableNamespace, bool chekforNull)
{
// this should be public! why it is missing?
if (chekforNull)
{
if (tableName == null)
{
throw ExceptionBuilder.ArgumentNull(nameof(tableName));
}
if (tableNamespace == null)
{
throw ExceptionBuilder.ArgumentNull(nameof(tableNamespace));
}
}
int index = InternalIndexOf(tableName, tableNamespace);
return (index < 0) ? -1 : index;
}
internal void ReplaceFromInference(List<DataTable> tableList)
{
Debug.Assert(_list.Count == tableList.Count, "Both lists should have equal numbers of tables");
_list.Clear();
_list.AddRange(tableList);
}
// Return value:
// >= 0: find the match
// -1: No match
// -2: At least two matches with different cases
// -3: At least two matches with different namespaces
internal int InternalIndexOf(string tableName)
{
int cachedI = -1;
if ((null != tableName) && (0 < tableName.Length))
{
int count = _list.Count;
int result = 0;
for (int i = 0; i < count; i++)
{
DataTable table = (DataTable)_list[i];
result = NamesEqual(table.TableName, tableName, false, _dataSet.Locale);
if (result == 1)
{
// ok, we have found a table with the same name.
// let's see if there are any others with the same name
// if any let's return (-3) otherwise...
for (int j = i + 1; j < count; j++)
{
DataTable dupTable = (DataTable)_list[j];
if (NamesEqual(dupTable.TableName, tableName, false, _dataSet.Locale) == 1)
return -3;
}
//... let's just return i
return i;
}
if (result == -1)
cachedI = (cachedI == -1) ? i : -2;
}
}
return cachedI;
}
// Return value:
// >= 0: find the match
// -1: No match
// -2: At least two matches with different cases
internal int InternalIndexOf(string tableName, string tableNamespace)
{
int cachedI = -1;
if ((null != tableName) && (0 < tableName.Length))
{
int count = _list.Count;
int result = 0;
for (int i = 0; i < count; i++)
{
DataTable table = (DataTable)_list[i];
result = NamesEqual(table.TableName, tableName, false, _dataSet.Locale);
if ((result == 1) && (table.Namespace == tableNamespace))
return i;
if ((result == -1) && (table.Namespace == tableNamespace))
cachedI = (cachedI == -1) ? i : -2;
}
}
return cachedI;
}
internal void FinishInitCollection()
{
if (_delayedAddRangeTables != null)
{
foreach (DataTable table in _delayedAddRangeTables)
{
if (table != null)
{
Add(table);
}
}
_delayedAddRangeTables = null;
}
}
/// <summary>
/// Makes a default name with the given index. e.g. Table1, Table2, ... Tablei
/// </summary>
private string MakeName(int index) => 1 == index ?
"Table1" :
"Table" + index.ToString(System.Globalization.CultureInfo.InvariantCulture);
/// <summary>
/// Raises the <see cref='System.Data.DataTableCollection.OnCollectionChanged'/> event.
/// </summary>
private void OnCollectionChanged(CollectionChangeEventArgs ccevent)
{
if (_onCollectionChangedDelegate != null)
{
DataCommonEventSource.Log.Trace("<ds.DataTableCollection.OnCollectionChanged|INFO> {0}", ObjectID);
_onCollectionChangedDelegate(this, ccevent);
}
}
private void OnCollectionChanging(CollectionChangeEventArgs ccevent)
{
if (_onCollectionChangingDelegate != null)
{
DataCommonEventSource.Log.Trace("<ds.DataTableCollection.OnCollectionChanging|INFO> {0}", ObjectID);
_onCollectionChangingDelegate(this, ccevent);
}
}
/// <summary>
/// Registers this name as being used in the collection. Will throw an ArgumentException
/// if the name is already being used. Called by Add, All property, and Table.TableName property.
/// if the name is equivalent to the next default name to hand out, we increment our defaultNameIndex.
/// </summary>
internal void RegisterName(string name, string tbNamespace)
{
DataCommonEventSource.Log.Trace("<ds.DataTableCollection.RegisterName|INFO> {0}, name='{1}', tbNamespace='{2}'", ObjectID, name, tbNamespace);
Debug.Assert(name != null);
CultureInfo locale = _dataSet.Locale;
int tableCount = _list.Count;
for (int i = 0; i < tableCount; i++)
{
DataTable table = (DataTable)_list[i];
if (NamesEqual(name, table.TableName, true, locale) != 0 && (tbNamespace == table.Namespace))
{
throw ExceptionBuilder.DuplicateTableName(((DataTable)_list[i]).TableName);
}
}
if (NamesEqual(name, MakeName(_defaultNameIndex), true, locale) != 0)
{
_defaultNameIndex++;
}
}
/// <summary>
/// Removes the specified table from the collection.
/// </summary>
public void Remove(DataTable table)
{
long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataTableCollection.Remove|API> {0}, table={1}", ObjectID, (table != null) ? table.ObjectID : 0);
try
{
OnCollectionChanging(new CollectionChangeEventArgs(CollectionChangeAction.Remove, table));
BaseRemove(table);
OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, table));
}
finally
{
DataCommonEventSource.Log.ExitScope(logScopeId);
}
}
/// <summary>
/// Removes the table at the given index from the collection
/// </summary>
public void RemoveAt(int index)
{
long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataTableCollection.RemoveAt|API> {0}, index={1}", ObjectID, index);
try
{
DataTable dt = this[index];
if (dt == null)
{
throw ExceptionBuilder.TableOutOfRange(index);
}
Remove(dt);
}
finally
{
DataCommonEventSource.Log.ExitScope(logScopeId);
}
}
/// <summary>
/// Removes the table with a specified name from the collection.
/// </summary>
public void Remove(string name)
{
long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataTableCollection.Remove|API> {0}, name='{1}'", ObjectID, name);
try
{
DataTable dt = this[name];
if (dt == null)
{
throw ExceptionBuilder.TableNotInTheDataSet(name);
}
Remove(dt);
}
finally
{
DataCommonEventSource.Log.ExitScope(logScopeId);
}
}
public void Remove(string name, string tableNamespace)
{
if (name == null)
{
throw ExceptionBuilder.ArgumentNull(nameof(name));
}
if (tableNamespace == null)
{
throw ExceptionBuilder.ArgumentNull(nameof(tableNamespace));
}
DataTable dt = this[name, tableNamespace];
if (dt == null)
{
throw ExceptionBuilder.TableNotInTheDataSet(name);
}
Remove(dt);
}
/// <summary>
/// Unregisters this name as no longer being used in the collection. Called by Remove, All property, and
/// Table.TableName property. If the name is equivalent to the last proposed default name, we walk backwards
/// to find the next proper default name to use.
/// </summary>
internal void UnregisterName(string name)
{
DataCommonEventSource.Log.Trace("<ds.DataTableCollection.UnregisterName|INFO> {0}, name='{1}'", ObjectID, name);
if (NamesEqual(name, MakeName(_defaultNameIndex - 1), true, _dataSet.Locale) != 0)
{
do
{
_defaultNameIndex--;
} while (_defaultNameIndex > 1 && !Contains(MakeName(_defaultNameIndex - 1)));
}
}
}
}
| |
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Moq.Properties;
namespace Moq
{
// These methods are intended to create more readable string representations for use in failure messages.
partial class StringBuilderExtensions
{
public static StringBuilder AppendExpression(this StringBuilder builder, Expression expression)
{
if (expression == null)
{
return builder.Append("null");
}
switch (expression.NodeType)
{
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.Not:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.ArrayLength:
case ExpressionType.Quote:
case ExpressionType.TypeAs:
return builder.AppendExpression((UnaryExpression)expression);
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.AddAssign:
case ExpressionType.Assign:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
case ExpressionType.SubtractAssign:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.And:
case ExpressionType.AndAlso:
case ExpressionType.Or:
case ExpressionType.OrElse:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.Equal:
case ExpressionType.NotEqual:
case ExpressionType.Coalesce:
case ExpressionType.ArrayIndex:
case ExpressionType.RightShift:
case ExpressionType.LeftShift:
case ExpressionType.ExclusiveOr:
return builder.AppendExpression((BinaryExpression)expression);
case ExpressionType.TypeIs:
return builder.AppendExpression((TypeBinaryExpression)expression);
case ExpressionType.Conditional:
return builder.AppendExpression((ConditionalExpression)expression);
case ExpressionType.Constant:
return builder.AppendValueOf(((ConstantExpression)expression).Value);
case ExpressionType.Parameter:
return builder.AppendExpression((ParameterExpression)expression);
case ExpressionType.MemberAccess:
return builder.AppendExpression((MemberExpression)expression);
case ExpressionType.Call:
return builder.AppendExpression((MethodCallExpression)expression);
case ExpressionType.Index:
return builder.AppendExpression((IndexExpression)expression);
case ExpressionType.Lambda:
return builder.AppendExpression((LambdaExpression)expression);
case ExpressionType.New:
return builder.AppendExpression((NewExpression)expression);
case ExpressionType.NewArrayInit:
case ExpressionType.NewArrayBounds:
return builder.AppendExpression((NewArrayExpression)expression);
case ExpressionType.Invoke:
return builder.AppendExpression((InvocationExpression)expression);
case ExpressionType.MemberInit:
return builder.AppendExpression((MemberInitExpression)expression);
case ExpressionType.ListInit:
return builder.AppendExpression((ListInitExpression)expression);
case ExpressionType.Extension:
if (expression is MatchExpression me)
{
return builder.AppendExpression(me);
}
goto default;
default:
throw new Exception(string.Format(Resources.UnhandledExpressionType, expression.NodeType));
}
}
private static StringBuilder AppendElementInit(this StringBuilder builder, ElementInit initializer)
{
return builder.AppendCommaSeparated("{ ", initializer.Arguments, AppendExpression, " }");
}
private static StringBuilder AppendExpression(this StringBuilder builder, UnaryExpression expression)
{
switch (expression.NodeType)
{
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
return builder.Append('(')
.AppendNameOf(expression.Type)
.Append(')')
.AppendExpression(expression.Operand);
case ExpressionType.ArrayLength:
return builder.AppendExpression(expression.Operand)
.Append(".Length");
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
return builder.Append('-')
.AppendExpression(expression.Operand);
case ExpressionType.Not:
return builder.Append("!(")
.AppendExpression(expression.Operand)
.Append(')');
case ExpressionType.Quote:
return builder.AppendExpression(expression.Operand);
case ExpressionType.TypeAs:
return builder.Append('(')
.AppendExpression(expression.Operand)
.Append(" as ")
.AppendNameOf(expression.Type)
.Append(')');
}
return builder; // TODO: check whether this should be unreachable
}
private static StringBuilder AppendExpression(this StringBuilder builder, BinaryExpression expression)
{
if (expression.NodeType == ExpressionType.ArrayIndex)
{
builder.AppendExpression(expression.Left)
.Append('[')
.AppendExpression(expression.Right)
.Append(']');
}
else
{
AppendMaybeParenthesized(expression.Left, builder);
builder.Append(' ')
.Append(GetOperator(expression.NodeType))
.Append(' ');
AppendMaybeParenthesized(expression.Right, builder);
}
return builder;
void AppendMaybeParenthesized(Expression operand, StringBuilder b)
{
bool parenthesize = operand.NodeType == ExpressionType.AndAlso || operand.NodeType == ExpressionType.OrElse;
if (parenthesize)
{
b.Append("(");
}
b.AppendExpression(operand);
if (parenthesize)
{
b.Append(")");
}
}
string GetOperator(ExpressionType nodeType)
{
return nodeType switch
{
ExpressionType.Add => "+",
ExpressionType.AddChecked => "+",
ExpressionType.AddAssign => "+=",
ExpressionType.Assign => "=",
ExpressionType.And => "&",
ExpressionType.AndAlso => "&&",
ExpressionType.Coalesce => "??",
ExpressionType.Divide => "/",
ExpressionType.Equal => "==",
ExpressionType.ExclusiveOr => "^",
ExpressionType.GreaterThan => ">",
ExpressionType.GreaterThanOrEqual => ">=",
ExpressionType.LeftShift => "<<",
ExpressionType.LessThan => "<",
ExpressionType.LessThanOrEqual => "<=",
ExpressionType.Modulo => "%",
ExpressionType.Multiply => "*",
ExpressionType.MultiplyChecked => "*",
ExpressionType.NotEqual => "!=",
ExpressionType.Or => "|",
ExpressionType.OrElse => "||",
ExpressionType.Power => "**",
ExpressionType.RightShift => ">>",
ExpressionType.Subtract => "-",
ExpressionType.SubtractChecked => "-",
ExpressionType.SubtractAssign => "-=",
_ => nodeType.ToString(),
};
}
}
private static StringBuilder AppendExpression(this StringBuilder builder, TypeBinaryExpression expression)
{
return builder.AppendExpression(expression.Expression)
.Append(" is ")
.AppendNameOf(expression.TypeOperand);
}
private static StringBuilder AppendExpression(this StringBuilder builder, ConditionalExpression expression)
{
return builder.AppendExpression(expression.Test)
.Append(" ? ")
.AppendExpression(expression.IfTrue)
.Append(" : ")
.AppendExpression(expression.IfFalse);
}
private static StringBuilder AppendExpression(this StringBuilder builder, ParameterExpression expression)
{
return builder.Append(expression.Name ?? "<param>");
}
private static StringBuilder AppendExpression(this StringBuilder builder, MemberExpression expression)
{
if (expression.Expression != null)
{
builder.AppendExpression(expression.Expression);
}
else
{
builder.AppendNameOf(expression.Member.DeclaringType);
}
return builder.Append('.')
.Append(expression.Member.Name);
}
private static StringBuilder AppendExpression(this StringBuilder builder, MethodCallExpression expression)
{
var instance = expression.Object;
var method = expression.Method;
var arguments = (IEnumerable<Expression>)expression.Arguments;
if (method.IsExtensionMethod())
{
instance = arguments.First();
arguments = arguments.Skip(1);
}
if (instance != null)
{
builder.AppendExpression(instance);
}
else
{
Debug.Assert(method.IsStatic);
builder.AppendNameOf(method.DeclaringType);
}
if (method.IsGetAccessor())
{
if (method.IsPropertyAccessor())
{
builder.Append('.')
.Append(method.Name, 4);
}
else
{
Debug.Assert(method.IsIndexerAccessor());
builder.AppendCommaSeparated("[", arguments, AppendExpression, "]");
}
}
else if (method.IsSetAccessor())
{
if (method.IsPropertyAccessor())
{
builder.Append('.')
.Append(method.Name, 4)
.Append(" = ")
.AppendExpression(arguments.Last());
}
else
{
Debug.Assert(method.IsIndexerAccessor());
builder.AppendCommaSeparated("[", arguments.Take(arguments.Count() - 1), AppendExpression, "] = ")
.AppendExpression(arguments.Last());
}
}
else if (method.IsEventAddAccessor())
{
builder.Append('.')
.Append(method.Name, 4)
.Append(" += ")
.AppendCommaSeparated(arguments, AppendExpression);
}
else if (method.IsEventRemoveAccessor())
{
builder.Append('.')
.Append(method.Name, 7)
.Append(" -= ")
.AppendCommaSeparated(arguments, AppendExpression);
}
else
{
builder.Append('.')
.AppendNameOf(method, includeGenericArgumentList: true)
.AppendCommaSeparated("(", arguments, AppendExpression, ")");
}
return builder;
}
private static StringBuilder AppendExpression(this StringBuilder builder, IndexExpression expression)
{
return builder.AppendExpression(expression.Object)
.AppendCommaSeparated("[", expression.Arguments, AppendExpression, "]");
}
private static StringBuilder AppendExpression(this StringBuilder builder, LambdaExpression expression)
{
if (expression.Parameters.Count == 1)
{
builder.AppendExpression(expression.Parameters[0]);
}
else
{
builder.AppendCommaSeparated("(", expression.Parameters, AppendExpression, ")");
}
return builder.Append(" => ")
.AppendExpression(expression.Body);
}
private static StringBuilder AppendExpression(this StringBuilder builder, NewExpression expression)
{
Type type = (expression.Constructor == null) ? expression.Type : expression.Constructor.DeclaringType;
return builder.Append("new ")
.AppendNameOf(type)
.AppendCommaSeparated("(", expression.Arguments, AppendExpression, ")");
}
private static StringBuilder AppendExpression(this StringBuilder builder, NewArrayExpression expression)
{
switch (expression.NodeType)
{
case ExpressionType.NewArrayInit:
return builder.AppendCommaSeparated("new[] { ", expression.Expressions, AppendExpression, " }");
case ExpressionType.NewArrayBounds:
return builder.Append("new ")
.AppendNameOf(expression.Type.GetElementType())
.AppendCommaSeparated("[", expression.Expressions, AppendExpression, "]");
}
return builder; // TODO: check whether this should be unreachable
}
private static StringBuilder AppendExpression(this StringBuilder builder, InvocationExpression expression)
{
return builder.AppendExpression(expression.Expression)
.AppendCommaSeparated("(", expression.Arguments, AppendExpression, ")");
}
private static StringBuilder AppendExpression(this StringBuilder builder, MemberInitExpression expression)
{
return builder.AppendExpression(expression.NewExpression)
.AppendCommaSeparated(" { ", expression.Bindings, AppendMemberBinding, " }");
StringBuilder AppendMemberBinding(StringBuilder b, MemberBinding binding)
{
switch (binding.BindingType)
{
case MemberBindingType.Assignment:
var assignment = (MemberAssignment)binding;
return builder.Append(assignment.Member.Name)
.Append("= ")
.AppendExpression(assignment.Expression);
case MemberBindingType.MemberBinding:
return b.AppendCommaSeparated(((MemberMemberBinding)binding).Bindings, AppendMemberBinding);
case MemberBindingType.ListBinding:
var original = ((MemberListBinding)binding).Initializers;
for (int i = 0, n = original.Count; i < n; i++)
{
builder.AppendElementInit(original[i]);
}
return builder;
default:
throw new Exception(string.Format(Resources.UnhandledBindingType, binding.BindingType));
}
}
}
private static StringBuilder AppendExpression(this StringBuilder builder, ListInitExpression expression)
{
return builder.AppendExpression(expression.NewExpression)
.AppendCommaSeparated(" { ", expression.Initializers, AppendElementInit, " }");
}
private static StringBuilder AppendExpression(this StringBuilder builder, MatchExpression expression)
{
return builder.AppendExpression(expression.Match.RenderExpression);
}
}
}
| |
// Copyright (c) 2003, Paul Welter
// All rights reserved.
using System;
using System.Collections;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Forms;
namespace NetSpell.DictionaryBuild
{
/// <summary>
/// Summary description for AboutForm.
/// </summary>
public class AboutForm : System.Windows.Forms.Form
{
private AssemblyInfo aInfo = new AssemblyInfo();
private System.Windows.Forms.ListView assembliesListView;
private System.Windows.Forms.ColumnHeader assemblyColumnHeader;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.ColumnHeader dateColumnHeader;
private System.Windows.Forms.ColumnHeader versionColumnHeader;
private System.Windows.Forms.GroupBox VersionGroup;
internal System.Windows.Forms.Label lblCopyright;
internal System.Windows.Forms.Label lblDescription;
internal System.Windows.Forms.Label lblTitle;
internal System.Windows.Forms.Label lblVersion;
private System.Windows.Forms.Button okButton;
private System.Windows.Forms.Label lblCompany;
internal System.Windows.Forms.PictureBox pbIcon;
private void AboutForm_Load(object sender, System.EventArgs e)
{
// Fill in loaded modules / version number info list view.
try
{
// Set this Form's Text & Icon properties by using values from the parent form
this.Text = "About " + this.Owner.Text;
this.Icon = this.Owner.Icon;
// Set this Form's Picture Box's image using the parent's icon
// However, we need to convert it to a Bitmap since the Picture Box Control
// will not accept a raw Icon.
this.pbIcon.Image = this.Owner.Icon.ToBitmap();
// Set the labels identitying the Title, Version, and Description by
// reading Assembly meta-data originally entered in the AssemblyInfo.vb file
this.lblTitle.Text = aInfo.Title;
this.lblVersion.Text = String.Format("Version {0}", aInfo.Version);
this.lblCopyright.Text = aInfo.Copyright;
this.lblDescription.Text = aInfo.Description;
this.lblCompany.Text = aInfo.Company;
assembliesListView.Items.Clear();
// Get all modules
ArrayList localItems = new ArrayList();
foreach (ProcessModule module in Process.GetCurrentProcess().Modules)
{
ListViewItem item = new ListViewItem();
item.Text = module.ModuleName;
// Get version info
FileVersionInfo verInfo = module.FileVersionInfo;
string versionStr = String.Format("{0}.{1}.{2}.{3}",
verInfo.FileMajorPart,
verInfo.FileMinorPart,
verInfo.FileBuildPart,
verInfo.FilePrivatePart);
item.SubItems.Add(versionStr);
// Get file date info
DateTime lastWriteDate = File.GetLastWriteTime(module.FileName);
string dateStr = lastWriteDate.ToString("MMM dd, yyyy");
item.SubItems.Add(dateStr);
assembliesListView.Items.Add(item);
// Stash assemply related list view items for later
if (module.ModuleName.ToLower().StartsWith("netspell"))
{
localItems.Add(item);
}
}
// Extract the assemply related modules and move them to the top
for (int i = localItems.Count; i > 0; i--)
{
ListViewItem localItem = (ListViewItem)localItems[i-1];
assembliesListView.Items.Remove(localItem);
assembliesListView.Items.Insert(0, localItem);
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.ToString(), "About Form Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#region Constructor / Dispose
/// <summary>
///
/// </summary>
public AboutForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#endregion
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.okButton = new System.Windows.Forms.Button();
this.VersionGroup = new System.Windows.Forms.GroupBox();
this.assembliesListView = new System.Windows.Forms.ListView();
this.assemblyColumnHeader = new System.Windows.Forms.ColumnHeader();
this.versionColumnHeader = new System.Windows.Forms.ColumnHeader();
this.dateColumnHeader = new System.Windows.Forms.ColumnHeader();
this.lblCopyright = new System.Windows.Forms.Label();
this.lblDescription = new System.Windows.Forms.Label();
this.lblVersion = new System.Windows.Forms.Label();
this.lblTitle = new System.Windows.Forms.Label();
this.pbIcon = new System.Windows.Forms.PictureBox();
this.lblCompany = new System.Windows.Forms.Label();
this.VersionGroup.SuspendLayout();
this.SuspendLayout();
//
// okButton
//
this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.okButton.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.okButton.Location = new System.Drawing.Point(328, 288);
this.okButton.Name = "okButton";
this.okButton.TabIndex = 0;
this.okButton.Text = "&Ok";
//
// VersionGroup
//
this.VersionGroup.Controls.Add(this.assembliesListView);
this.VersionGroup.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.VersionGroup.ForeColor = System.Drawing.SystemColors.Highlight;
this.VersionGroup.Location = new System.Drawing.Point(8, 136);
this.VersionGroup.Name = "VersionGroup";
this.VersionGroup.Size = new System.Drawing.Size(400, 144);
this.VersionGroup.TabIndex = 9;
this.VersionGroup.TabStop = false;
this.VersionGroup.Text = "Version Information";
//
// assembliesListView
//
this.assembliesListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.assemblyColumnHeader,
this.versionColumnHeader,
this.dateColumnHeader});
this.assembliesListView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.assembliesListView.Location = new System.Drawing.Point(8, 16);
this.assembliesListView.Name = "assembliesListView";
this.assembliesListView.Size = new System.Drawing.Size(384, 120);
this.assembliesListView.TabIndex = 9;
this.assembliesListView.View = System.Windows.Forms.View.Details;
//
// assemblyColumnHeader
//
this.assemblyColumnHeader.Text = "Module";
this.assemblyColumnHeader.Width = 160;
//
// versionColumnHeader
//
this.versionColumnHeader.Text = "Version";
this.versionColumnHeader.Width = 105;
//
// dateColumnHeader
//
this.dateColumnHeader.Text = "Date";
this.dateColumnHeader.Width = 95;
//
// lblCopyright
//
this.lblCopyright.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblCopyright.Location = new System.Drawing.Point(72, 56);
this.lblCopyright.Name = "lblCopyright";
this.lblCopyright.Size = new System.Drawing.Size(328, 23);
this.lblCopyright.TabIndex = 14;
this.lblCopyright.Text = "Application Copyright";
//
// lblDescription
//
this.lblDescription.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblDescription.Location = new System.Drawing.Point(72, 80);
this.lblDescription.Name = "lblDescription";
this.lblDescription.Size = new System.Drawing.Size(328, 32);
this.lblDescription.TabIndex = 13;
this.lblDescription.Text = "Application Description";
//
// lblVersion
//
this.lblVersion.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblVersion.Location = new System.Drawing.Point(72, 32);
this.lblVersion.Name = "lblVersion";
this.lblVersion.Size = new System.Drawing.Size(328, 23);
this.lblVersion.TabIndex = 12;
this.lblVersion.Text = "Application Version";
//
// lblTitle
//
this.lblTitle.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblTitle.Location = new System.Drawing.Point(72, 8);
this.lblTitle.Name = "lblTitle";
this.lblTitle.Size = new System.Drawing.Size(328, 24);
this.lblTitle.TabIndex = 11;
this.lblTitle.Text = "Application Title";
//
// pbIcon
//
this.pbIcon.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.pbIcon.Location = new System.Drawing.Point(16, 8);
this.pbIcon.Name = "pbIcon";
this.pbIcon.Size = new System.Drawing.Size(32, 32);
this.pbIcon.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pbIcon.TabIndex = 10;
this.pbIcon.TabStop = false;
//
// lblCompany
//
this.lblCompany.Location = new System.Drawing.Point(72, 112);
this.lblCompany.Name = "lblCompany";
this.lblCompany.Size = new System.Drawing.Size(328, 23);
this.lblCompany.TabIndex = 15;
this.lblCompany.Text = "Application Company";
//
// AboutForm
//
this.AcceptButton = this.okButton;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.okButton;
this.ClientSize = new System.Drawing.Size(418, 320);
this.Controls.Add(this.lblCompany);
this.Controls.Add(this.lblCopyright);
this.Controls.Add(this.lblDescription);
this.Controls.Add(this.lblVersion);
this.Controls.Add(this.lblTitle);
this.Controls.Add(this.pbIcon);
this.Controls.Add(this.VersionGroup);
this.Controls.Add(this.okButton);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "AboutForm";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "About ...";
this.Load += new System.EventHandler(this.AboutForm_Load);
this.VersionGroup.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
}
public class AssemblyInfo
{
private Type myType = typeof(AboutForm);
/// <summary>
/// CodeBase of Assembly
/// </summary>
public string CodeBase
{
get {return myType.Assembly.CodeBase.ToString();}
}
/// <summary>
/// Company of Assembly
/// </summary>
public string Company
{
get
{
Object[] r = myType.Assembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
AssemblyCompanyAttribute ct = (AssemblyCompanyAttribute)r[0];
return ct.Company;
}
}
/// <summary>
/// Copyright of Assembly
/// </summary>
public string Copyright
{
get
{
Object[] r = myType.Assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
AssemblyCopyrightAttribute ct = (AssemblyCopyrightAttribute)r[0];
return ct.Copyright;
}
}
/// <summary>
/// Description of Assembly
/// </summary>
public string Description
{
get
{
Object[] r = myType.Assembly.GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);
AssemblyDescriptionAttribute ct = (AssemblyDescriptionAttribute)r[0];
return ct.Description;
}
}
/// <summary>
/// FullName of Assembly
/// </summary>
public string FullName
{
get {return myType.Assembly.GetName().FullName.ToString();}
}
/// <summary>
/// Name of Assembly
/// </summary>
public string Name
{
get {return myType.Assembly.GetName().Name.ToString();}
}
/// <summary>
/// Product of Assembly
/// </summary>
public string Product
{
get
{
Object[] r = myType.Assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false);
AssemblyProductAttribute ct = (AssemblyProductAttribute)r[0];
return ct.Product;
}
}
/// <summary>
/// Title of Assembly
/// </summary>
public string Title
{
get
{
Object[] r = myType.Assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
AssemblyTitleAttribute ct = (AssemblyTitleAttribute)r[0];
return ct.Title;
}
}
/// <summary>
/// Version of Assembly
/// </summary>
public string Version
{
get { return myType.Assembly.GetName().Version.ToString(); }
}
}
}
| |
namespace Loon.Core.Graphics.Opengl
{
using Loon.Java;
using Loon.Utils;
public sealed class GLType
{
public readonly static GLType Point = new GLType(GL10.GL_POINTS);
public readonly static GLType Line = new GLType(GL10.GL_LINE_STRIP);
public readonly static GLType Filled = new GLType(GL10.GL_TRIANGLES);
internal int glType;
internal GLType(int glType)
{
this.glType = glType;
}
}
public class GLRenderer
{
private GLBatch _renderer;
private LColor _color = new LColor(1f, 1f, 1f, 1f);
private GLType _currType = null;
public GLRenderer()
: this(9000)
{
}
public GLRenderer(int maxVertices)
{
_renderer = new GLBatch(maxVertices);
}
public void Begin(GLType type)
{
if (_currType != null)
{
throw new RuntimeException(
"Call End() before beginning a new shape batch !");
}
_currType = type;
_renderer.Begin(_currType.glType);
}
public void SetColor(LColor Color)
{
this._color.SetColor(Color);
}
public void SetColor(float r, float g, float b, float a)
{
this._color.SetColor(r, g, b, a);
}
public void Point(float x, float y)
{
Point(x, y, 1);
}
public void Point(float x, float y, float z)
{
if (_currType != GLType.Point)
{
throw new RuntimeException("Must call Begin(GLType.Point)");
}
CheckDirty();
CheckFlush(1);
_renderer.Color(_color);
_renderer.Vertex(x, y, z);
}
public void Line(float x, float y, float z, float x2, float y2, float z2)
{
if (_currType != GLType.Line)
{
throw new RuntimeException("Must call Begin(GLType.Line)");
}
CheckDirty();
CheckFlush(2);
_renderer.Color(_color);
_renderer.Vertex(x, y, z);
_renderer.Color(_color);
_renderer.Vertex(x2, y2, z2);
}
public void Line(float x, float y, float x2, float y2)
{
if (_currType != GLType.Line)
{
throw new RuntimeException("Must call Begin(GLType.Line)");
}
CheckDirty();
CheckFlush(2);
_renderer.Color(_color);
_renderer.Vertex(x, y, 0);
_renderer.Color(_color);
_renderer.Vertex(x2, y2, 0);
}
public void Curve(float x1, float y1, float cx1, float cy1, float cx2,
float cy2, float x2, float y2, int segments)
{
if (_currType != GLType.Line)
{
throw new RuntimeException("Must call Begin(GLType.Line)");
}
CheckDirty();
CheckFlush(segments * 2 + 2);
float subdiv_step = 1f / segments;
float subdiv_step2 = subdiv_step * subdiv_step;
float subdiv_step3 = subdiv_step * subdiv_step * subdiv_step;
float pre1 = 3 * subdiv_step;
float pre2 = 3 * subdiv_step2;
float pre4 = 6 * subdiv_step2;
float pre5 = 6 * subdiv_step3;
float tmp1x = x1 - cx1 * 2 + cx2;
float tmp1y = y1 - cy1 * 2 + cy2;
float tmp2x = (cx1 - cx2) * 3 - x1 + x2;
float tmp2y = (cy1 - cy2) * 3 - y1 + y2;
float fx = x1;
float fy = y1;
float dfx = (cx1 - x1) * pre1 + tmp1x * pre2 + tmp2x * subdiv_step3;
float dfy = (cy1 - y1) * pre1 + tmp1y * pre2 + tmp2y * subdiv_step3;
float ddfx = tmp1x * pre4 + tmp2x * pre5;
float ddfy = tmp1y * pre4 + tmp2y * pre5;
float dddfx = tmp2x * pre5;
float dddfy = tmp2y * pre5;
for (; segments-- > 0; )
{
_renderer.Color(_color);
_renderer.Vertex(fx, fy, 0);
fx += dfx;
fy += dfy;
dfx += ddfx;
dfy += ddfy;
ddfx += dddfx;
ddfy += dddfy;
_renderer.Color(_color);
_renderer.Vertex(fx, fy, 0);
}
_renderer.Color(_color);
_renderer.Vertex(fx, fy, 0);
_renderer.Color(_color);
_renderer.Vertex(x2, y2, 0);
}
public void Triangle(float x1, float y1, float x2, float y2, float x3,
float y3)
{
if (_currType != GLType.Filled && _currType != GLType.Line)
{
throw new RuntimeException(
"Must call Begin(GLType.Filled) or Begin(GLType.Line)");
}
CheckDirty();
CheckFlush(6);
if (_currType == GLType.Line)
{
_renderer.Color(_color);
_renderer.Vertex(x1, y1, 0);
_renderer.Color(_color);
_renderer.Vertex(x2, y2, 0);
_renderer.Color(_color);
_renderer.Vertex(x2, y2, 0);
_renderer.Color(_color);
_renderer.Vertex(x3, y3, 0);
_renderer.Color(_color);
_renderer.Vertex(x3, y3, 0);
_renderer.Color(_color);
_renderer.Vertex(x1, y1, 0);
}
else
{
_renderer.Color(_color);
_renderer.Vertex(x1, y1, 0);
_renderer.Color(_color);
_renderer.Vertex(x2, y2, 0);
_renderer.Color(_color);
_renderer.Vertex(x3, y3, 0);
}
}
public void Rect(float x, float y, float width, float height)
{
if (_currType != GLType.Filled && _currType != GLType.Line)
{
throw new RuntimeException(
"Must call Begin(GLType.Filled) or Begin(GLType.Line)");
}
CheckDirty();
CheckFlush(8);
if (_currType == GLType.Line)
{
_renderer.Color(_color);
_renderer.Vertex(x, y, 0);
_renderer.Color(_color);
_renderer.Vertex(x + width, y, 0);
_renderer.Color(_color);
_renderer.Vertex(x + width, y, 0);
_renderer.Color(_color);
_renderer.Vertex(x + width, y + height, 0);
_renderer.Color(_color);
_renderer.Vertex(x + width, y + height, 0);
_renderer.Color(_color);
_renderer.Vertex(x, y + height, 0);
_renderer.Color(_color);
_renderer.Vertex(x, y + height, 0);
_renderer.Color(_color);
_renderer.Vertex(x, y, 0);
}
else
{
_renderer.Color(_color);
_renderer.Vertex(x, y, 0);
_renderer.Color(_color);
_renderer.Vertex(x + width, y, 0);
_renderer.Color(_color);
_renderer.Vertex(x + width, y + height, 0);
_renderer.Color(_color);
_renderer.Vertex(x + width, y + height, 0);
_renderer.Color(_color);
_renderer.Vertex(x, y + height, 0);
_renderer.Color(_color);
_renderer.Vertex(x, y, 0);
}
}
public void Rect(float x, float y, float width, float height, LColor col1,
LColor col2, LColor col3, LColor col4)
{
if (_currType != GLType.Filled && _currType != GLType.Line)
{
throw new RuntimeException(
"Must call Begin(GLType.Filled) or Begin(GLType.Line)");
}
CheckDirty();
CheckFlush(8);
if (_currType == GLType.Line)
{
_renderer.Color(col1.r, col1.g, col1.b, col1.a);
_renderer.Vertex(x, y, 0);
_renderer.Color(col2.r, col2.g, col2.b, col2.a);
_renderer.Vertex(x + width, y, 0);
_renderer.Color(col2.r, col2.g, col2.b, col2.a);
_renderer.Vertex(x + width, y, 0);
_renderer.Color(col3.r, col3.g, col3.b, col3.a);
_renderer.Vertex(x + width, y + height, 0);
_renderer.Color(col3.r, col3.g, col3.b, col3.a);
_renderer.Vertex(x + width, y + height, 0);
_renderer.Color(col4.r, col4.g, col4.b, col4.a);
_renderer.Vertex(x, y + height, 0);
_renderer.Color(col4.r, col4.g, col4.b, col4.a);
_renderer.Vertex(x, y + height, 0);
_renderer.Color(col1.r, col1.g, col1.b, col1.a);
_renderer.Vertex(x, y, 0);
}
else
{
_renderer.Color(col1.r, col1.g, col1.b, col1.a);
_renderer.Vertex(x, y, 0);
_renderer.Color(col2.r, col2.g, col2.b, col2.a);
_renderer.Vertex(x + width, y, 0);
_renderer.Color(col3.r, col3.g, col3.b, col3.a);
_renderer.Vertex(x + width, y + height, 0);
_renderer.Color(col3.r, col3.g, col3.b, col3.a);
_renderer.Vertex(x + width, y + height, 0);
_renderer.Color(col4.r, col4.g, col4.b, col4.a);
_renderer.Vertex(x, y + height, 0);
_renderer.Color(col1.r, col1.g, col1.b, col1.a);
_renderer.Vertex(x, y, 0);
}
}
public void Oval(float x, float y, float radius)
{
Oval(x, y, radius, (int)(6 * (float)JavaRuntime.Java_Cbrt(radius)));
}
public void Oval(float x, float y, float radius, int segments)
{
if (segments <= 0)
{
throw new System.ArgumentException("segments must be >= 0.");
}
if (_currType != GLType.Filled && _currType != GLType.Line)
{
throw new RuntimeException(
"Must call Begin(GLType.Filled) or Begin(GLType.Line)");
}
CheckDirty();
CheckFlush(segments * 2 + 2);
float angle = 2 * 3.1415926f / segments;
float cos = MathUtils.Cos(angle);
float sin = MathUtils.Sin(angle);
float cx = radius, cy = 0;
if (_currType == GLType.Line)
{
for (int i = 0; i < segments; i++)
{
_renderer.Color(_color);
_renderer.Vertex(x + cx, y + cy, 0);
float temp = cx;
cx = cos * cx - sin * cy;
cy = sin * temp + cos * cy;
_renderer.Color(_color);
_renderer.Vertex(x + cx, y + cy, 0);
}
_renderer.Color(_color);
_renderer.Vertex(x + cx, y + cy, 0);
}
else
{
segments--;
for (int i = 0; i < segments; i++)
{
_renderer.Color(_color);
_renderer.Vertex(x, y, 0);
_renderer.Color(_color);
_renderer.Vertex(x + cx, y + cy, 0);
float temp = cx;
cx = cos * cx - sin * cy;
cy = sin * temp + cos * cy;
_renderer.Color(_color);
_renderer.Vertex(x + cx, y + cy, 0);
}
_renderer.Color(_color);
_renderer.Vertex(x, y, 0);
_renderer.Color(_color);
_renderer.Vertex(x + cx, y + cy, 0);
}
cx = radius;
cy = 0;
_renderer.Color(_color);
_renderer.Vertex(x + cx, y + cy, 0);
}
public void Polygon(float[] vertices)
{
if (_currType != GLType.Line)
{
throw new RuntimeException("Must call Begin(GLType.Line)");
}
if (vertices.Length < 6)
{
throw new System.ArgumentException(
"Polygons must contain at least 3 points.");
}
if (vertices.Length % 2 != 0)
{
throw new System.ArgumentException(
"Polygons must have a pair number of vertices.");
}
int numFloats = vertices.Length;
CheckDirty();
CheckFlush(numFloats);
float firstX = vertices[0];
float firstY = vertices[1];
for (int i = 0; i < numFloats; i += 2)
{
float x1 = vertices[i];
float y1 = vertices[i + 1];
float x2;
float y2;
if (i + 2 >= numFloats)
{
x2 = firstX;
y2 = firstY;
}
else
{
x2 = vertices[i + 2];
y2 = vertices[i + 3];
}
_renderer.Color(_color);
_renderer.Vertex(x1, y1, 0);
_renderer.Color(_color);
_renderer.Vertex(x2, y2, 0);
}
}
private void CheckDirty()
{
GLType type = _currType;
End();
Begin(type);
}
private void CheckFlush(int newVertices)
{
if (_renderer.GetMaxVertices() - _renderer.GetNumVertices() >= newVertices)
{
return;
}
GLType type = _currType;
End();
Begin(type);
}
public void End()
{
if (_renderer != null)
{
_renderer.End();
_currType = null;
}
}
public void Flush()
{
GLType type = _currType;
End();
Begin(type);
}
public GLType GetCurrentType()
{
return _currType;
}
public void Dispose()
{
if (_renderer != null)
{
_renderer.Dispose();
}
}
}
}
| |
using System;
using NExpect.Implementations;
using NExpect.Interfaces;
using NExpect.MatcherLogic;
// ReSharper disable UnusedMember.Global
namespace NExpect
{
// TODO: allow passing in a custom message for all Thans
/// <summary>
/// Adds extension methods for Greater and Less
/// </summary>
public static class GreaterAndLessContinuationExtensions
{
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Greater or .Less</param>
/// <param name="expected">value to compare with</param>
public static void Than(
this ILessContinuation<int> continuation,
int expected
)
{
AddMatcher(continuation, expected, (a, e) => a < e);
}
/// <summary>
/// Tests if a value is greater than an expected value, allowing continuation
/// to test if it is also less than another value
/// </summary>
/// <param name="continuation"></param>
/// <param name="expected"></param>
/// <returns></returns>
public static IGreaterThan<int> Than(
this IGreaterContinuation<int> continuation,
int expected
) {
AddMatcher(continuation, expected, (a, e) => a > e);
return continuation.Continue();
}
private static IGreaterThan<T> Continue<T>(
this IGreaterContinuation<T> continuation
) {
return Factory.Create<T, GreaterThan<T>>(
continuation.GetActual(),
continuation as IExpectationContext<T>
);
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Less</param>
/// <param name="expected">value to compare with</param>
public static void Than(
this ILessContinuation<decimal> continuation,
decimal expected
)
{
AddMatcher(continuation, expected, (a, e) => a < e);
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Greater</param>
/// <param name="expected">value to compare with</param>
public static IGreaterThan<decimal> Than(
this IGreaterContinuation<decimal> continuation,
decimal expected
)
{
AddMatcher(continuation, expected, (a, e) => a > e);
return continuation.Continue();
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Less</param>
/// <param name="expected">value to compare with</param>
public static void Than(
this ILessContinuation<decimal> continuation,
double expected
)
{
AddMatcher(continuation, expected, (a, e) => a < new Decimal(e));
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Greater</param>
/// <param name="expected">value to compare with</param>
public static IGreaterThan<decimal> Than(
this IGreaterContinuation<decimal> continuation,
double expected
)
{
AddMatcher(continuation, expected, (a, e) => a > new Decimal(e));
return continuation.Continue();
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Less</param>
/// <param name="expected">value to compare with</param>
public static void Than(
this ILessContinuation<decimal> continuation,
long expected
)
{
AddMatcher(continuation, expected, (a, e) => a < new Decimal(e));
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Greater</param>
/// <param name="expected">value to compare with</param>
public static IGreaterThan<decimal> Than(
this IGreaterContinuation<decimal> continuation,
long expected
)
{
AddMatcher(continuation, expected, (a, e) => a > new Decimal(e));
return continuation.Continue();
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Less</param>
/// <param name="expected">value to compare with</param>
public static void Than(
this ILessContinuation<double> continuation,
double expected
)
{
AddMatcher(continuation, expected, (a, e) => a < e);
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Greater</param>
/// <param name="expected">value to compare with</param>
public static IGreaterThan<double> Than(
this IGreaterContinuation<double> continuation,
double expected
)
{
AddMatcher(continuation, expected, (a, e) => a > e);
return continuation.Continue();
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Less</param>
/// <param name="expected">value to compare with</param>
public static void Than(
this ILessContinuation<double> continuation,
decimal expected
)
{
AddMatcher(continuation, expected, (a, e) => new Decimal(a) < e);
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Greater</param>
/// <param name="expected">value to compare with</param>
public static IGreaterThan<double> Than(
this IGreaterContinuation<double> continuation,
decimal expected
)
{
AddMatcher(continuation, expected, (a, e) => new Decimal(a) > e);
return continuation.Continue();
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Greater or .Less</param>
/// <param name="expected">value to compare with</param>
public static void Than(
this ILessContinuation<double> continuation,
long expected
)
{
AddMatcher(continuation, expected, (a, e) => new Decimal(a) < e);
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Greater or .Less</param>
/// <param name="expected">value to compare with</param>
public static IGreaterThan<double> Than(
this IGreaterContinuation<double> continuation,
long expected
)
{
AddMatcher(continuation, expected, (a, e) => new Decimal(a) > e);
return continuation.Continue();
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Greater or .Less</param>
/// <param name="expected">value to compare with</param>
public static void Than(
this ILessContinuation<float> continuation,
float expected
)
{
AddMatcher(continuation, expected, (a, e) => a < e);
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Greater or .Less</param>
/// <param name="expected">value to compare with</param>
public static IGreaterThan<float> Than(
this IGreaterContinuation<float> continuation,
float expected
)
{
AddMatcher(continuation, expected, (a, e) => a > e);
return continuation.Continue();
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Greater or .Less</param>
/// <param name="expected">value to compare with</param>
public static void Than(
this ILessContinuation<float> continuation,
decimal expected
)
{
AddMatcher(continuation, expected, (a, e) => new Decimal(a) < e);
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Greater or .Less</param>
/// <param name="expected">value to compare with</param>
public static IGreaterThan<float> Than(
this IGreaterContinuation<float> continuation,
decimal expected
)
{
AddMatcher(continuation, expected, (a, e) => new Decimal(a) > e);
return continuation.Continue();
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Greater or .Less</param>
/// <param name="expected">value to compare with</param>
public static void Than(
this ILessContinuation<long> continuation,
long expected
)
{
AddMatcher(continuation, expected, (a, e) => a < e);
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Greater or .Less</param>
/// <param name="expected">value to compare with</param>
public static IGreaterThan<long> Than(
this IGreaterContinuation<long> continuation,
long expected
)
{
AddMatcher(continuation, expected, (a, e) => a > e);
return continuation.Continue();
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Greater or .Less</param>
/// <param name="expected">value to compare with</param>
public static void Than(
this ILessContinuation<long> continuation,
decimal expected
)
{
AddMatcher(continuation, expected, (a, e) => a < e);
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Greater or .Less</param>
/// <param name="expected">value to compare with</param>
public static IGreaterThan<long> Than(
this IGreaterContinuation<long> continuation,
decimal expected
)
{
AddMatcher(continuation, expected, (a, e) => a > e);
return continuation.Continue();
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Greater or .Less</param>
/// <param name="expected">value to compare with</param>
public static void Than(
this ILessContinuation<long> continuation,
double expected
)
{
AddMatcher(continuation, expected, (a, e) => a < e);
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Greater or .Less</param>
/// <param name="expected">value to compare with</param>
public static IGreaterThan<long> Than(
this IGreaterContinuation<long> continuation,
double expected
)
{
AddMatcher(continuation, expected, (a, e) => a > e);
return continuation.Continue();
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Greater or .Less</param>
/// <param name="expected">value to compare with</param>
public static void Than(
this ILessContinuation<DateTime> continuation,
DateTime expected
)
{
AddMatcher(continuation, expected, (a, e) => a < e);
}
/// <summary>
/// Compares two values
/// </summary>
/// <param name="continuation">.Greater or .Less</param>
/// <param name="expected">value to compare with</param>
public static IGreaterThan<DateTime> Than(
this IGreaterContinuation<DateTime> continuation,
DateTime expected
)
{
AddMatcher(continuation, expected, (a, e) => a > e);
return continuation.Continue();
}
private static void AddMatcher<T1, T2>(
ICanAddMatcher<T1> continuation,
T2 expected,
Func<T1, T2, bool> test
)
{
continuation.AddMatcher(actual =>
{
var passed = test(actual, expected);
var compare = continuation is IGreaterContinuation<T1> ? "greater" : "less";
var message = passed
? $"Expected {actual} not to be {compare} than {expected}"
: $"Expected {actual} to be {compare} than {expected}";
return new MatcherResult(passed, message);
});
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
namespace Microsoft.Azure.KeyVault.Tests
{
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Rest.Azure;
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.KeyVault.Models;
using Microsoft.Azure.KeyVault.WebKey;
using Microsoft.Azure.Services.AppAuthentication;
// Used to compile sample snippets used in MigrationGuide.md documents for track 1.
internal class SampleSnippets
{
private async Task CertificatesMigrationGuide()
{
#region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_Create
AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
KeyVaultClient client = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback));
#endregion Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_Create
#region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_CreateWithOptions
using (HttpClient httpClient = new HttpClient())
{
#if SNIPPET
AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
KeyVaultClient client = new KeyVaultClient(
#else
provider = new AzureServiceTokenProvider();
client = new KeyVaultClient(
#endif
new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback),
httpClient);
}
#endregion Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_CreateWithOptions
#region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_CreateCustomPolicy
CertificatePolicy policy = new CertificatePolicy
{
IssuerParameters = new IssuerParameters("issuer-name"),
SecretProperties = new SecretProperties("application/x-pkcs12"),
KeyProperties = new KeyProperties
{
KeyType = "RSA",
KeySize = 2048,
ReuseKey = true
},
X509CertificateProperties = new X509CertificateProperties("CN=customdomain.com")
{
KeyUsage = new[]
{
KeyUsageType.CRLSign,
KeyUsageType.DataEncipherment,
KeyUsageType.DigitalSignature,
KeyUsageType.KeyEncipherment,
KeyUsageType.KeyAgreement,
KeyUsageType.KeyCertSign
},
ValidityInMonths = 12
},
LifetimeActions = new[]
{
new LifetimeAction(
new Trigger
{
DaysBeforeExpiry = 90
},
new Models.Action(ActionType.AutoRenew))
}
};
#endregion Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_CreateCustomPolicy
{
#region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_CreateCertificate
CertificateBundle certificate = null;
// Start certificate creation.
// Depending on the policy and your business process, this could even take days for manual signing.
CertificateOperation createOperation = await client.CreateCertificateAsync("https://myvault.vault.azure.net", "certificate-name", policy);
while (true)
{
if ("InProgress".Equals(createOperation.Status, StringComparison.OrdinalIgnoreCase))
{
await Task.Delay(TimeSpan.FromSeconds(20));
createOperation = await client.GetCertificateOperationAsync("https://myvault.vault.azure.net", "certificate-name");
continue;
}
if ("Completed".Equals(createOperation.Status, StringComparison.OrdinalIgnoreCase))
{
certificate = await client.GetCertificateAsync(createOperation.Id);
break;
}
throw new Exception(string.Format(
CultureInfo.InvariantCulture,
"Polling on pending certificate returned an unexpected result. Error code = {0}, Error message = {1}",
createOperation.Error.Code,
createOperation.Error.Message));
}
// If you need to restart the application you can recreate the operation and continue awaiting.
do
{
createOperation = await client.GetCertificateOperationAsync("https://myvault.vault.azure.net", "certificate-name");
if ("InProgress".Equals(createOperation.Status, StringComparison.OrdinalIgnoreCase))
{
await Task.Delay(TimeSpan.FromSeconds(20));
continue;
}
if ("Completed".Equals(createOperation.Status, StringComparison.OrdinalIgnoreCase))
{
certificate = await client.GetCertificateAsync(createOperation.Id);
break;
}
throw new Exception(string.Format(
CultureInfo.InvariantCulture,
"Polling on pending certificate returned an unexpected result. Error code = {0}, Error message = {1}",
createOperation.Error.Code,
createOperation.Error.Message));
} while (true);
#endregion Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_CreateCertificate
}
{
#region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_ImportCertificate
byte[] cer = File.ReadAllBytes("certificate.pfx");
string cerBase64 = Convert.ToBase64String(cer);
CertificateBundle certificate = await client.ImportCertificateAsync(
"https://myvault.vault.azure.net",
"certificate-name",
cerBase64,
certificatePolicy: policy);
#endregion Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_ImportCertificate
}
#region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_CreateSelfSignedPolicy
#if SNIPPET
CertificatePolicy policy = new CertificatePolicy
#else
policy = new CertificatePolicy
#endif
{
IssuerParameters = new IssuerParameters("Self"),
X509CertificateProperties = new X509CertificateProperties("CN=DefaultPolicy")
};
#endregion Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_CreateSelfSignedPolicy
// TODO
{
#region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_ListCertificates
IPage<CertificateItem> page = await client.GetCertificatesAsync("https://myvault.vault.azure.net");
foreach (CertificateItem item in page)
{
CertificateIdentifier certificateId = item.Identifier;
CertificateBundle certificate = await client.GetCertificateAsync(certificateId.Vault, certificateId.Name);
}
while (page.NextPageLink != null)
{
page = await client.GetCertificatesNextAsync(page.NextPageLink);
foreach (CertificateItem item in page)
{
CertificateIdentifier certificateId = item.Identifier;
CertificateBundle certificate = await client.GetCertificateAsync(certificateId.Vault, certificateId.Name);
}
}
#endregion Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_ListCertificates
}
{
#region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_DeleteCertificate
// Delete the certificate.
DeletedCertificateBundle deletedCertificate = await client.DeleteCertificateAsync("https://myvault.vault.azure.net", "certificate-name");
// Purge or recover the deleted certificate if soft delete is enabled.
if (deletedCertificate.RecoveryId != null)
{
DeletedCertificateIdentifier deletedCertificateId = deletedCertificate.RecoveryIdentifier;
// Deleting a certificate does not happen immediately. Wait a while and check if the deleted certificate exists.
while (true)
{
try
{
await client.GetDeletedCertificateAsync(deletedCertificateId.Vault, deletedCertificateId.Name);
// Finally deleted.
break;
}
catch (KeyVaultErrorException ex) when (ex.Response.StatusCode == HttpStatusCode.NotFound)
{
// Not yet deleted...
}
}
// Purge the deleted certificate.
await client.PurgeDeletedCertificateAsync(deletedCertificateId.Vault, deletedCertificateId.Name);
// You can also recover the deleted certificate using RecoverDeletedCertificateAsync.
}
#endregion Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_DeleteCertificate
}
}
private async Task KeysMigrationGuide()
{
#region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Create
AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
KeyVaultClient client = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback));
#endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Create
#region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_CreateWithOptions
using (HttpClient httpClient = new HttpClient())
{
#if SNIPPET
AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
KeyVaultClient client = new KeyVaultClient(
#else
provider = new AzureServiceTokenProvider();
client = new KeyVaultClient(
#endif
new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback),
httpClient);
}
#endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_CreateWithOptions
{
#region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_CreateKey
// Create RSA key.
NewKeyParameters createRsaParameters = new NewKeyParameters
{
Kty = JsonWebKeyType.Rsa,
KeySize = 4096
};
KeyBundle rsaKey = await client.CreateKeyAsync("https://myvault.vault.azure.net", "rsa-key-name", createRsaParameters);
// Create Elliptic-Curve key.
NewKeyParameters createEcParameters = new NewKeyParameters
{
Kty = JsonWebKeyType.EllipticCurve,
CurveName = "P-256"
};
KeyBundle ecKey = await client.CreateKeyAsync("https://myvault.vault.azure.net", "ec-key-name", createEcParameters);
#endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_CreateKey
}
{
#region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_ListKeys
IPage<KeyItem> page = await client.GetKeysAsync("https://myvault.vault.azure.net");
foreach (KeyItem item in page)
{
KeyIdentifier keyId = item.Identifier;
KeyBundle key = await client.GetKeyAsync(keyId.Vault, keyId.Name);
}
while (page.NextPageLink != null)
{
page = await client.GetKeysNextAsync(page.NextPageLink);
foreach (KeyItem item in page)
{
KeyIdentifier keyId = item.Identifier;
KeyBundle key = await client.GetKeyAsync(keyId.Vault, keyId.Name);
}
}
#endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_ListKeys
}
{
#region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_DeleteKey
// Delete the key.
DeletedKeyBundle deletedKey = await client.DeleteKeyAsync("https://myvault.vault.azure.net", "key-name");
// Purge or recover the deleted key if soft delete is enabled.
if (deletedKey.RecoveryId != null)
{
DeletedKeyIdentifier deletedKeyId = deletedKey.RecoveryIdentifier;
// Deleting a key does not happen immediately. Wait a while and check if the deleted key exists.
while (true)
{
try
{
await client.GetDeletedKeyAsync(deletedKeyId.Vault, deletedKeyId.Name);
// Finally deleted.
break;
}
catch (KeyVaultErrorException ex) when (ex.Response.StatusCode == HttpStatusCode.NotFound)
{
// Not yet deleted...
}
}
// Purge the deleted key.
await client.PurgeDeletedKeyAsync(deletedKeyId.Vault, deletedKeyId.Name);
// You can also recover the deleted key using RecoverDeletedKeyAsync.
}
#endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_DeleteKey
}
{
#region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Encrypt
// Encrypt a message. The plaintext must be small enough for the chosen algorithm.
byte[] plaintext = Encoding.UTF8.GetBytes("Small message to encrypt");
KeyOperationResult encrypted = await client.EncryptAsync("rsa-key-name", JsonWebKeyEncryptionAlgorithm.RSAOAEP256, plaintext);
// Decrypt the message.
KeyOperationResult decrypted = await client.DecryptAsync("rsa-key-name", JsonWebKeyEncryptionAlgorithm.RSAOAEP256, encrypted.Result);
string message = Encoding.UTF8.GetString(decrypted.Result);
#endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Encrypt
}
{
#region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Wrap
using (Aes aes = Aes.Create())
{
// Use a symmetric key to encrypt large amounts of data, possibly streamed...
// Now wrap the key and store the encrypted key and plaintext IV to later decrypt the key to decrypt the data.
KeyOperationResult wrapped = await client.WrapKeyAsync(
"https://myvault.vault.azure.net",
"rsa-key-name",
null,
JsonWebKeyEncryptionAlgorithm.RSAOAEP256,
aes.Key);
// Read the IV and the encrypted key from the payload, then unwrap the key.
KeyOperationResult unwrapped = await client.UnwrapKeyAsync(
"https://myvault.vault.azure.net",
"rsa-key-name",
null,
JsonWebKeyEncryptionAlgorithm.RSAOAEP256,
wrapped.Result);
aes.Key = unwrapped.Result;
// Decrypt the payload with the symmetric key.
}
#endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Wrap
}
}
private async Task SecretsMigrationGuide()
{
#region Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_Create
AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
KeyVaultClient client = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback));
#endregion Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_Create
#region Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_CreateWithOptions
using (HttpClient httpClient = new HttpClient())
{
#if SNIPPET
AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
KeyVaultClient client = new KeyVaultClient(
#else
provider = new AzureServiceTokenProvider();
client = new KeyVaultClient(
#endif
new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback),
httpClient);
}
#endregion Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_CreateWithOptions
{
#region Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_SetSecret
SecretBundle secret = await client.SetSecretAsync("https://myvault.vault.azure.net", "secret-name", "secret-value");
#endregion Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_SetSecret
}
{
#region Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_GetSecret
// Get the latest secret value.
SecretBundle secret = await client.GetSecretAsync("https://myvault.vault.azure.net", "secret-name", null);
// Get a specific secret value.
SecretBundle secretVersion = await client.GetSecretAsync("https://myvault.vault.azure.net", "secret-name", "e43af03a7cbc47d4a4e9f11540186048");
#endregion Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_GetSecret
}
{
#region Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_ListSecrets
IPage<SecretItem> page = await client.GetSecretsAsync("https://myvault.vault.azure.net");
foreach (SecretItem item in page)
{
SecretIdentifier secretId = item.Identifier;
SecretBundle secret = await client.GetSecretAsync(secretId.Vault, secretId.Name);
}
while (page.NextPageLink != null)
{
page = await client.GetSecretsNextAsync(page.NextPageLink);
foreach (SecretItem item in page)
{
SecretIdentifier secretId = item.Identifier;
SecretBundle secret = await client.GetSecretAsync(secretId.Vault, secretId.Name);
}
}
#endregion Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_ListSecrets
}
{
#region Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_DeleteSecret
// Delete the secret.
DeletedSecretBundle deletedSecret = await client.DeleteSecretAsync("https://myvault.vault.azure.net", "secret-name");
// Purge or recover the deleted secret if soft delete is enabled.
if (deletedSecret.RecoveryId != null)
{
DeletedSecretIdentifier deletedSecretId = deletedSecret.RecoveryIdentifier;
// Deleting a secret does not happen immediately. Wait a while and check if the deleted secret exists.
while (true)
{
try
{
await client.GetDeletedSecretAsync(deletedSecretId.Vault, deletedSecretId.Name);
// Finally deleted.
break;
}
catch (KeyVaultErrorException ex) when (ex.Response.StatusCode == HttpStatusCode.NotFound)
{
// Not yet deleted...
}
}
// Purge the deleted secret.
await client.PurgeDeletedSecretAsync(deletedSecretId.Vault, deletedSecretId.Name);
// You can also recover the deleted secret using RecoverDeletedSecretAsync.
}
#endregion Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_DeleteSecret
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using Internal.Runtime.CompilerServices;
namespace System.Collections.Generic
{
/// <summary>
/// Used internally to control behavior of insertion into a <see cref="Dictionary{TKey, TValue}"/>.
/// </summary>
internal enum InsertionBehavior : byte
{
/// <summary>
/// The default insertion behavior.
/// </summary>
None = 0,
/// <summary>
/// Specifies that an existing entry with the same key should be overwritten if encountered.
/// </summary>
OverwriteExisting = 1,
/// <summary>
/// Specifies that if an existing entry with the same key is encountered, an exception should be thrown.
/// </summary>
ThrowOnExisting = 2
}
[DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback where TKey : notnull
{
private struct Entry
{
public uint hashCode;
// 0-based index of next entry in chain: -1 means end of chain
// also encodes whether this entry _itself_ is part of the free list by changing sign and subtracting 3,
// so -2 means end of free list, -3 means index 0 but on free list, -4 means index 1 but on free list, etc.
public int next;
public TKey key; // Key of entry
public TValue value; // Value of entry
}
private int[]? _buckets;
private Entry[]? _entries;
#if BIT64
private ulong _fastModMultiplier;
#endif
private int _count;
private int _freeList;
private int _freeCount;
private int _version;
private IEqualityComparer<TKey>? _comparer;
private KeyCollection? _keys;
private ValueCollection? _values;
private const int StartOfFreeList = -3;
// constants for serialization
private const string VersionName = "Version"; // Do not rename (binary serialization)
private const string HashSizeName = "HashSize"; // Do not rename (binary serialization). Must save buckets.Length
private const string KeyValuePairsName = "KeyValuePairs"; // Do not rename (binary serialization)
private const string ComparerName = "Comparer"; // Do not rename (binary serialization)
public Dictionary() : this(0, null) { }
public Dictionary(int capacity) : this(capacity, null) { }
public Dictionary(IEqualityComparer<TKey>? comparer) : this(0, comparer) { }
public Dictionary(int capacity, IEqualityComparer<TKey>? comparer)
{
if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
if (capacity > 0) Initialize(capacity);
if (comparer != EqualityComparer<TKey>.Default)
{
_comparer = comparer;
}
if (typeof(TKey) == typeof(string) && _comparer == null)
{
// To start, move off default comparer for string which is randomised
_comparer = (IEqualityComparer<TKey>)NonRandomizedStringEqualityComparer.Default;
}
}
public Dictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { }
public Dictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey>? comparer) :
this(dictionary != null ? dictionary.Count : 0, comparer)
{
if (dictionary == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
// It is likely that the passed-in dictionary is Dictionary<TKey,TValue>. When this is the case,
// avoid the enumerator allocation and overhead by looping through the entries array directly.
// We only do this when dictionary is Dictionary<TKey,TValue> and not a subclass, to maintain
// back-compat with subclasses that may have overridden the enumerator behavior.
if (dictionary.GetType() == typeof(Dictionary<TKey, TValue>))
{
Dictionary<TKey, TValue> d = (Dictionary<TKey, TValue>)dictionary;
int count = d._count;
Entry[]? entries = d._entries;
for (int i = 0; i < count; i++)
{
if (entries![i].next >= -1)
{
Add(entries[i].key, entries[i].value);
}
}
return;
}
foreach (KeyValuePair<TKey, TValue> pair in dictionary)
{
Add(pair.Key, pair.Value);
}
}
public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection) : this(collection, null) { }
public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey>? comparer) :
this((collection as ICollection<KeyValuePair<TKey, TValue>>)?.Count ?? 0, comparer)
{
if (collection == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
foreach (KeyValuePair<TKey, TValue> pair in collection)
{
Add(pair.Key, pair.Value);
}
}
protected Dictionary(SerializationInfo info, StreamingContext context)
{
// We can't do anything with the keys and values until the entire graph has been deserialized
// and we have a resonable estimate that GetHashCode is not going to fail. For the time being,
// we'll just cache this. The graph is not valid until OnDeserialization has been called.
HashHelpers.SerializationInfoTable.Add(this, info);
}
public IEqualityComparer<TKey> Comparer =>
(_comparer == null || _comparer is NonRandomizedStringEqualityComparer) ?
EqualityComparer<TKey>.Default :
_comparer;
public int Count => _count - _freeCount;
public KeyCollection Keys => _keys ??= new KeyCollection(this);
ICollection<TKey> IDictionary<TKey, TValue>.Keys => _keys ??= new KeyCollection(this);
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys => _keys ??= new KeyCollection(this);
public ValueCollection Values => _values ??= new ValueCollection(this);
ICollection<TValue> IDictionary<TKey, TValue>.Values => _values ??= new ValueCollection(this);
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values => _values ??= new ValueCollection(this);
public TValue this[TKey key]
{
get
{
ref TValue value = ref FindValue(key);
if (!Unsafe.IsNullRef(ref value))
{
return value;
}
ThrowHelper.ThrowKeyNotFoundException(key);
return default;
}
set
{
bool modified = TryInsert(key, value, InsertionBehavior.OverwriteExisting);
Debug.Assert(modified);
}
}
public void Add(TKey key, TValue value)
{
bool modified = TryInsert(key, value, InsertionBehavior.ThrowOnExisting);
Debug.Assert(modified); // If there was an existing key and the Add failed, an exception will already have been thrown.
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair)
=> Add(keyValuePair.Key, keyValuePair.Value);
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair)
{
ref TValue value = ref FindValue(keyValuePair.Key);
if (!Unsafe.IsNullRef(ref value) && EqualityComparer<TValue>.Default.Equals(value, keyValuePair.Value))
{
return true;
}
return false;
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair)
{
ref TValue value = ref FindValue(keyValuePair.Key);
if (!Unsafe.IsNullRef(ref value) && EqualityComparer<TValue>.Default.Equals(value, keyValuePair.Value))
{
Remove(keyValuePair.Key);
return true;
}
return false;
}
public void Clear()
{
int count = _count;
if (count > 0)
{
Debug.Assert(_buckets != null, "_buckets should be non-null");
Debug.Assert(_entries != null, "_entries should be non-null");
Array.Clear(_buckets, 0, _buckets.Length);
_count = 0;
_freeList = -1;
_freeCount = 0;
Array.Clear(_entries, 0, count);
}
}
public bool ContainsKey(TKey key)
=> !Unsafe.IsNullRef(ref FindValue(key));
public bool ContainsValue(TValue value)
{
Entry[]? entries = _entries;
if (value == null)
{
for (int i = 0; i < _count; i++)
{
if (entries![i].next >= -1 && entries[i].value == null) return true;
}
}
else
{
if (default(TValue)! != null) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
{
// ValueType: Devirtualize with EqualityComparer<TValue>.Default intrinsic
for (int i = 0; i < _count; i++)
{
if (entries![i].next >= -1 && EqualityComparer<TValue>.Default.Equals(entries[i].value, value)) return true;
}
}
else
{
// Object type: Shared Generic, EqualityComparer<TValue>.Default won't devirtualize
// https://github.com/dotnet/coreclr/issues/17273
// So cache in a local rather than get EqualityComparer per loop iteration
EqualityComparer<TValue> defaultComparer = EqualityComparer<TValue>.Default;
for (int i = 0; i < _count; i++)
{
if (entries![i].next >= -1 && defaultComparer.Equals(entries[i].value, value)) return true;
}
}
}
return false;
}
private void CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if ((uint)index > (uint)array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = _count;
Entry[]? entries = _entries;
for (int i = 0; i < count; i++)
{
if (entries![i].next >= -1)
{
array[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value);
}
}
}
public Enumerator GetEnumerator()
=> new Enumerator(this, Enumerator.KeyValuePair);
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
=> new Enumerator(this, Enumerator.KeyValuePair);
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info);
}
info.AddValue(VersionName, _version);
info.AddValue(ComparerName, _comparer ?? EqualityComparer<TKey>.Default, typeof(IEqualityComparer<TKey>));
info.AddValue(HashSizeName, _buckets == null ? 0 : _buckets.Length); // This is the length of the bucket array
if (_buckets != null)
{
var array = new KeyValuePair<TKey, TValue>[Count];
CopyTo(array, 0);
info.AddValue(KeyValuePairsName, array, typeof(KeyValuePair<TKey, TValue>[]));
}
}
private ref TValue FindValue(TKey key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
ref Entry entry = ref Unsafe.NullRef<Entry>();
if (_buckets != null)
{
Debug.Assert(_entries != null, "expected entries to be != null");
IEqualityComparer<TKey>? comparer = _comparer;
if (comparer == null)
{
uint hashCode = (uint)key.GetHashCode();
int i = GetBucket(hashCode);
Entry[]? entries = _entries;
uint collisionCount = 0;
if (default(TKey)! != null) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
{
// ValueType: Devirtualize with EqualityComparer<TValue>.Default intrinsic
// Value in _buckets is 1-based; subtract 1 from i. We do it here so it fuses with the following conditional.
i--;
do
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test in if to drop range check for following array access
if ((uint)i >= (uint)entries.Length)
{
goto ReturnNotFound;
}
entry = ref entries[i];
if (entry.hashCode == hashCode && EqualityComparer<TKey>.Default.Equals(entry.key, key))
{
goto ReturnFound;
}
i = entry.next;
collisionCount++;
} while (collisionCount <= (uint)entries.Length);
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
goto ConcurrentOperation;
}
else
{
// Object type: Shared Generic, EqualityComparer<TValue>.Default won't devirtualize
// https://github.com/dotnet/coreclr/issues/17273
// So cache in a local rather than get EqualityComparer per loop iteration
EqualityComparer<TKey> defaultComparer = EqualityComparer<TKey>.Default;
// Value in _buckets is 1-based; subtract 1 from i. We do it here so it fuses with the following conditional.
i--;
do
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test in if to drop range check for following array access
if ((uint)i >= (uint)entries.Length)
{
goto ReturnNotFound;
}
entry = ref entries[i];
if (entry.hashCode == hashCode && defaultComparer.Equals(entry.key, key))
{
goto ReturnFound;
}
i = entry.next;
collisionCount++;
} while (collisionCount <= (uint)entries.Length);
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
goto ConcurrentOperation;
}
}
else
{
uint hashCode = (uint)comparer.GetHashCode(key);
int i = GetBucket(hashCode);
Entry[]? entries = _entries;
uint collisionCount = 0;
// Value in _buckets is 1-based; subtract 1 from i. We do it here so it fuses with the following conditional.
i--;
do
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test in if to drop range check for following array access
if ((uint)i >= (uint)entries.Length)
{
goto ReturnNotFound;
}
entry = ref entries[i];
if (entry.hashCode == hashCode && comparer.Equals(entry.key, key))
{
goto ReturnFound;
}
i = entry.next;
collisionCount++;
} while (collisionCount <= (uint)entries.Length);
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
goto ConcurrentOperation;
}
}
goto ReturnNotFound;
ConcurrentOperation:
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
ReturnFound:
ref TValue value = ref entry.value;
Return:
return ref value;
ReturnNotFound:
value = ref Unsafe.NullRef<TValue>();
goto Return;
}
private int Initialize(int capacity)
{
int size = HashHelpers.GetPrime(capacity);
int[] buckets = new int[size];
Entry[] entries = new Entry[size];
// Assign member variables after both arrays allocated to guard against corruption from OOM if second fails
_freeList = -1;
#if BIT64
_fastModMultiplier = HashHelpers.GetFastModMultiplier((uint)size);
#endif
_buckets = buckets;
_entries = entries;
return size;
}
private bool TryInsert(TKey key, TValue value, InsertionBehavior behavior)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (_buckets == null)
{
Initialize(0);
}
Debug.Assert(_buckets != null);
Entry[]? entries = _entries;
Debug.Assert(entries != null, "expected entries to be non-null");
IEqualityComparer<TKey>? comparer = _comparer;
uint hashCode = (uint)((comparer == null) ? key.GetHashCode() : comparer.GetHashCode(key));
uint collisionCount = 0;
ref int bucket = ref GetBucket(hashCode);
// Value in _buckets is 1-based
int i = bucket - 1;
if (comparer == null)
{
if (default(TKey)! != null) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
{
// ValueType: Devirtualize with EqualityComparer<TValue>.Default intrinsic
while (true)
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test uint in if rather than loop condition to drop range check for following array access
if ((uint)i >= (uint)entries.Length)
{
break;
}
if (entries[i].hashCode == hashCode && EqualityComparer<TKey>.Default.Equals(entries[i].key, key))
{
if (behavior == InsertionBehavior.OverwriteExisting)
{
entries[i].value = value;
_version++;
return true;
}
if (behavior == InsertionBehavior.ThrowOnExisting)
{
ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
}
return false;
}
i = entries[i].next;
collisionCount++;
if (collisionCount > (uint)entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
}
}
else
{
// Object type: Shared Generic, EqualityComparer<TValue>.Default won't devirtualize
// https://github.com/dotnet/coreclr/issues/17273
// So cache in a local rather than get EqualityComparer per loop iteration
EqualityComparer<TKey> defaultComparer = EqualityComparer<TKey>.Default;
while (true)
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test uint in if rather than loop condition to drop range check for following array access
if ((uint)i >= (uint)entries.Length)
{
break;
}
if (entries[i].hashCode == hashCode && defaultComparer.Equals(entries[i].key, key))
{
if (behavior == InsertionBehavior.OverwriteExisting)
{
entries[i].value = value;
_version++;
return true;
}
if (behavior == InsertionBehavior.ThrowOnExisting)
{
ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
}
return false;
}
i = entries[i].next;
collisionCount++;
if (collisionCount > (uint)entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
}
}
}
else
{
while (true)
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test uint in if rather than loop condition to drop range check for following array access
if ((uint)i >= (uint)entries.Length)
{
break;
}
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key))
{
if (behavior == InsertionBehavior.OverwriteExisting)
{
entries[i].value = value;
_version++;
return true;
}
if (behavior == InsertionBehavior.ThrowOnExisting)
{
ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
}
return false;
}
i = entries[i].next;
collisionCount++;
if (collisionCount > (uint)entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
}
}
bool updateFreeList = false;
int index;
if (_freeCount > 0)
{
index = _freeList;
updateFreeList = true;
_freeCount--;
}
else
{
int count = _count;
if (count == entries.Length)
{
Resize();
bucket = ref GetBucket(hashCode);
}
index = count;
_count = count + 1;
entries = _entries;
}
ref Entry entry = ref entries![index];
if (updateFreeList)
{
Debug.Assert((StartOfFreeList - entries[_freeList].next) >= -1, "shouldn't overflow because `next` cannot underflow");
_freeList = StartOfFreeList - entries[_freeList].next;
}
entry.hashCode = hashCode;
// Value in _buckets is 1-based
entry.next = bucket - 1;
entry.key = key;
entry.value = value;
// Value in _buckets is 1-based
bucket = index + 1;
_version++;
// Value types never rehash
if (default(TKey)! == null && collisionCount > HashHelpers.HashCollisionThreshold && comparer is NonRandomizedStringEqualityComparer) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
{
// If we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing
// i.e. EqualityComparer<string>.Default.
_comparer = null;
Resize(entries.Length, true);
}
return true;
}
public virtual void OnDeserialization(object? sender)
{
HashHelpers.SerializationInfoTable.TryGetValue(this, out SerializationInfo? siInfo);
if (siInfo == null)
{
// We can return immediately if this function is called twice.
// Note we remove the serialization info from the table at the end of this method.
return;
}
int realVersion = siInfo.GetInt32(VersionName);
int hashsize = siInfo.GetInt32(HashSizeName);
_comparer = (IEqualityComparer<TKey>)siInfo.GetValue(ComparerName, typeof(IEqualityComparer<TKey>))!; // When serialized if comparer is null, we use the default.
if (hashsize != 0)
{
Initialize(hashsize);
KeyValuePair<TKey, TValue>[]? array = (KeyValuePair<TKey, TValue>[]?)
siInfo.GetValue(KeyValuePairsName, typeof(KeyValuePair<TKey, TValue>[]));
if (array == null)
{
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_MissingKeys);
}
for (int i = 0; i < array.Length; i++)
{
if (array[i].Key == null)
{
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_NullKey);
}
Add(array[i].Key, array[i].Value);
}
}
else
{
_buckets = null;
}
_version = realVersion;
HashHelpers.SerializationInfoTable.Remove(this);
}
private void Resize()
=> Resize(HashHelpers.ExpandPrime(_count), false);
private void Resize(int newSize, bool forceNewHashCodes)
{
// Value types never rehash
Debug.Assert(!forceNewHashCodes || default(TKey)! == null); // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
Debug.Assert(_entries != null, "_entries should be non-null");
Debug.Assert(newSize >= _entries.Length);
Entry[] entries = new Entry[newSize];
int count = _count;
Array.Copy(_entries, entries, count);
if (default(TKey)! == null && forceNewHashCodes) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
{
for (int i = 0; i < count; i++)
{
if (entries[i].next >= -1)
{
Debug.Assert(_comparer == null);
entries[i].hashCode = (uint)entries[i].key.GetHashCode();
}
}
}
// Assign member variables after both arrays allocated to guard against corruption from OOM if second fails
_buckets = new int[newSize];
#if BIT64
_fastModMultiplier = HashHelpers.GetFastModMultiplier((uint)newSize);
#endif
for (int i = 0; i < count; i++)
{
if (entries[i].next >= -1)
{
ref int bucket = ref GetBucket(entries[i].hashCode);
// Value in _buckets is 1-based
entries[i].next = bucket - 1;
// Value in _buckets is 1-based
bucket = i + 1;
}
}
_entries = entries;
}
// The overload Remove(TKey key, out TValue value) is a copy of this method with one additional
// statement to copy the value for entry being removed into the output parameter.
// Code has been intentionally duplicated for performance reasons.
public bool Remove(TKey key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (_buckets != null)
{
Debug.Assert(_entries != null, "entries should be non-null");
uint collisionCount = 0;
uint hashCode = (uint)(_comparer?.GetHashCode(key) ?? key.GetHashCode());
ref int bucket = ref GetBucket(hashCode);
Entry[]? entries = _entries;
int last = -1;
// Value in buckets is 1-based
int i = bucket - 1;
while (i >= 0)
{
ref Entry entry = ref entries[i];
if (entry.hashCode == hashCode && (_comparer?.Equals(entry.key, key) ?? EqualityComparer<TKey>.Default.Equals(entry.key, key)))
{
if (last < 0)
{
// Value in buckets is 1-based
bucket = entry.next + 1;
}
else
{
entries[last].next = entry.next;
}
Debug.Assert((StartOfFreeList - _freeList) < 0, "shouldn't underflow because max hashtable length is MaxPrimeArrayLength = 0x7FEFFFFD(2146435069) _freelist underflow threshold 2147483646");
entry.next = StartOfFreeList - _freeList;
if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>())
{
entry.key = default!;
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>())
{
entry.value = default!;
}
_freeList = i;
_freeCount++;
return true;
}
last = i;
i = entry.next;
collisionCount++;
if (collisionCount > (uint)entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
}
}
return false;
}
// This overload is a copy of the overload Remove(TKey key) with one additional
// statement to copy the value for entry being removed into the output parameter.
// Code has been intentionally duplicated for performance reasons.
public bool Remove(TKey key, [MaybeNullWhen(false)] out TValue value)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (_buckets != null)
{
Debug.Assert(_entries != null, "entries should be non-null");
uint collisionCount = 0;
uint hashCode = (uint)(_comparer?.GetHashCode(key) ?? key.GetHashCode());
ref int bucket = ref GetBucket(hashCode);
Entry[]? entries = _entries;
int last = -1;
// Value in buckets is 1-based
int i = bucket - 1;
while (i >= 0)
{
ref Entry entry = ref entries[i];
if (entry.hashCode == hashCode && (_comparer?.Equals(entry.key, key) ?? EqualityComparer<TKey>.Default.Equals(entry.key, key)))
{
if (last < 0)
{
// Value in buckets is 1-based
bucket = entry.next + 1;
}
else
{
entries[last].next = entry.next;
}
value = entry.value;
Debug.Assert((StartOfFreeList - _freeList) < 0, "shouldn't underflow because max hashtable length is MaxPrimeArrayLength = 0x7FEFFFFD(2146435069) _freelist underflow threshold 2147483646");
entry.next = StartOfFreeList - _freeList;
if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>())
{
entry.key = default!;
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>())
{
entry.value = default!;
}
_freeList = i;
_freeCount++;
return true;
}
last = i;
i = entry.next;
collisionCount++;
if (collisionCount > (uint)entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
}
}
value = default!;
return false;
}
public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
{
ref TValue valRef = ref FindValue(key);
if (!Unsafe.IsNullRef(ref valRef))
{
value = valRef;
return true;
}
value = default!;
return false;
}
public bool TryAdd(TKey key, TValue value)
=> TryInsert(key, value, InsertionBehavior.None);
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly => false;
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
=> CopyTo(array, index);
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (array.Rank != 1)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
if (array.GetLowerBound(0) != 0)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
if ((uint)index > (uint)array.Length)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (array.Length - index < Count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
if (array is KeyValuePair<TKey, TValue>[] pairs)
{
CopyTo(pairs, index);
}
else if (array is DictionaryEntry[] dictEntryArray)
{
Entry[]? entries = _entries;
for (int i = 0; i < _count; i++)
{
if (entries![i].next >= -1)
{
dictEntryArray[index++] = new DictionaryEntry(entries[i].key, entries[i].value);
}
}
}
else
{
object[]? objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
try
{
int count = _count;
Entry[]? entries = _entries;
for (int i = 0; i < count; i++)
{
if (entries![i].next >= -1)
{
objects[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value);
}
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
IEnumerator IEnumerable.GetEnumerator()
=> new Enumerator(this, Enumerator.KeyValuePair);
/// <summary>
/// Ensures that the dictionary can hold up to 'capacity' entries without any further expansion of its backing storage
/// </summary>
public int EnsureCapacity(int capacity)
{
if (capacity < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
int currentCapacity = _entries == null ? 0 : _entries.Length;
if (currentCapacity >= capacity)
return currentCapacity;
_version++;
if (_buckets == null)
return Initialize(capacity);
int newSize = HashHelpers.GetPrime(capacity);
Resize(newSize, forceNewHashCodes: false);
return newSize;
}
/// <summary>
/// Sets the capacity of this dictionary to what it would be if it had been originally initialized with all its entries
///
/// This method can be used to minimize the memory overhead
/// once it is known that no new elements will be added.
///
/// To allocate minimum size storage array, execute the following statements:
///
/// dictionary.Clear();
/// dictionary.TrimExcess();
/// </summary>
public void TrimExcess()
=> TrimExcess(Count);
/// <summary>
/// Sets the capacity of this dictionary to hold up 'capacity' entries without any further expansion of its backing storage
///
/// This method can be used to minimize the memory overhead
/// once it is known that no new elements will be added.
/// </summary>
public void TrimExcess(int capacity)
{
if (capacity < Count)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
int newSize = HashHelpers.GetPrime(capacity);
Entry[]? oldEntries = _entries;
int currentCapacity = oldEntries == null ? 0 : oldEntries.Length;
if (newSize >= currentCapacity)
return;
int oldCount = _count;
_version++;
Initialize(newSize);
Entry[]? entries = _entries;
int count = 0;
for (int i = 0; i < oldCount; i++)
{
uint hashCode = oldEntries![i].hashCode; // At this point, we know we have entries.
if (oldEntries[i].next >= -1)
{
ref Entry entry = ref entries![count];
entry = oldEntries[i];
ref int bucket = ref GetBucket(hashCode);
// Value in _buckets is 1-based
entry.next = bucket - 1;
// Value in _buckets is 1-based
bucket = count + 1;
count++;
}
}
_count = count;
_freeCount = 0;
}
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => this;
bool IDictionary.IsFixedSize => false;
bool IDictionary.IsReadOnly => false;
ICollection IDictionary.Keys => (ICollection)Keys;
ICollection IDictionary.Values => (ICollection)Values;
object? IDictionary.this[object key]
{
get
{
if (IsCompatibleKey(key))
{
ref TValue value = ref FindValue((TKey)key);
if (!Unsafe.IsNullRef(ref value))
{
return value;
}
}
return null;
}
set
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value);
try
{
TKey tempKey = (TKey)key;
try
{
this[tempKey] = (TValue)value!;
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
}
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
}
}
}
private static bool IsCompatibleKey(object key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
return key is TKey;
}
void IDictionary.Add(object key, object? value)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value);
try
{
TKey tempKey = (TKey)key;
try
{
Add(tempKey, (TValue)value!);
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
}
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
}
}
bool IDictionary.Contains(object key)
{
if (IsCompatibleKey(key))
{
return ContainsKey((TKey)key);
}
return false;
}
IDictionaryEnumerator IDictionary.GetEnumerator()
=> new Enumerator(this, Enumerator.DictEntry);
void IDictionary.Remove(object key)
{
if (IsCompatibleKey(key))
{
Remove((TKey)key);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private ref int GetBucket(uint hashCode)
{
int[] buckets = _buckets!;
#if BIT64
return ref buckets[HashHelpers.FastMod(hashCode, (uint)buckets.Length, _fastModMultiplier)];
#else
return ref buckets[hashCode % (uint)buckets.Length];
#endif
}
public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>,
IDictionaryEnumerator
{
private readonly Dictionary<TKey, TValue> _dictionary;
private readonly int _version;
private int _index;
private KeyValuePair<TKey, TValue> _current;
private readonly int _getEnumeratorRetType; // What should Enumerator.Current return?
internal const int DictEntry = 1;
internal const int KeyValuePair = 2;
internal Enumerator(Dictionary<TKey, TValue> dictionary, int getEnumeratorRetType)
{
_dictionary = dictionary;
_version = dictionary._version;
_index = 0;
_getEnumeratorRetType = getEnumeratorRetType;
_current = new KeyValuePair<TKey, TValue>();
}
public bool MoveNext()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
// Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends.
// dictionary.count+1 could be negative if dictionary.count is int.MaxValue
while ((uint)_index < (uint)_dictionary._count)
{
ref Entry entry = ref _dictionary._entries![_index++];
if (entry.next >= -1)
{
_current = new KeyValuePair<TKey, TValue>(entry.key, entry.value);
return true;
}
}
_index = _dictionary._count + 1;
_current = new KeyValuePair<TKey, TValue>();
return false;
}
public KeyValuePair<TKey, TValue> Current => _current;
public void Dispose()
{
}
object? IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
if (_getEnumeratorRetType == DictEntry)
{
return new DictionaryEntry(_current.Key, _current.Value);
}
else
{
return new KeyValuePair<TKey, TValue>(_current.Key, _current.Value);
}
}
}
void IEnumerator.Reset()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
_index = 0;
_current = new KeyValuePair<TKey, TValue>();
}
DictionaryEntry IDictionaryEnumerator.Entry
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return new DictionaryEntry(_current.Key, _current.Value);
}
}
object IDictionaryEnumerator.Key
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return _current.Key;
}
}
object? IDictionaryEnumerator.Value
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return _current.Value;
}
}
}
[DebuggerTypeProxy(typeof(DictionaryKeyCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey>
{
private readonly Dictionary<TKey, TValue> _dictionary;
public KeyCollection(Dictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
_dictionary = dictionary;
}
public Enumerator GetEnumerator()
=> new Enumerator(_dictionary);
public void CopyTo(TKey[] array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < _dictionary.Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = _dictionary._count;
Entry[]? entries = _dictionary._entries;
for (int i = 0; i < count; i++)
{
if (entries![i].next >= -1) array[index++] = entries[i].key;
}
}
public int Count => _dictionary.Count;
bool ICollection<TKey>.IsReadOnly => true;
void ICollection<TKey>.Add(TKey item)
=> ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
void ICollection<TKey>.Clear()
=> ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
bool ICollection<TKey>.Contains(TKey item)
=> _dictionary.ContainsKey(item);
bool ICollection<TKey>.Remove(TKey item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
return false;
}
IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator()
=> new Enumerator(_dictionary);
IEnumerator IEnumerable.GetEnumerator()
=> new Enumerator(_dictionary);
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (array.Rank != 1)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
if (array.GetLowerBound(0) != 0)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
if ((uint)index > (uint)array.Length)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (array.Length - index < _dictionary.Count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
if (array is TKey[] keys)
{
CopyTo(keys, index);
}
else
{
object[]? objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = _dictionary._count;
Entry[]? entries = _dictionary._entries;
try
{
for (int i = 0; i < count; i++)
{
if (entries![i].next >= -1) objects[index++] = entries[i].key;
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot;
public struct Enumerator : IEnumerator<TKey>, IEnumerator
{
private readonly Dictionary<TKey, TValue> _dictionary;
private int _index;
private readonly int _version;
[AllowNull, MaybeNull] private TKey _currentKey;
internal Enumerator(Dictionary<TKey, TValue> dictionary)
{
_dictionary = dictionary;
_version = dictionary._version;
_index = 0;
_currentKey = default;
}
public void Dispose()
{
}
public bool MoveNext()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
while ((uint)_index < (uint)_dictionary._count)
{
ref Entry entry = ref _dictionary._entries![_index++];
if (entry.next >= -1)
{
_currentKey = entry.key;
return true;
}
}
_index = _dictionary._count + 1;
_currentKey = default;
return false;
}
public TKey Current => _currentKey!;
object? IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return _currentKey;
}
}
void IEnumerator.Reset()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
_index = 0;
_currentKey = default;
}
}
}
[DebuggerTypeProxy(typeof(DictionaryValueCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue>
{
private readonly Dictionary<TKey, TValue> _dictionary;
public ValueCollection(Dictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
_dictionary = dictionary;
}
public Enumerator GetEnumerator()
=> new Enumerator(_dictionary);
public void CopyTo(TValue[] array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if ((uint)index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < _dictionary.Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = _dictionary._count;
Entry[]? entries = _dictionary._entries;
for (int i = 0; i < count; i++)
{
if (entries![i].next >= -1) array[index++] = entries[i].value;
}
}
public int Count => _dictionary.Count;
bool ICollection<TValue>.IsReadOnly => true;
void ICollection<TValue>.Add(TValue item)
=> ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
bool ICollection<TValue>.Remove(TValue item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
return false;
}
void ICollection<TValue>.Clear()
=> ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
bool ICollection<TValue>.Contains(TValue item)
=> _dictionary.ContainsValue(item);
IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator()
=> new Enumerator(_dictionary);
IEnumerator IEnumerable.GetEnumerator()
=> new Enumerator(_dictionary);
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (array.Rank != 1)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
if (array.GetLowerBound(0) != 0)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
if ((uint)index > (uint)array.Length)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (array.Length - index < _dictionary.Count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
if (array is TValue[] values)
{
CopyTo(values, index);
}
else
{
object[]? objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = _dictionary._count;
Entry[]? entries = _dictionary._entries;
try
{
for (int i = 0; i < count; i++)
{
if (entries![i].next >= -1) objects[index++] = entries[i].value!;
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot;
public struct Enumerator : IEnumerator<TValue>, IEnumerator
{
private readonly Dictionary<TKey, TValue> _dictionary;
private int _index;
private readonly int _version;
[AllowNull, MaybeNull] private TValue _currentValue;
internal Enumerator(Dictionary<TKey, TValue> dictionary)
{
_dictionary = dictionary;
_version = dictionary._version;
_index = 0;
_currentValue = default;
}
public void Dispose()
{
}
public bool MoveNext()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
while ((uint)_index < (uint)_dictionary._count)
{
ref Entry entry = ref _dictionary._entries![_index++];
if (entry.next >= -1)
{
_currentValue = entry.value;
return true;
}
}
_index = _dictionary._count + 1;
_currentValue = default;
return false;
}
public TValue Current => _currentValue!;
object? IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return _currentValue;
}
}
void IEnumerator.Reset()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
_index = 0;
_currentValue = default;
}
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using 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.Ads.GoogleAds.V10.Services
{
/// <summary>Settings for <see cref="CampaignServiceClient"/> instances.</summary>
public sealed partial class CampaignServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="CampaignServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="CampaignServiceSettings"/>.</returns>
public static CampaignServiceSettings GetDefault() => new CampaignServiceSettings();
/// <summary>Constructs a new <see cref="CampaignServiceSettings"/> object with default settings.</summary>
public CampaignServiceSettings()
{
}
private CampaignServiceSettings(CampaignServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
MutateCampaignsSettings = existing.MutateCampaignsSettings;
OnCopy(existing);
}
partial void OnCopy(CampaignServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CampaignServiceClient.MutateCampaigns</c> and <c>CampaignServiceClient.MutateCampaignsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateCampaignsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="CampaignServiceSettings"/> object.</returns>
public CampaignServiceSettings Clone() => new CampaignServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="CampaignServiceClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
internal sealed partial class CampaignServiceClientBuilder : gaxgrpc::ClientBuilderBase<CampaignServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public CampaignServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public CampaignServiceClientBuilder()
{
UseJwtAccessWithScopes = CampaignServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref CampaignServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CampaignServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override CampaignServiceClient Build()
{
CampaignServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<CampaignServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<CampaignServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private CampaignServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return CampaignServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<CampaignServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return CampaignServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => CampaignServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => CampaignServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => CampaignServiceClient.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>CampaignService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage campaigns.
/// </remarks>
public abstract partial class CampaignServiceClient
{
/// <summary>
/// The default endpoint for the CampaignService service, which is a host of "googleads.googleapis.com" and a
/// port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default CampaignService scopes.</summary>
/// <remarks>
/// The default CampaignService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
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="CampaignServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="CampaignServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="CampaignServiceClient"/>.</returns>
public static stt::Task<CampaignServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new CampaignServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="CampaignServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="CampaignServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="CampaignServiceClient"/>.</returns>
public static CampaignServiceClient Create() => new CampaignServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="CampaignServiceClient"/> 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="CampaignServiceSettings"/>.</param>
/// <returns>The created <see cref="CampaignServiceClient"/>.</returns>
internal static CampaignServiceClient Create(grpccore::CallInvoker callInvoker, CampaignServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
CampaignService.CampaignServiceClient grpcClient = new CampaignService.CampaignServiceClient(callInvoker);
return new CampaignServiceClientImpl(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 CampaignService client</summary>
public virtual CampaignService.CampaignServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes campaigns. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CampaignBudgetError]()
/// [CampaignError]()
/// [ContextError]()
/// [DatabaseError]()
/// [DateError]()
/// [DateRangeError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SettingError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </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 MutateCampaignsResponse MutateCampaigns(MutateCampaignsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes campaigns. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CampaignBudgetError]()
/// [CampaignError]()
/// [ContextError]()
/// [DatabaseError]()
/// [DateError]()
/// [DateRangeError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SettingError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </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<MutateCampaignsResponse> MutateCampaignsAsync(MutateCampaignsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes campaigns. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CampaignBudgetError]()
/// [CampaignError]()
/// [ContextError]()
/// [DatabaseError]()
/// [DateError]()
/// [DateRangeError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SettingError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </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<MutateCampaignsResponse> MutateCampaignsAsync(MutateCampaignsRequest request, st::CancellationToken cancellationToken) =>
MutateCampaignsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes campaigns. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CampaignBudgetError]()
/// [CampaignError]()
/// [ContextError]()
/// [DatabaseError]()
/// [DateError]()
/// [DateRangeError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SettingError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose campaigns are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual campaigns.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCampaignsResponse MutateCampaigns(string customerId, scg::IEnumerable<CampaignOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCampaigns(new MutateCampaignsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes campaigns. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CampaignBudgetError]()
/// [CampaignError]()
/// [ContextError]()
/// [DatabaseError]()
/// [DateError]()
/// [DateRangeError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SettingError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose campaigns are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual campaigns.
/// </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<MutateCampaignsResponse> MutateCampaignsAsync(string customerId, scg::IEnumerable<CampaignOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCampaignsAsync(new MutateCampaignsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes campaigns. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CampaignBudgetError]()
/// [CampaignError]()
/// [ContextError]()
/// [DatabaseError]()
/// [DateError]()
/// [DateRangeError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SettingError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose campaigns are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual campaigns.
/// </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<MutateCampaignsResponse> MutateCampaignsAsync(string customerId, scg::IEnumerable<CampaignOperation> operations, st::CancellationToken cancellationToken) =>
MutateCampaignsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>CampaignService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage campaigns.
/// </remarks>
public sealed partial class CampaignServiceClientImpl : CampaignServiceClient
{
private readonly gaxgrpc::ApiCall<MutateCampaignsRequest, MutateCampaignsResponse> _callMutateCampaigns;
/// <summary>
/// Constructs a client wrapper for the CampaignService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="CampaignServiceSettings"/> used within this client.</param>
public CampaignServiceClientImpl(CampaignService.CampaignServiceClient grpcClient, CampaignServiceSettings settings)
{
GrpcClient = grpcClient;
CampaignServiceSettings effectiveSettings = settings ?? CampaignServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callMutateCampaigns = clientHelper.BuildApiCall<MutateCampaignsRequest, MutateCampaignsResponse>(grpcClient.MutateCampaignsAsync, grpcClient.MutateCampaigns, effectiveSettings.MutateCampaignsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateCampaigns);
Modify_MutateCampaignsApiCall(ref _callMutateCampaigns);
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_MutateCampaignsApiCall(ref gaxgrpc::ApiCall<MutateCampaignsRequest, MutateCampaignsResponse> call);
partial void OnConstruction(CampaignService.CampaignServiceClient grpcClient, CampaignServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC CampaignService client</summary>
public override CampaignService.CampaignServiceClient GrpcClient { get; }
partial void Modify_MutateCampaignsRequest(ref MutateCampaignsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Creates, updates, or removes campaigns. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CampaignBudgetError]()
/// [CampaignError]()
/// [ContextError]()
/// [DatabaseError]()
/// [DateError]()
/// [DateRangeError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SettingError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </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 MutateCampaignsResponse MutateCampaigns(MutateCampaignsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCampaignsRequest(ref request, ref callSettings);
return _callMutateCampaigns.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes campaigns. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CampaignBudgetError]()
/// [CampaignError]()
/// [ContextError]()
/// [DatabaseError]()
/// [DateError]()
/// [DateRangeError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SettingError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </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<MutateCampaignsResponse> MutateCampaignsAsync(MutateCampaignsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCampaignsRequest(ref request, ref callSettings);
return _callMutateCampaigns.Async(request, callSettings);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>GoogleAdsField</c> resource.</summary>
public sealed partial class GoogleAdsFieldName : gax::IResourceName, sys::IEquatable<GoogleAdsFieldName>
{
/// <summary>The possible contents of <see cref="GoogleAdsFieldName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>googleAdsFields/{google_ads_field}</c>.</summary>
GoogleAdsField = 1,
}
private static gax::PathTemplate s_googleAdsField = new gax::PathTemplate("googleAdsFields/{google_ads_field}");
/// <summary>Creates a <see cref="GoogleAdsFieldName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="GoogleAdsFieldName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static GoogleAdsFieldName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new GoogleAdsFieldName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="GoogleAdsFieldName"/> with the pattern <c>googleAdsFields/{google_ads_field}</c>.
/// </summary>
/// <param name="googleAdsFieldId">The <c>GoogleAdsField</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="GoogleAdsFieldName"/> constructed from the provided ids.</returns>
public static GoogleAdsFieldName FromGoogleAdsField(string googleAdsFieldId) =>
new GoogleAdsFieldName(ResourceNameType.GoogleAdsField, googleAdsFieldId: gax::GaxPreconditions.CheckNotNullOrEmpty(googleAdsFieldId, nameof(googleAdsFieldId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="GoogleAdsFieldName"/> with pattern
/// <c>googleAdsFields/{google_ads_field}</c>.
/// </summary>
/// <param name="googleAdsFieldId">The <c>GoogleAdsField</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="GoogleAdsFieldName"/> with pattern
/// <c>googleAdsFields/{google_ads_field}</c>.
/// </returns>
public static string Format(string googleAdsFieldId) => FormatGoogleAdsField(googleAdsFieldId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="GoogleAdsFieldName"/> with pattern
/// <c>googleAdsFields/{google_ads_field}</c>.
/// </summary>
/// <param name="googleAdsFieldId">The <c>GoogleAdsField</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="GoogleAdsFieldName"/> with pattern
/// <c>googleAdsFields/{google_ads_field}</c>.
/// </returns>
public static string FormatGoogleAdsField(string googleAdsFieldId) =>
s_googleAdsField.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(googleAdsFieldId, nameof(googleAdsFieldId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="GoogleAdsFieldName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>googleAdsFields/{google_ads_field}</c></description></item>
/// </list>
/// </remarks>
/// <param name="googleAdsFieldName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="GoogleAdsFieldName"/> if successful.</returns>
public static GoogleAdsFieldName Parse(string googleAdsFieldName) => Parse(googleAdsFieldName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="GoogleAdsFieldName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>googleAdsFields/{google_ads_field}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="googleAdsFieldName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="GoogleAdsFieldName"/> if successful.</returns>
public static GoogleAdsFieldName Parse(string googleAdsFieldName, bool allowUnparsed) =>
TryParse(googleAdsFieldName, allowUnparsed, out GoogleAdsFieldName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="GoogleAdsFieldName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>googleAdsFields/{google_ads_field}</c></description></item>
/// </list>
/// </remarks>
/// <param name="googleAdsFieldName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="GoogleAdsFieldName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string googleAdsFieldName, out GoogleAdsFieldName result) =>
TryParse(googleAdsFieldName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="GoogleAdsFieldName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>googleAdsFields/{google_ads_field}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="googleAdsFieldName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="GoogleAdsFieldName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string googleAdsFieldName, bool allowUnparsed, out GoogleAdsFieldName result)
{
gax::GaxPreconditions.CheckNotNull(googleAdsFieldName, nameof(googleAdsFieldName));
gax::TemplatedResourceName resourceName;
if (s_googleAdsField.TryParseName(googleAdsFieldName, out resourceName))
{
result = FromGoogleAdsField(resourceName[0]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(googleAdsFieldName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private GoogleAdsFieldName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string googleAdsFieldId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
GoogleAdsFieldId = googleAdsFieldId;
}
/// <summary>
/// Constructs a new instance of a <see cref="GoogleAdsFieldName"/> class from the component parts of pattern
/// <c>googleAdsFields/{google_ads_field}</c>
/// </summary>
/// <param name="googleAdsFieldId">The <c>GoogleAdsField</c> ID. Must not be <c>null</c> or empty.</param>
public GoogleAdsFieldName(string googleAdsFieldId) : this(ResourceNameType.GoogleAdsField, googleAdsFieldId: gax::GaxPreconditions.CheckNotNullOrEmpty(googleAdsFieldId, nameof(googleAdsFieldId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>GoogleAdsField</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string GoogleAdsFieldId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.GoogleAdsField: return s_googleAdsField.Expand(GoogleAdsFieldId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as GoogleAdsFieldName);
/// <inheritdoc/>
public bool Equals(GoogleAdsFieldName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(GoogleAdsFieldName a, GoogleAdsFieldName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(GoogleAdsFieldName a, GoogleAdsFieldName b) => !(a == b);
}
public partial class GoogleAdsField
{
/// <summary>
/// <see cref="gagvr::GoogleAdsFieldName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal GoogleAdsFieldName ResourceNameAsGoogleAdsFieldName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::GoogleAdsFieldName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::GoogleAdsFieldName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
internal GoogleAdsFieldName GoogleAdsFieldName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::GoogleAdsFieldName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using UnityEngine.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
public class SubsurfaceScatteringManager
{
// Currently we only support SSSBuffer with one buffer. If the shader code change, it may require to update the shader manager
public const int k_MaxSSSBuffer = 1;
public int sssBufferCount { get { return k_MaxSSSBuffer; } }
RTHandleSystem.RTHandle[] m_ColorMRTs = new RTHandleSystem.RTHandle[k_MaxSSSBuffer];
RTHandleSystem.RTHandle[] m_ColorMSAAMRTs = new RTHandleSystem.RTHandle[k_MaxSSSBuffer];
bool[] m_ReuseGBufferMemory = new bool[k_MaxSSSBuffer];
// Disney SSS Model
ComputeShader m_SubsurfaceScatteringCS;
int m_SubsurfaceScatteringKernel;
int m_SubsurfaceScatteringKernelMSAA;
Material m_CombineLightingPass;
RTHandleSystem.RTHandle m_HTile;
// End Disney SSS Model
// Need an extra buffer on some platforms
RTHandleSystem.RTHandle m_CameraFilteringBuffer;
// This is use to be able to read stencil value in compute shader
Material m_CopyStencilForSplitLighting;
bool m_MSAASupport = false;
// List of every diffusion profile data we need
Vector4[] thicknessRemaps;
Vector4[] shapeParams;
Vector4[] transmissionTintsAndFresnel0;
Vector4[] disabledTransmissionTintsAndFresnel0;
Vector4[] worldScales;
Vector4[] filterKernels;
float[] diffusionProfileHashes;
int[] diffusionProfileUpdate;
DiffusionProfileSettings[] setDiffusionProfiles;
HDRenderPipelineAsset hdAsset;
DiffusionProfileSettings defaultDiffusionProfile;
int activeDiffusionProfileCount;
public uint texturingModeFlags; // 1 bit/profile: 0 = PreAndPostScatter, 1 = PostScatter
public uint transmissionFlags; // 1 bit/profile: 0 = regular, 1 = thin
public SubsurfaceScatteringManager()
{
}
public void InitSSSBuffers(GBufferManager gbufferManager, RenderPipelineSettings settings)
{
// Reset the msaa flag
m_MSAASupport = settings.supportMSAA;
if (settings.supportedLitShaderMode == RenderPipelineSettings.SupportedLitShaderMode.ForwardOnly) //forward only
{
// In case of full forward we must allocate the render target for forward SSS (or reuse one already existing)
// TODO: Provide a way to reuse a render target
m_ColorMRTs[0] = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: GraphicsFormat.R8G8B8A8_SRGB, xrInstancing: true, useDynamicScale: true, name: "SSSBuffer");
m_ReuseGBufferMemory [0] = false;
}
// We need to allocate the texture if we are in forward or both in case one of the cameras is in enable forward only mode
if (m_MSAASupport)
{
m_ColorMSAAMRTs[0] = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: GraphicsFormat.R8G8B8A8_SRGB, enableMSAA: true, bindTextureMS: true, xrInstancing: true, useDynamicScale: true, name: "SSSBufferMSAA");
}
if ((settings.supportedLitShaderMode & RenderPipelineSettings.SupportedLitShaderMode.DeferredOnly) != 0) //deferred or both
{
// In case of deferred, we must be in sync with SubsurfaceScattering.hlsl and lit.hlsl files and setup the correct buffers
m_ColorMRTs[0] = gbufferManager.GetSubsurfaceScatteringBuffer(0); // Note: This buffer must be sRGB (which is the case with Lit.shader)
m_ReuseGBufferMemory [0] = true;
}
if (NeedTemporarySubsurfaceBuffer() || settings.supportMSAA)
{
// Caution: must be same format as m_CameraSssDiffuseLightingBuffer
m_CameraFilteringBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: GraphicsFormat.B10G11R11_UFloatPack32, enableRandomWrite: true, xrInstancing: true, useDynamicScale: true, name: "SSSCameraFiltering"); // Enable UAV
}
// We use 8x8 tiles in order to match the native GCN HTile as closely as possible.
m_HTile = RTHandles.Alloc(size => new Vector2Int((size.x + 7) / 8, (size.y + 7) / 8), filterMode: FilterMode.Point, colorFormat: GraphicsFormat.R8_UNorm, enableRandomWrite: true, xrInstancing: true, useDynamicScale: true, name: "SSSHtile"); // Enable UAV
// fill the list with the max number of diffusion profile so we dont have
// the error: exceeds previous array size (5 vs 3). Cap to previous size.
thicknessRemaps = new Vector4[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT];
shapeParams = new Vector4[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT];
transmissionTintsAndFresnel0 = new Vector4[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT];
disabledTransmissionTintsAndFresnel0 = new Vector4[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT];
worldScales = new Vector4[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT];
filterKernels = new Vector4[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT * DiffusionProfileConstants.SSS_N_SAMPLES_NEAR_FIELD];
diffusionProfileHashes = new float[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT];
diffusionProfileUpdate = new int[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT];
setDiffusionProfiles = new DiffusionProfileSettings[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT];
}
public RTHandleSystem.RTHandle GetSSSBuffer(int index)
{
Debug.Assert(index < sssBufferCount);
return m_ColorMRTs[index];
}
public RTHandleSystem.RTHandle GetSSSBufferMSAA(int index)
{
Debug.Assert(index < sssBufferCount);
return m_ColorMSAAMRTs[index];
}
public void Build(HDRenderPipelineAsset hdAsset)
{
// Disney SSS (compute + combine)
string kernelName = hdAsset.currentPlatformRenderPipelineSettings.increaseSssSampleCount ? "SubsurfaceScatteringHQ" : "SubsurfaceScatteringMQ";
string kernelNameMSAA = hdAsset.currentPlatformRenderPipelineSettings.increaseSssSampleCount ? "SubsurfaceScatteringHQ_MSAA" : "SubsurfaceScatteringMQ_MSAA";
m_SubsurfaceScatteringCS = hdAsset.renderPipelineResources.shaders.subsurfaceScatteringCS;
m_SubsurfaceScatteringKernel = m_SubsurfaceScatteringCS.FindKernel(kernelName);
m_SubsurfaceScatteringKernelMSAA = m_SubsurfaceScatteringCS.FindKernel(kernelNameMSAA);
m_CombineLightingPass = CoreUtils.CreateEngineMaterial(hdAsset.renderPipelineResources.shaders.combineLightingPS);
m_CombineLightingPass.SetInt(HDShaderIDs._StencilMask, (int)HDRenderPipeline.StencilBitMask.LightingMask);
m_CopyStencilForSplitLighting = CoreUtils.CreateEngineMaterial(hdAsset.renderPipelineResources.shaders.copyStencilBufferPS);
m_CopyStencilForSplitLighting.SetInt(HDShaderIDs._StencilRef, (int)StencilLightingUsage.SplitLighting);
m_CopyStencilForSplitLighting.SetInt(HDShaderIDs._StencilMask, (int)HDRenderPipeline.StencilBitMask.LightingMask);
this.hdAsset = hdAsset;
defaultDiffusionProfile = hdAsset.renderPipelineResources.assets.defaultDiffusionProfile;
}
public void Cleanup()
{
CoreUtils.Destroy(m_CombineLightingPass);
CoreUtils.Destroy(m_CopyStencilForSplitLighting);
for (int i = 0; i < k_MaxSSSBuffer; ++i)
{
if (!m_ReuseGBufferMemory [i])
{
RTHandles.Release(m_ColorMRTs[i]);
}
if (m_MSAASupport)
{
RTHandles.Release(m_ColorMSAAMRTs[i]);
}
}
RTHandles.Release(m_CameraFilteringBuffer);
RTHandles.Release(m_HTile);
}
void UpdateCurrentDiffusionProfileSettings()
{
var currentDiffusionProfiles = hdAsset.diffusionProfileSettingsList;
var diffusionProfileOverride = VolumeManager.instance.stack.GetComponent<DiffusionProfileOverride>();
// If there is a diffusion profile volume override, we merge diffusion profiles that are overwritten
if (diffusionProfileOverride.active && diffusionProfileOverride.diffusionProfiles.value != null)
{
currentDiffusionProfiles = diffusionProfileOverride.diffusionProfiles.value;
}
// The first profile of the list is the default diffusion profile, used either when the diffusion profile
// on the material isn't assigned or when the diffusion profile can't be displayed (too many on the frame)
SetDiffusionProfileAtIndex(defaultDiffusionProfile, 0);
diffusionProfileHashes[0] = DiffusionProfileConstants.DIFFUSION_PROFILE_NEUTRAL_ID;
int i = 1;
foreach (var v in currentDiffusionProfiles)
{
if (v == null)
continue;
SetDiffusionProfileAtIndex(v, i++);
}
activeDiffusionProfileCount = i;
}
void SetDiffusionProfileAtIndex(DiffusionProfileSettings settings, int index)
{
// if the diffusion profile was already set and it haven't changed then there is nothing to upgrade
if (setDiffusionProfiles[index] == settings && diffusionProfileUpdate[index] == settings.updateCount)
return;
// if the settings have not yet been initialized
if (settings.profile.filterKernelNearField == null)
return;
thicknessRemaps[index] = settings.thicknessRemaps;
shapeParams[index] = settings.shapeParams;
transmissionTintsAndFresnel0[index] = settings.transmissionTintsAndFresnel0;
disabledTransmissionTintsAndFresnel0[index] = settings.disabledTransmissionTintsAndFresnel0;
worldScales[index] = settings.worldScales;
for (int j = 0, n = DiffusionProfileConstants.SSS_N_SAMPLES_NEAR_FIELD; j < n; j++)
{
filterKernels[n * index + j].x = settings.profile.filterKernelNearField[j].x;
filterKernels[n * index + j].y = settings.profile.filterKernelNearField[j].y;
if (j < DiffusionProfileConstants.SSS_N_SAMPLES_FAR_FIELD)
{
filterKernels[n * index + j].z = settings.profile.filterKernelFarField[j].x;
filterKernels[n * index + j].w = settings.profile.filterKernelFarField[j].y;
}
}
diffusionProfileHashes[index] = HDShadowUtils.Asfloat(settings.profile.hash);
// Erase previous value (This need to be done here individually as in the SSS editor we edit individual component)
uint mask = 1u << index;
texturingModeFlags &= ~mask;
transmissionFlags &= ~mask;
texturingModeFlags |= (uint)settings.profile.texturingMode << index;
transmissionFlags |= (uint)settings.profile.transmissionMode << index;
setDiffusionProfiles[index] = settings;
diffusionProfileUpdate[index] = settings.updateCount;
}
public void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd)
{
UpdateCurrentDiffusionProfileSettings();
cmd.SetGlobalInt(HDShaderIDs._DiffusionProfileCount, activeDiffusionProfileCount);
if (activeDiffusionProfileCount == 0)
return ;
// Broadcast SSS parameters to all shaders.
cmd.SetGlobalInt(HDShaderIDs._EnableSubsurfaceScattering, hdCamera.frameSettings.IsEnabled(FrameSettingsField.SubsurfaceScattering) ? 1 : 0);
unsafe
{
// Warning: Unity is not able to losslessly transfer integers larger than 2^24 to the shader system.
// Therefore, we bitcast uint to float in C#, and bitcast back to uint in the shader.
uint texturingModeFlags = this.texturingModeFlags;
uint transmissionFlags = this.transmissionFlags;
cmd.SetGlobalFloat(HDShaderIDs._TexturingModeFlags, *(float*)&texturingModeFlags);
cmd.SetGlobalFloat(HDShaderIDs._TransmissionFlags, *(float*)&transmissionFlags);
}
cmd.SetGlobalVectorArray(HDShaderIDs._ThicknessRemaps, thicknessRemaps);
cmd.SetGlobalVectorArray(HDShaderIDs._ShapeParams, shapeParams);
// To disable transmission, we simply nullify the transmissionTint
cmd.SetGlobalVectorArray(HDShaderIDs._TransmissionTintsAndFresnel0, hdCamera.frameSettings.IsEnabled(FrameSettingsField.Transmission) ? transmissionTintsAndFresnel0 : disabledTransmissionTintsAndFresnel0);
cmd.SetGlobalVectorArray(HDShaderIDs._WorldScales, worldScales);
cmd.SetGlobalFloatArray(HDShaderIDs._DiffusionProfileHashTable, diffusionProfileHashes);
}
bool NeedTemporarySubsurfaceBuffer()
{
// Caution: need to be in sync with SubsurfaceScattering.cs USE_INTERMEDIATE_BUFFER (Can't make a keyword as it is a compute shader)
// Typed UAV loads from FORMAT_R16G16B16A16_FLOAT is an optional feature of Direct3D 11.
// Most modern GPUs support it. We can avoid performing a costly copy in this case.
// TODO: test/implement for other platforms.
return SystemInfo.graphicsDeviceType != GraphicsDeviceType.PlayStation4 &&
SystemInfo.graphicsDeviceType != GraphicsDeviceType.XboxOne &&
SystemInfo.graphicsDeviceType != GraphicsDeviceType.XboxOneD3D12;
}
// Combines specular lighting and diffuse lighting with subsurface scattering.
// In the case our frame is MSAA, for the moment given the fact that we do not have read/write access to the stencil buffer of the MSAA target; we need to keep this pass MSAA
// However, the compute can't output and MSAA target so we blend the non-MSAA target into the MSAA one.
public void SubsurfaceScatteringPass(HDCamera hdCamera, CommandBuffer cmd, RTHandleSystem.RTHandle colorBufferRT,
RTHandleSystem.RTHandle diffuseBufferRT, RTHandleSystem.RTHandle depthStencilBufferRT, RTHandleSystem.RTHandle depthTextureRT)
{
if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.SubsurfaceScattering))
return;
// TODO: For MSAA, at least initially, we can only support Jimenez, because we can't
// create MSAA + UAV render targets.
using (new ProfilingSample(cmd, "Subsurface Scattering", CustomSamplerId.SubsurfaceScattering.GetSampler()))
{
// For Jimenez we always need an extra buffer, for Disney it depends on platform
if (NeedTemporarySubsurfaceBuffer() || hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA))
{
// Clear the SSS filtering target
using (new ProfilingSample(cmd, "Clear SSS filtering target", CustomSamplerId.ClearSSSFilteringTarget.GetSampler()))
{
HDUtils.SetRenderTarget(cmd, m_CameraFilteringBuffer, ClearFlag.Color, Color.clear);
}
}
using (new ProfilingSample(cmd, "HTile for SSS", CustomSamplerId.HTileForSSS.GetSampler()))
{
// Currently, Unity does not offer a way to access the GCN HTile even on PS4 and Xbox One.
// Therefore, it's computed in a pixel shader, and optimized to only contain the SSS bit.
// Clear the HTile texture. TODO: move this to ClearBuffers(). Clear operations must be batched!
HDUtils.SetRenderTarget(cmd, m_HTile, ClearFlag.Color, Color.clear);
HDUtils.SetRenderTarget(cmd, depthStencilBufferRT); // No need for color buffer here
cmd.SetRandomWriteTarget(1, m_HTile); // This need to be done AFTER SetRenderTarget
// Generate HTile for the split lighting stencil usage. Don't write into stencil texture (shaderPassId = 2)
// Use ShaderPassID 1 => "Pass 2 - Export HTILE for stencilRef to output"
CoreUtils.DrawFullScreen(cmd, m_CopyStencilForSplitLighting, null, 2);
cmd.ClearRandomWriteTargets();
}
unsafe
{
// Warning: Unity is not able to losslessly transfer integers larger than 2^24 to the shader system.
// Therefore, we bitcast uint to float in C#, and bitcast back to uint in the shader.
uint texturingModeFlags = this.texturingModeFlags;
cmd.SetComputeFloatParam(m_SubsurfaceScatteringCS, HDShaderIDs._TexturingModeFlags, *(float*)&texturingModeFlags);
}
cmd.SetComputeVectorArrayParam(m_SubsurfaceScatteringCS, HDShaderIDs._WorldScales, worldScales);
cmd.SetComputeVectorArrayParam(m_SubsurfaceScatteringCS, HDShaderIDs._FilterKernels, filterKernels);
cmd.SetComputeVectorArrayParam(m_SubsurfaceScatteringCS, HDShaderIDs._ShapeParams, shapeParams);
cmd.SetComputeFloatParams(m_SubsurfaceScatteringCS, HDShaderIDs._DiffusionProfileHashTable, diffusionProfileHashes);
int sssKernel = hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA) ? m_SubsurfaceScatteringKernelMSAA : m_SubsurfaceScatteringKernel;
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, sssKernel, HDShaderIDs._DepthTexture, depthTextureRT);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, sssKernel, HDShaderIDs._SSSHTile, m_HTile);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, sssKernel, HDShaderIDs._IrradianceSource, diffuseBufferRT);
for (int i = 0; i < sssBufferCount; ++i)
{
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, sssKernel, HDShaderIDs._SSSBufferTexture[i], GetSSSBuffer(i));
}
int numTilesX = ((int)hdCamera.screenSize.x + 15) / 16;
int numTilesY = ((int)hdCamera.screenSize.y + 15) / 16;
int numTilesZ = hdCamera.computePassCount;
if (NeedTemporarySubsurfaceBuffer() || hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA))
{
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, sssKernel, HDShaderIDs._CameraFilteringBuffer, m_CameraFilteringBuffer);
// Perform the SSS filtering pass which fills 'm_CameraFilteringBufferRT'.
cmd.DispatchCompute(m_SubsurfaceScatteringCS, sssKernel, numTilesX, numTilesY, numTilesZ);
cmd.SetGlobalTexture(HDShaderIDs._IrradianceSource, m_CameraFilteringBuffer); // Cannot set a RT on a material
// Additively blend diffuse and specular lighting into 'm_CameraColorBufferRT'.
HDUtils.DrawFullScreen(cmd, m_CombineLightingPass, colorBufferRT, depthStencilBufferRT);
}
else
{
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._CameraColorTexture, colorBufferRT);
// Perform the SSS filtering pass which performs an in-place update of 'colorBuffer'.
cmd.DispatchCompute(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, numTilesX, numTilesY, numTilesZ);
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace sep02v3.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// 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.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using Analyzer.Utilities;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.ApiDesignGuidelines.Analyzers
{
/// <summary>
/// CA1724: Type names should not match namespaces
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class TypeNamesShouldNotMatchNamespacesAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA1724";
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.TypeNamesShouldNotMatchNamespacesTitle), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageDefault = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.TypeNamesShouldNotMatchNamespacesMessageDefault), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageSystem = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.TypeNamesShouldNotMatchNamespacesMessageSystem), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.TypeNamesShouldNotMatchNamespacesDescription), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
internal static DiagnosticDescriptor DefaultRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageDefault,
DiagnosticCategory.Naming,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: s_localizableDescription,
helpLinkUri: "https://msdn.microsoft.com/en-us/library/ms182257.aspx",
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor SystemRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageSystem,
DiagnosticCategory.Naming,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: s_localizableDescription,
helpLinkUri: "https://msdn.microsoft.com/en-us/library/ms182257.aspx",
customTags: WellKnownDiagnosticTags.Telemetry);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DefaultRule, SystemRule);
private static readonly object s_lock = new object();
private static ImmutableDictionary<string, string> s_wellKnownSystemNamespaceTable;
public override void Initialize(AnalysisContext analysisContext)
{
analysisContext.EnableConcurrentExecution();
analysisContext.RegisterCompilationStartAction(
compilationStartAnalysisContext =>
{
var namedTypesInCompilation = new ConcurrentBag<INamedTypeSymbol>();
compilationStartAnalysisContext.RegisterSymbolAction(
symbolAnalysisContext =>
{
var namedType = (INamedTypeSymbol)symbolAnalysisContext.Symbol;
namedTypesInCompilation.Add(namedType);
}, SymbolKind.NamedType);
compilationStartAnalysisContext.RegisterCompilationEndAction(
compilationAnalysisContext =>
{
var namespaceNamesInCompilation = new ConcurrentBag<string>();
Compilation compilation = compilationAnalysisContext.Compilation;
AddNamespacesFromCompilation(namespaceNamesInCompilation, compilation.GlobalNamespace);
/* We construct a dictionary whose keys are all the components of all the namespace names in the compilation,
* and whose values are the namespace names of which the components are a part. For example, if the compilation
* includes namespaces A.B and C.D, the dictionary will map "A" to "A", "B" to "A.B", "C" to "C", and "D" to "C.D".
* When the analyzer encounters a type name that appears in a dictionary, it will emit a diagnostic, for instance,
* "Type name "D" conflicts with namespace name "C.D"".
* A component can occur in more than one namespace (for example, you might have namespaces "A" and "A.B".).
* In that case, we have to choose one namespace to report the diagnostic on. We want to make sure that this is
* deterministic (we don't want to complain about "A" in one compilation, and about "A.B" in the next).
* By calling ToImmutableSortedSet on the list of namespace names in the compilation, we ensure that
* we'll always construct the dictionary with the same set of keys.
*/
var namespaceComponentToNamespaceNameDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
UpdateNamespaceTable(namespaceComponentToNamespaceNameDictionary, namespaceNamesInCompilation.ToImmutableSortedSet());
InitializeWellKnownSystemNamespaceTable();
foreach (INamedTypeSymbol symbol in namedTypesInCompilation)
{
string symbolName = symbol.Name;
if (s_wellKnownSystemNamespaceTable.ContainsKey(symbolName))
{
compilationAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(SystemRule, symbolName, s_wellKnownSystemNamespaceTable[symbolName]));
}
else if (namespaceComponentToNamespaceNameDictionary.ContainsKey(symbolName))
{
compilationAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(DefaultRule, symbolName, namespaceComponentToNamespaceNameDictionary[symbolName]));
}
}
});
});
}
private void AddNamespacesFromCompilation(ConcurrentBag<string> namespaceNamesInCompilation, INamespaceSymbol @namespace)
{
namespaceNamesInCompilation.Add(@namespace.ToDisplayString());
foreach (INamespaceSymbol namespaceMember in @namespace.GetNamespaceMembers())
{
AddNamespacesFromCompilation(namespaceNamesInCompilation, namespaceMember);
}
}
private void InitializeWellKnownSystemNamespaceTable()
{
if (s_wellKnownSystemNamespaceTable == null)
{
lock (s_lock)
{
if (s_wellKnownSystemNamespaceTable == null)
{
#region List of Well known System Namespaces
var wellKnownSystemNamespaces = new List<string>
{
"Microsoft.CSharp",
"Microsoft.SqlServer.Server",
"Microsoft.VisualBasic",
"Microsoft.Win32",
"Microsoft.Win32.SafeHandles",
"System",
"System.CodeDom",
"System.CodeDom.Compiler",
"System.Collections",
"System.Collections.Generic",
"System.Collections.ObjectModel",
"System.Collections.Specialized",
"System.ComponentModel",
"System.ComponentModel.Design",
"System.ComponentModel.Design.Serialization",
"System.Configuration",
"System.Configuration.Assemblies",
"System.Data",
"System.Data.Common",
"System.Data.Odbc",
"System.Data.OleDb",
"System.Data.Sql",
"System.Data.SqlClient",
"System.Data.SqlTypes",
"System.Deployment.Internal",
"System.Diagnostics",
"System.Diagnostics.CodeAnalysis",
"System.Diagnostics.SymbolStore",
"System.Drawing",
"System.Drawing.Design",
"System.Drawing.Drawing2D",
"System.Drawing.Imaging",
"System.Drawing.Printing",
"System.Drawing.Text",
"System.Globalization",
"System.IO",
"System.IO.Compression",
"System.IO.IsolatedStorage",
"System.IO.Ports",
"System.Media",
"System.Net",
"System.Net.Cache",
"System.Net.Configuration",
"System.Net.Mail",
"System.Net.Mime",
"System.Net.NetworkInformation",
"System.Net.Security",
"System.Net.Sockets",
"System.Reflection",
"System.Reflection.Emit",
"System.Resources",
"System.Runtime",
"System.Runtime.CompilerServices",
"System.Runtime.ConstrainedExecution",
"System.Runtime.Hosting",
"System.Runtime.InteropServices",
"System.Runtime.InteropServices.ComTypes",
"System.Runtime.InteropServices.Expando",
"System.Runtime.Remoting",
"System.Runtime.Remoting.Activation",
"System.Runtime.Remoting.Channels",
"System.Runtime.Remoting.Contexts",
"System.Runtime.Remoting.Lifetime",
"System.Runtime.Remoting.Messaging",
"System.Runtime.Remoting.Metadata",
"System.Runtime.Remoting.Metadata.W3cXsd2001",
"System.Runtime.Remoting.Proxies",
"System.Runtime.Remoting.Services",
"System.Runtime.Serialization",
"System.Runtime.Serialization.Formatters",
"System.Runtime.Serialization.Formatters.Binary",
"System.Runtime.Versioning",
"System.Security",
"System.Security.AccessControl",
"System.Security.Authentication",
"System.Security.Cryptography",
"System.Security.Cryptography.X509Certificates",
"System.Security.Permissions",
"System.Security.Policy",
"System.Security.Principal",
"System.Text",
"System.Text.RegularExpressions",
"System.Threading",
"System.Timers",
"System.Web",
"System.Web.Caching",
"System.Web.Compilation",
"System.Web.Configuration",
"System.Web.Configuration.Internal",
"System.Web.Handlers",
"System.Web.Hosting",
"System.Web.Mail",
"System.Web.Management",
"System.Web.Profile",
"System.Web.Security",
"System.Web.SessionState",
"System.Web.UI",
"System.Web.UI.Adapters",
"System.Web.UI.HtmlControls",
"System.Web.UI.WebControls",
"System.Web.UI.WebControls.Adapters",
"System.Web.UI.WebControls.WebParts",
"System.Web.Util",
"System.Windows.Forms",
"System.Windows.Forms.ComponentModel.Com2Interop",
"System.Windows.Forms.Design",
"System.Windows.Forms.Layout",
"System.Windows.Forms.PropertyGridInternal",
"System.Windows.Forms.VisualStyles",
"System.Xml",
"System.Xml.Schema",
"System.Xml.Serialization",
"System.Xml.Serialization.Advanced",
"System.Xml.Serialization.Configuration",
"System.Xml.XPath",
"System.Xml.Xsl"
};
#endregion
var wellKnownSystemNamespaceTable = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
UpdateNamespaceTable(wellKnownSystemNamespaceTable, wellKnownSystemNamespaces);
s_wellKnownSystemNamespaceTable = wellKnownSystemNamespaceTable.ToImmutableDictionary();
}
}
}
}
private static void UpdateNamespaceTable(Dictionary<string, string> namespaceTable, IList<string> namespaces)
{
if (namespaces == null)
{
return;
}
foreach (string namespaceName in namespaces)
{
UpdateNamespaceTable(namespaceTable, namespaceName);
}
}
private static void UpdateNamespaceTable(Dictionary<string, string> namespaceTable, string namespaceName)
{
foreach (string word in namespaceName.Split('.'))
{
if (!namespaceTable.ContainsKey(word))
namespaceTable.Add(word, namespaceName);
}
}
}
}
| |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using CommandLine;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V10.Common;
using Google.Ads.GoogleAds.V10.Errors;
using Google.Ads.GoogleAds.V10.Resources;
using Google.Ads.GoogleAds.V10.Services;
using System;
using System.Collections.Generic;
using static Google.Ads.GoogleAds.V10.Enums.ProductCustomAttributeIndexEnum.Types;
using static Google.Ads.GoogleAds.V10.Enums.ProductTypeLevelEnum.Types;
namespace Google.Ads.GoogleAds.Examples.V10
{
/// <summary>
/// This code example adds a shopping listing scope to a shopping campaign. The example will
/// construct and add a new listing scope which will act as the inventory filter for the
/// campaign. The campaign will only advertise products that match the following requirements:
///
/// <ul>
/// <li>Brand is "google"</li>
/// <li>Custom label 0 is "top_selling_products"</li>
/// <li>Product type (level 1) is "electronics"</li>
/// <li>Product type(level 2) is "smartphones"</li>
/// </ul>
///
/// Only one listing scope is allowed per campaign. Remove any existing listing scopes before
/// running this code example.
/// </summary>
public class AddListingScope : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="AddListingScope"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The Google Ads customer ID for which the call is made.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The Google Ads customer ID for which the call is made.")]
public long CustomerId { get; set; }
/// <summary>
/// The campaign to which listing scope is added.
/// </summary>
[Option("campaignId", Required = true, HelpText =
"The campaign to which listing scope is added.")]
public long CampaignId { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = new Options();
CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult(
delegate (Options o)
{
options = o;
return 0;
}, delegate (IEnumerable<Error> errors)
{
// The Google Ads customer ID for which the call is made.
options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE");
// The campaign to which listing scope is added.
options.CampaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE");
return 0;
});
AddListingScope codeExample = new AddListingScope();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.CampaignId);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This code example adds a shopping listing scope to a shopping campaign. The example " +
"will construct and add a new listing scope which will act as the inventory filter " +
"for the campaign. The campaign will only advertise products that match the " +
"following requirements: \n" +
" - Brand is 'google'\n" +
" - Custom label 0 is 'top_selling_products'\n" +
" - Product type (level 1) is 'electronics'\n" +
" - Product type (level 2) is 'smartphones'\n" +
"Only one listing scope is allowed per campaign. Remove any existing listing scopes " +
"before running this code example.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="campaignId">The campaign to which listing scope is added.</param>
public void Run(GoogleAdsClient client, long customerId, long campaignId)
{
// Get the CampaignCriterionService.
CampaignCriterionServiceClient campaignCriterionService =
client.GetService(Services.V10.CampaignCriterionService);
// A listing scope allows you to filter the products that will be included in a given
// campaign. You can specify multiple dimensions with conditions that must be met for
// a product to be included in a campaign.
// A typical ListingScope might only have a few dimensions. This example demonstrates
// a range of different dimensions you could use.
ListingScopeInfo listingScope = new ListingScopeInfo()
{
Dimensions =
{
// Creates a ProductBrand dimension set to "google".
new ListingDimensionInfo()
{
ProductBrand = new ProductBrandInfo()
{
Value = "google"
}
},
// Creates a ProductCustomAttribute dimension for INDEX0 set to
// "top_selling_products".
new ListingDimensionInfo()
{
ProductCustomAttribute = new ProductCustomAttributeInfo()
{
Index = ProductCustomAttributeIndex.Index0,
Value = "top_selling_products"
}
},
// Creates a ProductType dimension for LEVEL1 set to "electronics".
new ListingDimensionInfo()
{
ProductType = new ProductTypeInfo()
{
Level = ProductTypeLevel.Level1,
Value = "electronics"
}
},
// Creates a ProductType dimension for LEVEL2 set to "smartphones".
new ListingDimensionInfo()
{
ProductType = new ProductTypeInfo()
{
Level = ProductTypeLevel.Level2,
Value = "smartphones"
}
},
}
};
string campaignResourceName = ResourceNames.Campaign(customerId, campaignId);
// Creates a campaign criterion to store the listing scope.
CampaignCriterion campaignCriterion = new CampaignCriterion()
{
Campaign = campaignResourceName,
ListingScope = listingScope
};
CampaignCriterionOperation operation = new CampaignCriterionOperation()
{
Create = campaignCriterion
};
try
{
// Calls the mutate method to add the campaign criterion.
MutateCampaignCriteriaResponse response =
campaignCriterionService.MutateCampaignCriteria(
customerId.ToString(), new[] { operation });
Console.WriteLine($"Added {response.Results.Count} campaign criteria:");
foreach (MutateCampaignCriterionResult result in response.Results)
{
Console.WriteLine(result.ResourceName);
}
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
}
}
| |
/*
* 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 Mono.Addins;
using Mono.Addins.Description;
using Mono.Addins.Setup;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace OpenSim.Framework
{
/// <summary>
/// Manager for registries and plugins
/// </summary>
public class PluginManager : SetupService
{
public AddinRegistry PluginRegistry;
public PluginManager(AddinRegistry registry)
: base(registry)
{
PluginRegistry = registry;
}
// Show plugin info
/// <summary>
/// Addins the info.
/// </summary>
/// <returns>
/// The info.
/// </returns>
/// <param name='args'>
/// Arguments.
/// </param>
public bool AddinInfo(int ndx, out Dictionary<string, object> result)
{
Dictionary<string, object> res = new Dictionary<string, object>();
result = res;
Addin[] addins = GetSortedAddinList("RobustPlugin");
if (ndx > (addins.Length - 1))
{
MainConsole.Instance.Output("Selection out of range");
return false;
}
// author category description
Addin addin = addins[ndx];
res["author"] = addin.Description.Author;
res["category"] = addin.Description.Category;
res["description"] = addin.Description.Description;
res["name"] = addin.Name;
res["url"] = addin.Description.Url;
res["file_name"] = addin.Description.FileName;
result = res;
return true;
}
// Register a repository
/// <summary>
/// Register a repository with our server.
/// </summary>
/// <returns>
/// result of the action
/// </returns>
/// <param name='repo'>
/// The URL of the repository we want to add
/// </param>
public bool AddRepository(string repo)
{
Repositories.RegisterRepository(null, repo, true);
PluginRegistry.Rebuild(null);
return true;
}
/// <summary>
/// Checks the installed.
/// </summary>
/// <returns>
/// The installed.
/// </returns>
public string CheckInstalled()
{
return "CheckInstall";
}
// Disable a plugin
/// <summary>
/// Disables the plugin.
/// </summary>
/// <param name='args'>
/// Arguments.
/// </param>
public void DisablePlugin(string[] args)
{
Addin[] addins = GetSortedAddinList("RobustPlugin");
int n = Convert.ToInt16(args[2]);
if (n > (addins.Length - 1))
{
MainConsole.Instance.Output("Selection out of range");
return;
}
Addin addin = addins[n];
AddinManager.Registry.DisableAddin(addin.Id);
addin.Enabled = false;
return;
}
// Disable a repository
/// <summary>
/// Disables the repository.
/// </summary>
/// <param name='args'>
/// Arguments.
/// </param>
public void DisableRepository(string[] args)
{
AddinRepository[] reps = Repositories.GetRepositories();
Array.Sort(reps, (r1, r2) => r1.Title.CompareTo(r2.Title));
if (reps.Length == 0)
{
MainConsole.Instance.Output("No repositories have been registered.");
return;
}
int n = Convert.ToInt16(args[2]);
if (n > (reps.Length - 1))
{
MainConsole.Instance.Output("Selection out of range");
return;
}
AddinRepository rep = reps[n];
Repositories.SetRepositoryEnabled(rep.Url, false);
return;
}
// Enable plugin
/// <summary>
/// Enables the plugin.
/// </summary>
/// <param name='args'>
/// Arguments.
/// </param>
public void EnablePlugin(string[] args)
{
Addin[] addins = GetSortedAddinList("RobustPlugin");
int n = Convert.ToInt16(args[2]);
if (n > (addins.Length - 1))
{
MainConsole.Instance.Output("Selection out of range");
return;
}
Addin addin = addins[n];
addin.Enabled = true;
AddinManager.Registry.EnableAddin(addin.Id);
// AddinManager.Registry.Update();
if (PluginRegistry.IsAddinEnabled(addin.Id))
{
ConsoleProgressStatus ps = new ConsoleProgressStatus(false);
if (!AddinManager.AddinEngine.IsAddinLoaded(addin.Id))
{
MainConsole.Instance.Output("Ignore the following error...");
AddinManager.Registry.Rebuild(ps);
AddinManager.AddinEngine.LoadAddin(ps, addin.Id);
}
}
else
{
MainConsole.Instance.OutputFormat("Not Enabled in this domain {0}", addin.Name);
}
return;
}
// Enable repository
/// <summary>
/// Enables the repository.
/// </summary>
/// <param name='args'>
/// Arguments.
/// </param>
public void EnableRepository(string[] args)
{
AddinRepository[] reps = Repositories.GetRepositories();
Array.Sort(reps, (r1, r2) => r1.Title.CompareTo(r2.Title));
if (reps.Length == 0)
{
MainConsole.Instance.Output("No repositories have been registered.");
return;
}
int n = Convert.ToInt16(args[2]);
if (n > (reps.Length - 1))
{
MainConsole.Instance.Output("Selection out of range");
return;
}
AddinRepository rep = reps[n];
Repositories.SetRepositoryEnabled(rep.Url, true);
return;
}
/// <summary>
/// Gets the repository.
/// </summary>
public void GetRepository()
{
Repositories.UpdateAllRepositories(new ConsoleProgressStatus(false));
}
/// <summary>
/// Installs the plugin.
/// </summary>
/// <returns>
/// The plugin.
/// </returns>
/// <param name='args'>
/// Arguments.
/// </param>
public bool InstallPlugin(int ndx, out Dictionary<string, object> result)
{
Dictionary<string, object> res = new Dictionary<string, object>();
PackageCollection pack = new PackageCollection();
PackageCollection toUninstall;
DependencyCollection unresolved;
IProgressStatus ps = new ConsoleProgressStatus(false);
AddinRepositoryEntry[] available = GetSortedAvailbleAddins();
if (ndx > (available.Length - 1))
{
MainConsole.Instance.Output("Selection out of range");
result = res;
return false;
}
AddinRepositoryEntry aentry = available[ndx];
Package p = Package.FromRepository(aentry);
pack.Add(p);
ResolveDependencies(ps, pack, out toUninstall, out unresolved);
// Attempt to install the plugin disabled
if (Install(ps, pack) == true)
{
MainConsole.Instance.Output("Ignore the following error...");
PluginRegistry.Update(ps);
Addin addin = PluginRegistry.GetAddin(aentry.Addin.Id);
PluginRegistry.DisableAddin(addin.Id);
addin.Enabled = false;
MainConsole.Instance.Output("Installation Success");
ListInstalledAddins(out res);
result = res;
return true;
}
else
{
MainConsole.Instance.Output("Installation Failed");
result = res;
return false;
}
}
// List compatible plugins in registered repositories
/// <summary>
/// Lists the available.
/// </summary>
/// <param name='result'>
/// Result.
/// </param>
public void ListAvailable(out Dictionary<string, object> result)
{
Dictionary<string, object> res = new Dictionary<string, object>();
AddinRepositoryEntry[] addins = GetSortedAvailbleAddins();
int count = 0;
foreach (AddinRepositoryEntry addin in addins)
{
Dictionary<string, object> r = new Dictionary<string, object>();
r["name"] = addin.Addin.Name;
r["version"] = addin.Addin.Version;
r["repository"] = addin.RepositoryName;
res.Add(count.ToString(), r);
count++;
}
result = res;
return;
}
/// <summary>
/// Lists the installed addins.
/// </summary>
/// <param name='result'>
/// Result.
/// </param>
public void ListInstalledAddins(out Dictionary<string, object> result)
{
Dictionary<string, object> res = new Dictionary<string, object>();
Addin[] addins = GetSortedAddinList("RobustPlugin");
if (addins.Count() < 1)
{
MainConsole.Instance.Output("Error!");
}
int count = 0;
foreach (Addin addin in addins)
{
Dictionary<string, object> r = new Dictionary<string, object>();
r["enabled"] = addin.Enabled == true ? true : false;
r["name"] = addin.LocalId;
r["version"] = addin.Version;
res.Add(count.ToString(), r);
count++;
}
result = res;
return;
}
// List registered repositories
/// <summary>
/// Lists the repositories.
/// </summary>
/// <param name='result'>
/// Result.
/// </param>
public void ListRepositories(out Dictionary<string, object> result)
{
Dictionary<string, object> res = new Dictionary<string, object>();
result = res;
AddinRepository[] reps = GetSortedAddinRepo();
if (reps.Length == 0)
{
MainConsole.Instance.Output("No repositories have been registered.");
return;
}
int count = 0;
foreach (AddinRepository rep in reps)
{
Dictionary<string, object> r = new Dictionary<string, object>();
r["enabled"] = rep.Enabled == true ? true : false;
r["name"] = rep.Name;
r["url"] = rep.Url;
res.Add(count.ToString(), r);
count++;
}
return;
}
// List available updates ** 1
/// <summary>
/// Lists the updates.
/// </summary>
public void ListUpdates()
{
IProgressStatus ps = new ConsoleProgressStatus(true);
Console.WriteLine("Looking for updates...");
Repositories.UpdateAllRepositories(ps);
Console.WriteLine("Available add-in updates:");
AddinRepositoryEntry[] entries = Repositories.GetAvailableUpdates();
foreach (AddinRepositoryEntry entry in entries)
{
Console.WriteLine(String.Format("{0}", entry.Addin.Id));
}
}
// Remove a repository from the list
/// <summary>
/// Removes the repository.
/// </summary>
/// <param name='args'>
/// Arguments.
/// </param>
public void RemoveRepository(string[] args)
{
AddinRepository[] reps = Repositories.GetRepositories();
Array.Sort(reps, (r1, r2) => r1.Title.CompareTo(r2.Title));
if (reps.Length == 0)
{
MainConsole.Instance.Output("No repositories have been registered.");
return;
}
int n = Convert.ToInt16(args[2]);
if (n > (reps.Length - 1))
{
MainConsole.Instance.Output("Selection out of range");
return;
}
AddinRepository rep = reps[n];
Repositories.RemoveRepository(rep.Url);
return;
}
// Remove plugin
/// <summary>
/// Uns the install.
/// </summary>
/// <param name='args'>
/// Arguments.
/// </param>
public void UnInstall(int ndx)
{
Addin[] addins = GetSortedAddinList("RobustPlugin");
if (ndx > (addins.Length - 1))
{
MainConsole.Instance.Output("Selection out of range");
return;
}
Addin addin = addins[ndx];
MainConsole.Instance.OutputFormat("Uninstalling plugin {0}", addin.Id);
AddinManager.Registry.DisableAddin(addin.Id);
addin.Enabled = false;
IProgressStatus ps = new ConsoleProgressStatus(false);
Uninstall(ps, addin.Id);
MainConsole.Instance.Output("Uninstall Success - restart to complete operation");
return;
}
// Sync to repositories
/// <summary>
/// Update this instance.
/// </summary>
public string Update()
{
IProgressStatus ps = new ConsoleProgressStatus(true);
Repositories.UpdateAllRepositories(ps);
return "Update";
}
/// <summary>
/// Updates the registry.
/// </summary>
public void UpdateRegistry()
{
PluginRegistry.Update();
}
#region Util
private Addin[] GetSortedAddinList(string category)
{
ArrayList xlist = new ArrayList();
ArrayList list = new ArrayList();
try
{
list.AddRange(PluginRegistry.GetAddins());
}
catch (Exception)
{
Addin[] x = xlist.ToArray(typeof(Addin)) as Addin[];
return x;
}
foreach (Addin addin in list)
{
if (addin.Description.Category == category)
xlist.Add(addin);
}
Addin[] addins = xlist.ToArray(typeof(Addin)) as Addin[];
Array.Sort(addins, (r1, r2) => r1.Id.CompareTo(r2.Id));
return addins;
}
private AddinRepository[] GetSortedAddinRepo()
{
ArrayList list = new ArrayList();
list.AddRange(Repositories.GetRepositories());
AddinRepository[] repos = list.ToArray(typeof(AddinRepository)) as AddinRepository[];
Array.Sort(repos, (r1, r2) => r1.Name.CompareTo(r2.Name));
return repos;
}
// These will let us deal with numbered lists instead
// of needing to type in the full ids
private AddinRepositoryEntry[] GetSortedAvailbleAddins()
{
ArrayList list = new ArrayList();
list.AddRange(Repositories.GetAvailableAddins());
AddinRepositoryEntry[] addins = list.ToArray(typeof(AddinRepositoryEntry)) as AddinRepositoryEntry[];
Array.Sort(addins, (r1, r2) => r1.Addin.Id.CompareTo(r2.Addin.Id));
return addins;
}
private void Testing()
{
Addin[] list = Registry.GetAddins();
var addins = list.Where(a => a.Description.Category == "RobustPlugin");
foreach (Addin addin in addins)
{
MainConsole.Instance.OutputFormat("Addin {0}", addin.Name);
}
}
#endregion Util
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using Orleans.Concurrency;
using Orleans.Runtime;
namespace Orleans.Serialization
{
using System.Runtime.CompilerServices;
internal static class TypeUtilities
{
internal static bool IsOrleansPrimitive(this TypeInfo typeInfo)
{
var t = typeInfo.AsType();
return typeInfo.IsPrimitive || typeInfo.IsEnum || t == typeof(string) || t == typeof(DateTime) || t == typeof(Decimal) || (typeInfo.IsArray && typeInfo.GetElementType().GetTypeInfo().IsOrleansPrimitive());
}
static readonly ConcurrentDictionary<Type, bool> shallowCopyableTypes = new ConcurrentDictionary<Type, bool>();
static readonly ConcurrentDictionary<Type, string> typeNameCache = new ConcurrentDictionary<Type, string>();
static readonly ConcurrentDictionary<Type, string> typeKeyStringCache = new ConcurrentDictionary<Type, string>();
static readonly ConcurrentDictionary<Type, byte[]> typeKeyCache = new ConcurrentDictionary<Type, byte[]>();
static TypeUtilities()
{
shallowCopyableTypes[typeof(Decimal)] = true;
shallowCopyableTypes[typeof(DateTime)] = true;
shallowCopyableTypes[typeof(TimeSpan)] = true;
shallowCopyableTypes[typeof(IPAddress)] = true;
shallowCopyableTypes[typeof(IPEndPoint)] = true;
shallowCopyableTypes[typeof(SiloAddress)] = true;
shallowCopyableTypes[typeof(GrainId)] = true;
shallowCopyableTypes[typeof(ActivationId)] = true;
shallowCopyableTypes[typeof(ActivationAddress)] = true;
shallowCopyableTypes[typeof(CorrelationId)] = true;
shallowCopyableTypes[typeof(string)] = true;
shallowCopyableTypes[typeof(Immutable<>)] = true;
shallowCopyableTypes[typeof(CancellationToken)] = true;
}
internal static bool IsOrleansShallowCopyable(this Type t)
{
bool result;
if (shallowCopyableTypes.TryGetValue(t, out result))
{
return result;
}
var typeInfo = t.GetTypeInfo();
if (typeInfo.IsPrimitive || typeInfo.IsEnum)
{
shallowCopyableTypes[t] = true;
return true;
}
if (typeInfo.GetCustomAttributes(typeof(ImmutableAttribute), false).Any())
{
shallowCopyableTypes[t] = true;
return true;
}
if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(Immutable<>))
{
shallowCopyableTypes[t] = true;
return true;
}
if (typeInfo.IsValueType && !typeInfo.IsGenericType && !typeInfo.IsGenericTypeDefinition)
{
result = IsValueTypeFieldsShallowCopyable(typeInfo);
shallowCopyableTypes[t] = result;
return result;
}
shallowCopyableTypes[t] = false;
return false;
}
private static bool IsValueTypeFieldsShallowCopyable(TypeInfo typeInfo)
{
return typeInfo.GetFields().All(f => f.FieldType != typeInfo.AsType() && IsOrleansShallowCopyable(f.FieldType));
}
internal static bool IsSpecializationOf(this Type t, Type match)
{
var typeInfo = t.GetTypeInfo();
return typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == match;
}
internal static string OrleansTypeName(this Type t)
{
string name;
if (typeNameCache.TryGetValue(t, out name))
return name;
name = TypeUtils.GetTemplatedName(t, _ => !_.IsGenericParameter);
typeNameCache[t] = name;
return name;
}
public static byte[] OrleansTypeKey(this Type t)
{
byte[] key;
if (typeKeyCache.TryGetValue(t, out key))
return key;
key = Encoding.UTF8.GetBytes(t.OrleansTypeKeyString());
typeKeyCache[t] = key;
return key;
}
public static string OrleansTypeKeyString(this Type t)
{
string key;
if (typeKeyStringCache.TryGetValue(t, out key))
return key;
var typeInfo = t.GetTypeInfo();
var sb = new StringBuilder();
if (typeInfo.IsGenericTypeDefinition)
{
sb.Append(GetBaseTypeKey(t));
sb.Append('\'');
sb.Append(typeInfo.GetGenericArguments().Length);
}
else if (typeInfo.IsGenericType)
{
sb.Append(GetBaseTypeKey(t));
sb.Append('<');
var first = true;
foreach (var genericArgument in t.GetGenericArguments())
{
if (!first)
{
sb.Append(',');
}
first = false;
sb.Append(OrleansTypeKeyString(genericArgument));
}
sb.Append('>');
}
else if (t.IsArray)
{
sb.Append(OrleansTypeKeyString(t.GetElementType()));
sb.Append('[');
if (t.GetArrayRank() > 1)
{
sb.Append(',', t.GetArrayRank() - 1);
}
sb.Append(']');
}
else
{
sb.Append(GetBaseTypeKey(t));
}
key = sb.ToString();
typeKeyStringCache[t] = key;
return key;
}
private static string GetBaseTypeKey(Type t)
{
var typeInfo = t.GetTypeInfo();
string namespacePrefix = "";
if ((typeInfo.Namespace != null) && !typeInfo.Namespace.StartsWith("System.") && !typeInfo.Namespace.Equals("System"))
{
namespacePrefix = typeInfo.Namespace + '.';
}
if (typeInfo.IsNestedPublic)
{
return namespacePrefix + OrleansTypeKeyString(typeInfo.DeclaringType) + "." + typeInfo.Name;
}
return namespacePrefix + typeInfo.Name;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public static string GetLocationSafe(this Assembly a)
{
if (a.IsDynamic)
{
return "dynamic";
}
try
{
return a.Location;
}
catch (Exception)
{
return "unknown";
}
}
public static bool IsTypeIsInaccessibleForSerialization(Type type, Module fromModule, Assembly fromAssembly)
{
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsGenericTypeDefinition)
{
// Guard against invalid type constraints, which appear when generating code for some languages.
foreach (var parameter in typeInfo.GenericTypeParameters)
{
if (parameter.GetTypeInfo().GetGenericParameterConstraints().Any(IsSpecialClass))
{
return true;
}
}
}
if (!typeInfo.IsVisible && type.IsConstructedGenericType)
{
foreach (var inner in typeInfo.GetGenericArguments())
{
if (IsTypeIsInaccessibleForSerialization(inner, fromModule, fromAssembly))
{
return true;
}
}
if (IsTypeIsInaccessibleForSerialization(typeInfo.GetGenericTypeDefinition(), fromModule, fromAssembly))
{
return true;
}
}
if ((typeInfo.IsNotPublic || !typeInfo.IsVisible) && !AreInternalsVisibleTo(typeInfo.Assembly, fromAssembly))
{
// subtype is defined in a different assembly from the outer type
if (!typeInfo.Module.Equals(fromModule))
{
return true;
}
// subtype defined in a different assembly from the one we are generating serializers for.
if (!typeInfo.Assembly.Equals(fromAssembly))
{
return true;
}
}
// For arrays, check the element type.
if (typeInfo.IsArray)
{
if (IsTypeIsInaccessibleForSerialization(typeInfo.GetElementType(), fromModule, fromAssembly))
{
return true;
}
}
// For nested types, check that the declaring type is accessible.
if (typeInfo.IsNested)
{
if (IsTypeIsInaccessibleForSerialization(typeInfo.DeclaringType, fromModule, fromAssembly))
{
return true;
}
}
return typeInfo.IsNestedPrivate || typeInfo.IsNestedFamily || type.IsPointer;
}
/// <summary>
/// Returns true if <paramref name="fromAssembly"/> has exposed its internals to <paramref name="toAssembly"/>, false otherwise.
/// </summary>
/// <param name="fromAssembly">The assembly containing internal types.</param>
/// <param name="toAssembly">The assembly requiring access to internal types.</param>
/// <returns>
/// true if <paramref name="fromAssembly"/> has exposed its internals to <paramref name="toAssembly"/>, false otherwise
/// </returns>
private static bool AreInternalsVisibleTo(Assembly fromAssembly, Assembly toAssembly)
{
// If the to-assembly is null, it cannot have internals visible to it.
if (toAssembly == null)
{
return false;
}
// Check InternalsVisibleTo attributes on the from-assembly, pointing to the to-assembly.
var serializationAssemblyName = toAssembly.GetName().FullName;
var internalsVisibleTo = fromAssembly.GetCustomAttributes<InternalsVisibleToAttribute>();
return internalsVisibleTo.Any(_ => _.AssemblyName == serializationAssemblyName);
}
private static bool IsSpecialClass(Type type)
{
return type == typeof(object) || type == typeof(Array) || type == typeof(Delegate) ||
type == typeof(Enum) || type == typeof(ValueType);
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
//#define PARSER_TRACE
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.AspNet.Razor.Generator;
using Microsoft.AspNet.Razor.Parser;
using Microsoft.AspNet.Razor.Parser.SyntaxTree;
using Microsoft.AspNet.Razor.Text;
using Xunit;
namespace Microsoft.AspNet.Razor.Test.Framework
{
public abstract class ParserTestBase
{
protected static Block IgnoreOutput = new IgnoreOutputBlock();
public SpanFactory Factory { get; private set; }
protected ParserTestBase()
{
Factory = CreateSpanFactory();
}
public abstract ParserBase CreateMarkupParser();
public abstract ParserBase CreateCodeParser();
protected abstract ParserBase SelectActiveParser(ParserBase codeParser, ParserBase markupParser);
public virtual ParserContext CreateParserContext(ITextDocument input, ParserBase codeParser, ParserBase markupParser)
{
return new ParserContext(input, codeParser, markupParser, SelectActiveParser(codeParser, markupParser));
}
protected abstract SpanFactory CreateSpanFactory();
protected virtual void ParseBlockTest(string document)
{
ParseBlockTest(document, null, false, new RazorError[0]);
}
protected virtual void ParseBlockTest(string document, bool designTimeParser)
{
ParseBlockTest(document, null, designTimeParser, new RazorError[0]);
}
protected virtual void ParseBlockTest(string document, params RazorError[] expectedErrors)
{
ParseBlockTest(document, false, expectedErrors);
}
protected virtual void ParseBlockTest(string document, bool designTimeParser, params RazorError[] expectedErrors)
{
ParseBlockTest(document, null, designTimeParser, expectedErrors);
}
protected virtual void ParseBlockTest(string document, Block expectedRoot)
{
ParseBlockTest(document, expectedRoot, false, null);
}
protected virtual void ParseBlockTest(string document, Block expectedRoot, bool designTimeParser)
{
ParseBlockTest(document, expectedRoot, designTimeParser, null);
}
protected virtual void ParseBlockTest(string document, Block expectedRoot, params RazorError[] expectedErrors)
{
ParseBlockTest(document, expectedRoot, false, expectedErrors);
}
protected virtual void ParseBlockTest(string document, Block expectedRoot, bool designTimeParser, params RazorError[] expectedErrors)
{
RunParseTest(document, parser => parser.ParseBlock, expectedRoot, (expectedErrors ?? new RazorError[0]).ToList(), designTimeParser);
}
protected virtual void SingleSpanBlockTest(string document, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters = AcceptedCharacters.Any)
{
SingleSpanBlockTest(document, blockType, spanType, acceptedCharacters, expectedError: null);
}
protected virtual void SingleSpanBlockTest(string document, string spanContent, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters = AcceptedCharacters.Any)
{
SingleSpanBlockTest(document, spanContent, blockType, spanType, acceptedCharacters, expectedErrors: null);
}
protected virtual void SingleSpanBlockTest(string document, BlockType blockType, SpanKind spanType, params RazorError[] expectedError)
{
SingleSpanBlockTest(document, document, blockType, spanType, expectedError);
}
protected virtual void SingleSpanBlockTest(string document, string spanContent, BlockType blockType, SpanKind spanType, params RazorError[] expectedErrors)
{
SingleSpanBlockTest(document, spanContent, blockType, spanType, AcceptedCharacters.Any, expectedErrors ?? new RazorError[0]);
}
protected virtual void SingleSpanBlockTest(string document, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters, params RazorError[] expectedError)
{
SingleSpanBlockTest(document, document, blockType, spanType, acceptedCharacters, expectedError);
}
protected virtual void SingleSpanBlockTest(string document, string spanContent, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters, params RazorError[] expectedErrors)
{
BlockBuilder builder = new BlockBuilder();
builder.Type = blockType;
ParseBlockTest(
document,
ConfigureAndAddSpanToBlock(
builder,
Factory.Span(spanType, spanContent, spanType == SpanKind.Markup)
.Accepts(acceptedCharacters)),
expectedErrors ?? new RazorError[0]);
}
protected virtual void ParseDocumentTest(string document) {
ParseDocumentTest(document, null, false);
}
protected virtual void ParseDocumentTest(string document, Block expectedRoot) {
ParseDocumentTest(document, expectedRoot, false, null);
}
protected virtual void ParseDocumentTest(string document, Block expectedRoot, params RazorError[] expectedErrors) {
ParseDocumentTest(document, expectedRoot, false, expectedErrors);
}
protected virtual void ParseDocumentTest(string document, bool designTimeParser) {
ParseDocumentTest(document, null, designTimeParser);
}
protected virtual void ParseDocumentTest(string document, Block expectedRoot, bool designTimeParser) {
ParseDocumentTest(document, expectedRoot, designTimeParser, null);
}
protected virtual void ParseDocumentTest(string document, Block expectedRoot, bool designTimeParser, params RazorError[] expectedErrors) {
RunParseTest(document, parser => parser.ParseDocument, expectedRoot, expectedErrors, designTimeParser, parserSelector: c => c.MarkupParser);
}
protected virtual ParserResults ParseDocument(string document) {
return ParseDocument(document, designTimeParser: false);
}
protected virtual ParserResults ParseDocument(string document, bool designTimeParser) {
return RunParse(document, parser => parser.ParseDocument, designTimeParser, parserSelector: c => c.MarkupParser);
}
protected virtual ParserResults ParseBlock(string document) {
return ParseBlock(document, designTimeParser: false);
}
protected virtual ParserResults ParseBlock(string document, bool designTimeParser) {
return RunParse(document, parser => parser.ParseBlock, designTimeParser);
}
protected virtual ParserResults RunParse(string document, Func<ParserBase, Action> parserActionSelector, bool designTimeParser, Func<ParserContext, ParserBase> parserSelector = null)
{
parserSelector = parserSelector ?? (c => c.ActiveParser);
// Create the source
ParserResults results = null;
using (SeekableTextReader reader = new SeekableTextReader(document))
{
try
{
ParserBase codeParser = CreateCodeParser();
ParserBase markupParser = CreateMarkupParser();
ParserContext context = CreateParserContext(reader, codeParser, markupParser);
context.DesignTimeMode = designTimeParser;
codeParser.Context = context;
markupParser.Context = context;
// Run the parser
parserActionSelector(parserSelector(context))();
results = context.CompleteParse();
}
finally
{
if (results != null && results.Document != null)
{
WriteTraceLine(String.Empty);
WriteTraceLine("Actual Parse Tree:");
WriteNode(0, results.Document);
}
}
}
return results;
}
protected virtual void RunParseTest(string document, Func<ParserBase, Action> parserActionSelector, Block expectedRoot, IList<RazorError> expectedErrors, bool designTimeParser, Func<ParserContext, ParserBase> parserSelector = null)
{
// Create the source
ParserResults results = RunParse(document, parserActionSelector, designTimeParser, parserSelector);
// Evaluate the results
if (!ReferenceEquals(expectedRoot, IgnoreOutput))
{
EvaluateResults(results, expectedRoot, expectedErrors);
}
}
[Conditional("PARSER_TRACE")]
private void WriteNode(int indent, SyntaxTreeNode node)
{
string content = node.ToString().Replace("\r", "\\r")
.Replace("\n", "\\n")
.Replace("{", "{{")
.Replace("}", "}}");
if (indent > 0)
{
content = new String('.', indent * 2) + content;
}
WriteTraceLine(content);
Block block = node as Block;
if (block != null)
{
foreach (SyntaxTreeNode child in block.Children)
{
WriteNode(indent + 1, child);
}
}
}
public static void EvaluateResults(ParserResults results, Block expectedRoot)
{
EvaluateResults(results, expectedRoot, null);
}
public static void EvaluateResults(ParserResults results, Block expectedRoot, IList<RazorError> expectedErrors)
{
EvaluateParseTree(results.Document, expectedRoot);
EvaluateRazorErrors(results.ParserErrors, expectedErrors);
}
public static void EvaluateParseTree(Block actualRoot, Block expectedRoot)
{
// Evaluate the result
ErrorCollector collector = new ErrorCollector();
// Link all the nodes
expectedRoot.LinkNodes();
if (expectedRoot == null)
{
Assert.Null(actualRoot);
}
else
{
Assert.NotNull(actualRoot);
EvaluateSyntaxTreeNode(collector, actualRoot, expectedRoot);
if (collector.Success)
{
WriteTraceLine("Parse Tree Validation Succeeded:\r\n{0}", collector.Message);
}
else
{
Assert.True(false, String.Format("\r\n{0}", collector.Message));
}
}
}
private static void EvaluateSyntaxTreeNode(ErrorCollector collector, SyntaxTreeNode actual, SyntaxTreeNode expected)
{
if (actual == null)
{
AddNullActualError(collector, actual, expected);
}
if (actual.IsBlock != expected.IsBlock)
{
AddMismatchError(collector, actual, expected);
}
else
{
if (expected.IsBlock)
{
EvaluateBlock(collector, (Block)actual, (Block)expected);
}
else
{
EvaluateSpan(collector, (Span)actual, (Span)expected);
}
}
}
private static void EvaluateSpan(ErrorCollector collector, Span actual, Span expected)
{
if (!Equals(expected, actual))
{
AddMismatchError(collector, actual, expected);
}
else
{
AddPassedMessage(collector, expected);
}
}
private static void EvaluateBlock(ErrorCollector collector, Block actual, Block expected)
{
if (actual.Type != expected.Type || !expected.CodeGenerator.Equals(actual.CodeGenerator))
{
AddMismatchError(collector, actual, expected);
}
else
{
AddPassedMessage(collector, expected);
using (collector.Indent())
{
IEnumerator<SyntaxTreeNode> expectedNodes = expected.Children.GetEnumerator();
IEnumerator<SyntaxTreeNode> actualNodes = actual.Children.GetEnumerator();
while (expectedNodes.MoveNext())
{
if (!actualNodes.MoveNext())
{
collector.AddError("{0} - FAILED :: No more elements at this node", expectedNodes.Current);
}
else
{
EvaluateSyntaxTreeNode(collector, actualNodes.Current, expectedNodes.Current);
}
}
while (actualNodes.MoveNext())
{
collector.AddError("End of Node - FAILED :: Found Node: {0}", actualNodes.Current);
}
}
}
}
private static void AddPassedMessage(ErrorCollector collector, SyntaxTreeNode expected)
{
collector.AddMessage("{0} - PASSED", expected);
}
private static void AddMismatchError(ErrorCollector collector, SyntaxTreeNode actual, SyntaxTreeNode expected)
{
collector.AddError("{0} - FAILED :: Actual: {1}", expected, actual);
}
private static void AddNullActualError(ErrorCollector collector, SyntaxTreeNode actual, SyntaxTreeNode expected)
{
collector.AddError("{0} - FAILED :: Actual: << Null >>", expected);
}
public static void EvaluateRazorErrors(IList<RazorError> actualErrors, IList<RazorError> expectedErrors)
{
// Evaluate the errors
if (expectedErrors == null || expectedErrors.Count == 0)
{
Assert.True(actualErrors.Count == 0,
String.Format("Expected that no errors would be raised, but the following errors were:\r\n{0}", FormatErrors(actualErrors)));
}
else
{
Assert.True(expectedErrors.Count == actualErrors.Count,
String.Format("Expected that {0} errors would be raised, but {1} errors were.\r\nExpected Errors: \r\n{2}\r\nActual Errors: \r\n{3}",
expectedErrors.Count,
actualErrors.Count,
FormatErrors(expectedErrors),
FormatErrors(actualErrors)));
Assert.Equal(expectedErrors.ToArray(), actualErrors.ToArray());
}
WriteTraceLine("Expected Errors were raised:\r\n{0}", FormatErrors(expectedErrors));
}
public static string FormatErrors(IList<RazorError> errors)
{
if (errors == null)
{
return "\t<< No Errors >>";
}
StringBuilder builder = new StringBuilder();
foreach (RazorError err in errors)
{
builder.AppendFormat("\t{0}", err);
builder.AppendLine();
}
return builder.ToString();
}
[Conditional("PARSER_TRACE")]
private static void WriteTraceLine(string format, params object[] args)
{
Trace.WriteLine(String.Format(format, args));
}
protected virtual Block CreateSimpleBlockAndSpan(string spanContent, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters = AcceptedCharacters.Any)
{
SpanConstructor span = Factory.Span(spanType, spanContent, spanType == SpanKind.Markup).Accepts(acceptedCharacters);
BlockBuilder b = new BlockBuilder()
{
Type = blockType
};
return ConfigureAndAddSpanToBlock(b, span);
}
protected virtual Block ConfigureAndAddSpanToBlock(BlockBuilder block, SpanConstructor span)
{
switch (block.Type)
{
case BlockType.Markup:
span.With(new MarkupCodeGenerator());
break;
case BlockType.Statement:
span.With(new StatementCodeGenerator());
break;
case BlockType.Expression:
block.CodeGenerator = new ExpressionCodeGenerator();
span.With(new ExpressionCodeGenerator());
break;
}
block.Children.Add(span);
return block.Build();
}
private class IgnoreOutputBlock : Block
{
public IgnoreOutputBlock() : base(BlockType.Template, Enumerable.Empty<SyntaxTreeNode>(), null) { }
}
}
}
| |
using System;
using System.IO;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Collections.Generic;
using Platform.IO;
using Platform.Text;
using Platform.Network.ExtensibleServer;
using Platform.Network.ExtensibleServer.CommandServer;
using Platform.VirtualFileSystem.Network.Text.Protocol;
namespace Platform.VirtualFileSystem.Network.Text.Server
{
public class FileSystemCommandConnection
: CommandConnection, ITextConnection
{
public new FileSystemNetworkServer NetworkServer
{
get
{
return (FileSystemNetworkServer)base.NetworkServer;
}
set
{
base.NetworkServer = value;
}
}
public virtual IFileSystemManager FileSystemManager { get; private set; }
public virtual Stream RawReadStream
{
get
{
if (this.rawReadStream == null)
{
var stream = base.ReadStream;
this.rawReadStream = new MeteringStream(base.ReadStream);
this.rawReadStream.ReadMeter.ValueChanged += delegate(object sender, MeterEventArgs eventArgs)
{
};
}
return this.rawReadStream;
}
}
private MeteringStream rawReadStream;
public virtual Stream RawWriteStream
{
get
{
if (this.rawWriteStream == null)
{
this.rawWriteStream = new MeteringStream(base.WriteStream);
this.rawWriteStream.WriteMeter.ValueChanged += delegate(object sender, MeterEventArgs eventArgs)
{
};
}
return this.rawWriteStream;
}
}
private MeteringStream rawWriteStream;
public override Stream ReadStream
{
get
{
if (this.readStream == null)
{
this.ReadStream = this.RawWriteStream;
}
return this.readStream;
}
set
{
if (value != this.readStream)
{
this.readStream = new ChunkingStream(value, 4096, Encoding.ASCII.GetBytes("\n"));
this.readStream.ReadMeter.ValueChanged += delegate(object sender, MeterEventArgs eventArgs)
{
var ratio = ((double)(long)this.rawReadStream.ReadMeter.Value) / ((double)(long)eventArgs.Value) * 100.0d;
ProtocolTrafficLogger.LogTraffic
(
String.Format("type=read, compressed={0}, uncompressed={1}, compressed-percent={2:F2}%", this.rawReadStream.ReadMeter.Value, eventArgs.Value, ratio)
);
};
this.reader = new StreamReader(this.readStream);
}
}
}
private ChunkingStream readStream = null;
private TextReader reader;
public override Stream WriteStream
{
get
{
if (this.writeStream == null)
{
this.WriteStream = this.RawWriteStream;
}
return this.writeStream;
}
set
{
if (value != this.writeStream)
{
this.writeStream = new MeteringStream(value);
this.writeStream.WriteMeter.ValueChanged += delegate(object sender, MeterEventArgs eventArgs)
{
double ratio;
ratio = ((double)(long)this.rawWriteStream.WriteMeter.Value) / ((double)(long)eventArgs.Value) * 100.0d;
ProtocolTrafficLogger.LogTraffic
(
String.Format("type=write, compressed={0}, uncompressed={1}, compressed-percent={2:F2}%", this.rawWriteStream.WriteMeter.Value, eventArgs.Value, ratio)
);
};
this.Writer = new StreamWriter(this.writeStream, new UTF8Encoding(false));
}
}
}
private MeteringStream writeStream = null;
public class DeterministicBinaryReadContext
: IDisposable
{
private bool acquired = false;
private readonly FileSystemCommandConnection connection;
internal DeterministicBinaryReadContext(FileSystemCommandConnection connection)
{
this.acquired = false;
this.connection = connection;
}
internal void Aquire()
{
if (this.acquired)
{
throw new InvalidOperationException();
}
this.acquired = true;
this.connection.readStream.ChunkingEnabled = false;
}
internal void Release()
{
if (!this.acquired)
{
throw new InvalidOperationException();
}
this.acquired = false;
this.connection.readStream.ChunkingEnabled = true;
}
public void Dispose()
{
Release();
}
}
private readonly DeterministicBinaryReadContext binaryReadContext;
public virtual DeterministicBinaryReadContext AquireBinaryReadContext()
{
this.binaryReadContext.Aquire();
return this.binaryReadContext;
}
public virtual IDictionary<object, object> ConnectionState
{
get
{
return this.connectionState;
}
}
private readonly IDictionary<object, object> connectionState = new Dictionary<object, object>();
public virtual TextWriter Writer { get; private set; }
protected ProtocolReadLog ProtocolReadLogger { get; private set; }
protected ProtocolWriteLog ProtocolWriteLogger { get; private set; }
public virtual void WriteTextPartialBlock(char[] buffer, int index, int count)
{
if (ProtocolWriteLogger.IsEnabled)
{
ProtocolWriteLogger.LogWritePartial(buffer, index, count);
}
this.Writer.Write(buffer, index, count);
}
public virtual void WriteTextPartialBlock(string text)
{
if (ProtocolWriteLogger.IsEnabled)
{
ProtocolWriteLogger.LogWritePartial(text);
}
this.Writer.Write(text);
}
public virtual void WriteTextBlock(string text)
{
if (ProtocolWriteLogger.IsEnabled)
{
ProtocolWriteLogger.LogWrite(text);
}
this.Writer.Write(text);
this.Writer.Write("\r\n");
}
public virtual void WriteTextBlock(string format, params object[] args)
{
if (ProtocolWriteLogger.IsEnabled)
{
ProtocolWriteLogger.LogWrite(format, args);
}
this.Writer.Write(format, args);
this.Writer.Write("\r\n");
}
public virtual string ReadTextBlock()
{
bool overflow;
var retval = this.reader.ReadLine(10 * 1024 * 1024, out overflow);
retval = retval.Trim(' ', '\r', '\n');
if (overflow)
{
throw new OverflowException("Input Too Long");
}
if (ProtocolReadLogger.IsEnabled)
{
ProtocolReadLogger.LogRead(retval);
}
return retval;
}
private static int connectionIdCount = 0;
private readonly int connectionId;
public ProtocolTrafficLog ProtocolTrafficLogger { get; private set; }
public FileSystemCommandConnection(NetworkServer networkServer, Socket socket, IFileSystemManager fileSystemManager)
: base(networkServer, socket)
{
this.connectionId = Interlocked.Increment(ref connectionIdCount);
this.ProtocolReadLogger = new ProtocolReadLog(this.connectionId.ToString());
this.ProtocolWriteLogger = new ProtocolWriteLog(this.connectionId.ToString());
this.ProtocolTrafficLogger = new ProtocolTrafficLog(this.connectionId.ToString());
this.FileSystemManager = fileSystemManager;
this.ReadStream = RawReadStream;
this.WriteStream = RawWriteStream;
System.Reflection.AssemblyName name;
name = GetType().Assembly.GetName();
WriteTextBlock("NETVFS {0}.{1}", name.Version.Major, name.Version.Minor);
this.binaryReadContext = new DeterministicBinaryReadContext(this);
}
public override void Run()
{
this.RunLevel = HandshakeRunLevel.Default;
base.Run();
}
public virtual void WriteOk()
{
WriteTextBlock(ResponseCodes.OK);
}
public virtual void WriteOk(params object[] extraArgs)
{
if (extraArgs.Length % 2 != 0)
{
throw new ArgumentException();
}
if (extraArgs.Length > 0)
{
var text = new StringBuilder(255);
text.Append(ResponseCodes.OK);
if (extraArgs.Length > 0)
{
text.Append(' ');
for (var i = 0; i < extraArgs.Length; i += 2)
{
text.Append(extraArgs[i].ToString());
text.Append('=');
text.Append('\"');
text.Append(extraArgs[i + 1].ToString());
text.Append('\"');
text.Append(" ");
}
text.Length--;
}
WriteTextBlock(text.ToString());
}
else
{
WriteTextBlock(ResponseCodes.OK);
}
Flush();
}
public override void Flush()
{
try
{
this.Writer.Flush();
base.Flush();
}
catch (IOException)
{
throw;
}
catch (Exception)
{
this.RunLevel = DisconnectedRunLevel.Default;
}
}
public virtual void WriteReady()
{
WriteTextBlock(ResponseCodes.READY);
Flush();
}
public virtual void WriteError(string errorCode)
{
WriteError(errorCode, "");
}
public virtual void WriteError(string errorCode, string messageFormat, params object[] args)
{
var s = String.Format(messageFormat, args);
if (s.Length > 0)
{
WriteTextBlock("{0} CODE={1} MESSAGE=\"{2}\"", ResponseCodes.ERROR, errorCode, TextConversion.ToEscapedHexString(s));
}
else
{
WriteTextBlock("{0} CODE={1}", ResponseCodes.ERROR, errorCode);
}
Flush();
}
public virtual void ReadReady()
{
string s = this.ReadTextBlock();
if (!s.EqualsIgnoreCase(ResponseCodes.READY))
{
throw new FileSystemServerException(ErrorCodes.UNEXPECTED_COMMAND, s);
}
}
protected override void BuildAndProcessSingleCommand()
{
WriteReady();
base.BuildAndProcessSingleCommand();
}
protected override void UnhandledExceptionFromSingleCommand(Exception e)
{
try
{
Predicate<char> isEscapeChar = (c) => c == '\n' || c == '\"' || c == '\r';
if (e is DirectoryNodeNotFoundException)
{
WriteTextBlock("{0} CODE={1} URI=\"{2}\"",
ResponseCodes.ERROR, ErrorCodes.DIRECTORY_NOT_FOUND, ((NodeNotFoundException)e).NodeAddress.Uri);
Flush();
}
else if (e is FileNodeNotFoundException)
{
WriteTextBlock("{0} CODE={1} URI=\"{2}\"",
ResponseCodes.ERROR, ErrorCodes.FILE_NOT_FOUND, ((NodeNotFoundException)e).NodeAddress.Uri);
Flush();
}
else if (e is NodeNotFoundException)
{
WriteTextBlock("{0} CODE={1} URI=\"{2}\"",
ResponseCodes.ERROR, ErrorCodes.FILE_NOT_FOUND, ((NodeNotFoundException)e).NodeAddress.Uri);
Flush();
}
else if (e is ObjectDisposedException)
{
this.RunLevel = DisconnectedRunLevel.Default;
}
else if (e is IOException)
{
WriteTextBlock("{0} CODE={1} DETAILS=\"{2}: {3}\"",
ResponseCodes.ERROR, ErrorCodes.IO_ERROR, e.GetType().Name, TextConversion.ToEscapedHexString(e.ToString(), isEscapeChar));
Flush();
}
else if (e is FileSystemServerException)
{
WriteTextBlock("{0} CODE={1} DETAILS=\"{2}\"",
ResponseCodes.ERROR, ((FileSystemServerException)e).ErrorCode, TextConversion.ToEscapedHexString(e.ToString(), isEscapeChar));
Flush();
}
else if (e is CommandNotSupportedException)
{
WriteTextBlock("{0} CODE={1} DETAILS=\"{2}\"",
ResponseCodes.ERROR, ErrorCodes.INVALID_COMMAND, TextConversion.ToEscapedHexString(e.ToString(), isEscapeChar));
Flush();
}
else if (e is ProcessNextCommandException)
{
return;
}
else if (e is MalformedUriException)
{
WriteTextBlock("{0} CODE={1} DETAILS=\"{2}\"",
ResponseCodes.ERROR, ErrorCodes.MALFORMED_URI, TextConversion.ToEscapedHexString(e.ToString(), isEscapeChar));
Flush();
}
else if (e is NotSupportedException)
{
WriteTextBlock("{0} CODE={1} DETAILS=\"{2}\"",
ResponseCodes.ERROR, ErrorCodes.NOT_SUPPORTED, TextConversion.ToEscapedHexString(e.ToString(), isEscapeChar));
Flush();
}
else if (e is UnauthorizedAccessException)
{
WriteTextBlock("{0} CODE={1} DETAILS=\"{2}\"",
ResponseCodes.ERROR, ErrorCodes.UNAUTHORISED, TextConversion.ToEscapedHexString(e.ToString(), isEscapeChar));
Flush();
}
else if (e is DisconnectedException)
{
RunLevel = DisconnectedRunLevel.Default;
}
else
{
WriteTextBlock("{0} CODE={1} DETAILS=\"{2}\"",
ResponseCodes.ERROR, ErrorCodes.UNEXPECTED, TextConversion.ToEscapedHexString(e.ToString(), isEscapeChar));
Flush();
RunLevel = DisconnectedRunLevel.Default;
}
}
catch (IOException)
{
RunLevel = DisconnectedRunLevel.Default;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.ComponentModel.Container test cases
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
// Ivan N. Zlatev (contact i-nZ.net)
// Copyright (c) 2006 Novell, Inc. (http://www.novell.com)
// Copyright (c) 2006 Ivan N. Zlatev
//
using System.ComponentModel.Design;
using System.Linq;
using Xunit;
namespace System.ComponentModel.Tests
{
internal class TestService
{
}
internal class TestContainer : Container
{
ServiceContainer _services = new ServiceContainer();
bool allowDuplicateNames;
public TestContainer()
{
_services.AddService(typeof(TestService), new TestService());
}
public bool AllowDuplicateNames
{
get { return allowDuplicateNames; }
set { allowDuplicateNames = value; }
}
protected override object GetService(Type serviceType)
{
return _services.GetService(serviceType);
}
public new void RemoveWithoutUnsiting(IComponent component)
{
base.RemoveWithoutUnsiting(component);
}
public void InvokeValidateName(IComponent component, string name)
{
ValidateName(component, name);
}
protected override void ValidateName(IComponent component, string name)
{
if (AllowDuplicateNames)
return;
base.ValidateName(component, name);
}
public bool Contains(IComponent component)
{
bool found = false;
foreach (IComponent c in Components)
{
if (component.Equals(c))
{
found = true;
break;
}
}
return found;
}
public new void Dispose(bool disposing)
{
base.Dispose(disposing);
}
}
internal class TestComponent : Component
{
public override ISite Site
{
get
{
return base.Site;
}
set
{
base.Site = value;
if (value != null)
{
Assert.NotNull(value.GetService(typeof(ISite)));
Assert.NotNull(value.GetService(typeof(TestService)));
}
}
}
public bool IsDisposed
{
get { return disposed; }
}
public bool ThrowOnDispose
{
get { return throwOnDispose; }
set { throwOnDispose = value; }
}
protected override void Dispose(bool disposing)
{
if (ThrowOnDispose)
throw new InvalidOperationException();
base.Dispose(disposing);
disposed = true;
}
private bool disposed;
private bool throwOnDispose;
}
public class ContainerTest
{
private TestContainer _container;
public ContainerTest()
{
_container = new TestContainer();
}
[Fact] // Add (IComponent)
public void Add1()
{
TestContainer containerA = new TestContainer();
TestContainer containerB = new TestContainer();
ISite siteA;
ISite siteB;
TestComponent compA = new TestComponent();
Assert.Null(compA.Site);
TestComponent compB = new TestComponent();
Assert.Null(compB.Site);
Assert.Equal(0, containerA.Components.Count);
Assert.Equal(0, containerB.Components.Count);
containerA.Add(compA);
siteA = compA.Site;
Assert.NotNull(siteA);
Assert.Same(compA, siteA.Component);
Assert.Same(containerA, siteA.Container);
Assert.False(siteA.DesignMode);
Assert.Null(siteA.Name);
containerA.Add(compB);
siteB = compB.Site;
Assert.NotNull(siteB);
Assert.Same(compB, siteB.Component);
Assert.Same(containerA, siteB.Container);
Assert.False(siteB.DesignMode);
Assert.Null(siteB.Name);
Assert.False(object.ReferenceEquals(siteA, siteB));
Assert.Equal(2, containerA.Components.Count);
Assert.Equal(0, containerB.Components.Count);
Assert.Same(compA, containerA.Components[0]);
Assert.Same(compB, containerA.Components[1]);
// check effect of adding component that is already member of
// another container
containerB.Add(compA);
Assert.False(object.ReferenceEquals(siteA, compA.Site));
siteA = compA.Site;
Assert.NotNull(siteA);
Assert.Same(compA, siteA.Component);
Assert.Same(containerB, siteA.Container);
Assert.False(siteA.DesignMode);
Assert.Null(siteA.Name);
Assert.Equal(1, containerA.Components.Count);
Assert.Equal(1, containerB.Components.Count);
Assert.Same(compB, containerA.Components[0]);
Assert.Same(compA, containerB.Components[0]);
// check effect of add component twice to same container
containerB.Add(compA);
Assert.Same(siteA, compA.Site);
Assert.Equal(1, containerA.Components.Count);
Assert.Equal(1, containerB.Components.Count);
Assert.Same(compB, containerA.Components[0]);
Assert.Same(compA, containerB.Components[0]);
}
[Fact]
public void Add1_Component_Null()
{
_container.Add((IComponent)null);
Assert.Equal(0, _container.Components.Count);
}
[Fact] // Add (IComponent, String)
public void Add2()
{
TestContainer containerA = new TestContainer();
TestContainer containerB = new TestContainer();
ISite siteA;
ISite siteB;
TestComponent compA = new TestComponent();
Assert.Null(compA.Site);
TestComponent compB = new TestComponent();
Assert.Null(compB.Site);
Assert.Equal(0, containerA.Components.Count);
Assert.Equal(0, containerB.Components.Count);
containerA.Add(compA, "A");
siteA = compA.Site;
Assert.NotNull(siteA);
Assert.Same(compA, siteA.Component);
Assert.Same(containerA, siteA.Container);
Assert.False(siteA.DesignMode);
Assert.Equal("A", siteA.Name);
containerA.Add(compB, "B");
siteB = compB.Site;
Assert.NotNull(siteB);
Assert.Same(compB, siteB.Component);
Assert.Same(containerA, siteB.Container);
Assert.False(siteB.DesignMode);
Assert.Equal("B", siteB.Name);
Assert.False(object.ReferenceEquals(siteA, siteB));
Assert.Equal(2, containerA.Components.Count);
Assert.Equal(0, containerB.Components.Count);
Assert.Same(compA, containerA.Components[0]);
Assert.Same(compB, containerA.Components[1]);
// check effect of adding component that is already member of
// another container
containerB.Add(compA, "A2");
Assert.False(object.ReferenceEquals(siteA, compA.Site));
siteA = compA.Site;
Assert.NotNull(siteA);
Assert.Same(compA, siteA.Component);
Assert.Same(containerB, siteA.Container);
Assert.False(siteA.DesignMode);
Assert.Equal("A2", siteA.Name);
Assert.Equal(1, containerA.Components.Count);
Assert.Equal(1, containerB.Components.Count);
Assert.Same(compB, containerA.Components[0]);
Assert.Same(compA, containerB.Components[0]);
// check effect of add component twice to same container
containerB.Add(compA, "A2");
Assert.Same(siteA, compA.Site);
Assert.Equal("A2", siteA.Name);
Assert.Equal(1, containerA.Components.Count);
Assert.Equal(1, containerB.Components.Count);
Assert.Same(compB, containerA.Components[0]);
Assert.Same(compA, containerB.Components[0]);
// add again with different name
containerB.Add(compA, "A3");
Assert.Same(siteA, compA.Site);
Assert.Equal("A2", siteA.Name);
Assert.Equal(1, containerA.Components.Count);
Assert.Equal(1, containerB.Components.Count);
Assert.Same(compB, containerA.Components[0]);
Assert.Same(compA, containerB.Components[0]);
// check effect of add component twice to same container
containerB.Add(compA, "A2");
Assert.Same(siteA, compA.Site);
Assert.Equal("A2", siteA.Name);
}
[Fact]
public void Add_ExceedsSizeOfBuffer_Success()
{
var container = new Container();
var components = new Component[] { new Component(), new Component(), new Component(), new Component(), new Component() };
for (int i = 0; i < components.Length; i++)
{
container.Add(components[i]);
Assert.Same(components[i], container.Components[i]);
}
}
[Fact]
public void Add2_Component_Null()
{
_container.Add((IComponent)null, "A");
Assert.Equal(0, _container.Components.Count);
_container.Add(new TestComponent(), "A");
Assert.Equal(1, _container.Components.Count);
_container.Add((IComponent)null, "A");
Assert.Equal(1, _container.Components.Count);
}
[Fact]
public void Add2_Name_Duplicate()
{
TestContainer container = new TestContainer();
TestComponent c1 = new TestComponent();
container.Add(c1, "dup");
// new component, same case
TestComponent c2 = new TestComponent();
ArgumentException ex;
ex = AssertExtensions.Throws<ArgumentException>(null, () => container.Add(c2, "dup"));
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.True(ex.Message.IndexOf("'dup'") != -1);
Assert.Null(ex.ParamName);
Assert.Equal(1, container.Components.Count);
// new component, different case
TestComponent c3 = new TestComponent();
ex = AssertExtensions.Throws<ArgumentException>(null, () => container.Add(c3, "duP"));
// Duplicate component name 'duP'. Component names must be
// unique and case-insensitive
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.True(ex.Message.IndexOf("'duP'") != -1);
Assert.Null(ex.ParamName);
Assert.Equal(1, container.Components.Count);
// existing component, same case
TestComponent c4 = new TestComponent();
container.Add(c4, "C4");
Assert.Equal(2, container.Components.Count);
container.Add(c4, "dup");
Assert.Equal(2, container.Components.Count);
Assert.Equal("C4", c4.Site.Name);
// component of other container, same case
TestContainer container2 = new TestContainer();
TestComponent c5 = new TestComponent();
container2.Add(c5, "C5");
ex = AssertExtensions.Throws<ArgumentException>(null, () => container.Add(c5, "dup"));
// Duplicate component name 'dup'. Component names must be
// unique and case-insensitive
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.True(ex.Message.IndexOf("'dup'") != -1);
Assert.Null(ex.ParamName);
Assert.Equal(2, container.Components.Count);
Assert.Equal(1, container2.Components.Count);
Assert.Same(c5, container2.Components[0]);
container.AllowDuplicateNames = true;
TestComponent c6 = new TestComponent();
container.Add(c6, "dup");
Assert.Equal(3, container.Components.Count);
Assert.NotNull(c1.Site);
Assert.Equal("dup", c1.Site.Name);
Assert.NotNull(c6.Site);
Assert.Equal("dup", c6.Site.Name);
Assert.False(object.ReferenceEquals(c1.Site, c6.Site));
}
[Fact]
public void Add_SetSiteName_ReturnsExpected()
{
var component = new Component();
var container = new Container();
container.Add(component, "Name1");
Assert.Equal("Name1", component.Site.Name);
component.Site.Name = "OtherName";
Assert.Equal("OtherName", component.Site.Name);
// Setting to the same value is a nop.
component.Site.Name = "OtherName";
Assert.Equal("OtherName", component.Site.Name);
}
[Fact]
public void Add_SetSiteNameDuplicate_ThrowsArgumentException()
{
var component1 = new Component();
var component2 = new Component();
var container = new Container();
container.Add(component1, "Name1");
container.Add(component2, "Name2");
Assert.Throws<ArgumentException>(null, () => component1.Site.Name = "Name2");
}
[Fact]
public void Add_DuplicateNameWithInheritedReadOnly_AddsSuccessfully()
{
var component1 = new Component();
var component2 = new Component();
TypeDescriptor.AddAttributes(component1, new InheritanceAttribute(InheritanceLevel.InheritedReadOnly));
var container = new Container();
container.Add(component1, "Name");
container.Add(component2, "Name");
Assert.Equal(new IComponent[] { component1, component2 }, container.Components.Cast<IComponent>());
}
[Fact]
public void AddRemove()
{
TestComponent component = new TestComponent();
_container.Add(component);
Assert.NotNull(component.Site);
Assert.True(_container.Contains(component));
_container.Remove(component);
Assert.Null(component.Site);
Assert.False(_container.Contains(component));
}
[Fact] // Dispose ()
public void Dispose1()
{
TestComponent compA;
TestComponent compB;
compA = new TestComponent();
_container.Add(compA);
compB = new TestComponent();
_container.Add(compB);
_container.Dispose();
Assert.Equal(0, _container.Components.Count);
Assert.True(compA.IsDisposed);
Assert.Null(compA.Site);
Assert.True(compB.IsDisposed);
Assert.Null(compB.Site);
_container = new TestContainer();
compA = new TestComponent();
compA.ThrowOnDispose = true;
_container.Add(compA);
compB = new TestComponent();
_container.Add(compB);
Assert.Throws<InvalidOperationException>(() => _container.Dispose());
// assert that component is not removed from components until after
// Dispose of component has succeeded
Assert.Equal(0, _container.Components.Count);
Assert.False(compA.IsDisposed);
Assert.Null(compA.Site);
Assert.True(compB.IsDisposed);
Assert.Null(compB.Site);
compA.ThrowOnDispose = false;
_container = new TestContainer();
compA = new TestComponent();
_container.Add(compA);
compB = new TestComponent();
compB.ThrowOnDispose = true;
_container.Add(compB);
Assert.Throws<InvalidOperationException>(() => _container.Dispose());
Assert.Equal(1, _container.Components.Count);
Assert.Same(compA, _container.Components[0]);
Assert.False(compA.IsDisposed);
Assert.NotNull(compA.Site);
Assert.False(compB.IsDisposed);
Assert.Null(compB.Site);
compB.ThrowOnDispose = false;
}
[Fact] // Dispose (Boolean)
public void Dispose2()
{
TestComponent compA;
TestComponent compB;
compA = new TestComponent();
_container.Add(compA);
compB = new TestComponent();
_container.Add(compB);
_container.Dispose(false);
Assert.Equal(2, _container.Components.Count);
Assert.False(compA.IsDisposed);
Assert.NotNull(compA.Site);
Assert.False(compB.IsDisposed);
Assert.NotNull(compB.Site);
_container.Dispose(true);
Assert.Equal(0, _container.Components.Count);
Assert.True(compA.IsDisposed);
Assert.Null(compA.Site);
Assert.True(compB.IsDisposed);
Assert.Null(compB.Site);
compA = new TestComponent();
_container.Add(compA);
compB = new TestComponent();
_container.Add(compB);
Assert.Equal(2, _container.Components.Count);
Assert.False(compA.IsDisposed);
Assert.NotNull(compA.Site);
Assert.False(compB.IsDisposed);
Assert.NotNull(compB.Site);
_container.Dispose(true);
Assert.Equal(0, _container.Components.Count);
Assert.True(compA.IsDisposed);
Assert.Null(compA.Site);
Assert.True(compB.IsDisposed);
Assert.Null(compB.Site);
}
[Fact]
public void Dispose_Recursive()
{
MyComponent comp = new MyComponent();
Container container = comp.CreateContainer();
comp.Dispose();
Assert.Equal(0, container.Components.Count);
}
[Fact]
public void GetService()
{
object service;
GetServiceContainer container = new GetServiceContainer();
container.Add(new MyComponent());
service = container.GetService(typeof(MyComponent));
Assert.Null(service);
service = container.GetService(typeof(Component));
Assert.Null(service);
service = container.GetService(typeof(IContainer));
Assert.Same(container, service);
service = container.GetService((Type)null);
Assert.Null(service);
}
[Fact]
public void Remove()
{
TestComponent compA;
TestComponent compB;
ISite siteA;
ISite siteB;
compA = new TestComponent();
_container.Add(compA);
siteA = compA.Site;
compB = new TestComponent();
_container.Add(compB);
siteB = compB.Site;
_container.Remove(compB);
Assert.Same(siteA, compA.Site);
Assert.Null(compB.Site);
Assert.Equal(1, _container.Components.Count);
Assert.Same(compA, _container.Components[0]);
// remove component with no site
compB = new TestComponent();
_container.Remove(compB);
Assert.Same(siteA, compA.Site);
Assert.Null(compB.Site);
Assert.Equal(1, _container.Components.Count);
Assert.Same(compA, _container.Components[0]);
// remove component associated with other container
TestContainer container2 = new TestContainer();
compB = new TestComponent();
container2.Add(compB);
siteB = compB.Site;
_container.Remove(compB);
Assert.Same(siteA, compA.Site);
Assert.Same(siteB, compB.Site);
Assert.Equal(1, _container.Components.Count);
Assert.Same(compA, _container.Components[0]);
Assert.Equal(1, container2.Components.Count);
Assert.Same(compB, container2.Components[0]);
}
[Fact]
public void Remove_Component_Null()
{
_container.Add(new TestComponent());
_container.Remove((IComponent)null);
Assert.Equal(1, _container.Components.Count);
}
[Fact]
public void RemoveWithoutUnsiting()
{
TestComponent compA;
TestComponent compB;
ISite siteA;
ISite siteB;
compA = new TestComponent();
_container.Add(compA);
siteA = compA.Site;
compB = new TestComponent();
_container.Add(compB);
siteB = compB.Site;
_container.RemoveWithoutUnsiting(compB);
Assert.Same(siteA, compA.Site);
Assert.Same(siteB, compB.Site);
Assert.Equal(1, _container.Components.Count);
Assert.Same(compA, _container.Components[0]);
// remove component with no site
compB = new TestComponent();
_container.RemoveWithoutUnsiting(compB);
Assert.Same(siteA, compA.Site);
Assert.Null(compB.Site);
Assert.Equal(1, _container.Components.Count);
Assert.Same(compA, _container.Components[0]);
// remove component associated with other container
TestContainer container2 = new TestContainer();
compB = new TestComponent();
container2.Add(compB);
siteB = compB.Site;
_container.RemoveWithoutUnsiting(compB);
Assert.Same(siteA, compA.Site);
Assert.Same(siteB, compB.Site);
Assert.Equal(1, _container.Components.Count);
Assert.Same(compA, _container.Components[0]);
Assert.Equal(1, container2.Components.Count);
Assert.Same(compB, container2.Components[0]);
}
[Fact]
public void RemoveWithoutUnsiting_Component_Null()
{
ISite site;
TestComponent component;
component = new TestComponent();
_container.Add(component);
site = component.Site;
_container.RemoveWithoutUnsiting((IComponent)null);
Assert.Same(site, component.Site);
Assert.Equal(1, _container.Components.Count);
Assert.Same(component, _container.Components[0]);
}
[Fact]
public void Remove_NoSuchComponentWithoutUnsiting_Nop()
{
var component1 = new Component();
var component2 = new Component();
var container = new SitingContainer();
container.Add(component1);
container.Add(component2);
container.DoRemoveWithoutUnsitting(component1);
Assert.Equal(1, container.Components.Count);
container.DoRemoveWithoutUnsitting(component1);
Assert.Equal(1, container.Components.Count);
container.DoRemoveWithoutUnsitting(component2);
Assert.Equal(0, container.Components.Count);
}
private class SitingContainer : Container
{
public void DoRemoveWithoutUnsitting(IComponent component) => RemoveWithoutUnsiting(component);
}
[Fact]
public void ValidateName_Component_Null()
{
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => _container.InvokeValidateName((IComponent)null, "A"));
Assert.Equal(typeof(ArgumentNullException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Equal("component", ex.ParamName);
}
[Fact]
public void ValidateName_Name_Null()
{
TestComponent compA = new TestComponent();
_container.Add(compA, (string)null);
TestComponent compB = new TestComponent();
_container.InvokeValidateName(compB, (string)null);
}
[Fact]
public void ValidateName_Name_Duplicate()
{
TestComponent compA = new TestComponent();
_container.Add(compA, "dup");
// same component, same case
_container.InvokeValidateName(compA, "dup");
// existing component, same case
TestComponent compB = new TestComponent();
_container.Add(compB, "B");
ArgumentException ex;
ex = AssertExtensions.Throws<ArgumentException>(null, () => _container.InvokeValidateName(compB, "dup"));
// Duplicate component name 'duP'. Component names must be
// unique and case-insensitive
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.True(ex.Message.IndexOf("'dup'") != -1);
Assert.Null(ex.ParamName);
Assert.Equal(2, _container.Components.Count);
_container.InvokeValidateName(compB, "whatever");
// new component, different case
TestComponent compC = new TestComponent();
ex = AssertExtensions.Throws<ArgumentException>(null, () => _container.InvokeValidateName(compC, "dup"));
// Duplicate component name 'duP'. Component names must be
// unique and case-insensitive
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.True(ex.Message.IndexOf("'dup'") != -1);
Assert.Null(ex.ParamName);
Assert.Equal(2, _container.Components.Count);
_container.InvokeValidateName(compC, "whatever");
// component of other container, different case
TestContainer container2 = new TestContainer();
TestComponent compD = new TestComponent();
container2.Add(compD, "B");
ex = AssertExtensions.Throws<ArgumentException>(null, () => _container.InvokeValidateName(compD, "dup"));
// Duplicate component name 'duP'. Component names must be
// unique and case-insensitive
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.True(ex.Message.IndexOf("'dup'") != -1);
Assert.Null(ex.ParamName);
Assert.Equal(2, _container.Components.Count);
_container.InvokeValidateName(compD, "whatever");
Assert.Equal(1, container2.Components.Count);
Assert.Same(compD, container2.Components[0]);
}
[Fact]
public void Components_GetWithDefaultFilterService_ReturnsAllComponents()
{
var component1 = new SubComponent();
var component2 = new Component();
var component3 = new SubComponent();
var container = new FilterContainer { FilterService = new DefaultFilterService() };
container.Add(component1);
container.Add(component2);
container.Add(component3);
Assert.Equal(new IComponent[] { component1, component2, component3 }, container.Components.Cast<IComponent>());
}
[Fact]
public void Components_GetWithCustomFilterService_ReturnsFilteredComponents()
{
var component1 = new SubComponent();
var component2 = new Component();
var component3 = new SubComponent();
// This filter only includes SubComponents.
var container = new FilterContainer { FilterService = new CustomContainerFilterService() };
container.Add(component1);
container.Add(component2);
container.Add(component3);
Assert.Equal(new IComponent[] { component1, component3 }, container.Components.Cast<IComponent>());
}
[Fact]
public void Components_GetWithCustomFilterServiceAfterChangingComponents_ReturnsUpdatedComponents()
{
var component1 = new SubComponent();
var component2 = new Component();
var component3 = new SubComponent();
// This filter only includes SubComponents.
var container = new FilterContainer { FilterService = new CustomContainerFilterService() };
container.Add(component1);
container.Add(component2);
container.Add(component3);
Assert.Equal(new IComponent[] { component1, component3 }, container.Components.Cast<IComponent>());
container.Remove(component1);
Assert.Equal(new IComponent[] { component3 }, container.Components.Cast<IComponent>());
}
[Fact]
public void Components_GetWithNullFilterService_ReturnsUnfiltered()
{
var component1 = new SubComponent();
var component2 = new Component();
var component3 = new SubComponent();
// This filter only includes SubComponents.
var container = new FilterContainer { FilterService = new NullContainerFilterService() };
container.Add(component1);
container.Add(component2);
container.Add(component3);
Assert.Equal(new IComponent[] { component1, component2, component3 }, container.Components.Cast<IComponent>());
}
private class FilterContainer : Container
{
public ContainerFilterService FilterService { get; set; }
protected override object GetService(Type service)
{
if (service == typeof(ContainerFilterService))
{
return FilterService;
}
return base.GetService(service);
}
}
private class SubComponent : Component { }
private class DefaultFilterService : ContainerFilterService { }
private class CustomContainerFilterService : ContainerFilterService
{
public override ComponentCollection FilterComponents(ComponentCollection components)
{
SubComponent[] newComponents = components.OfType<SubComponent>().ToArray();
return new ComponentCollection(newComponents);
}
}
private class NullContainerFilterService : ContainerFilterService
{
public override ComponentCollection FilterComponents(ComponentCollection components)
{
return null;
}
}
private class MyComponent : Component
{
private Container container;
protected override void Dispose(bool disposing)
{
if (container != null)
container.Dispose();
base.Dispose(disposing);
}
public Container CreateContainer()
{
if (container != null)
throw new InvalidOperationException();
container = new Container();
container.Add(new MyComponent());
container.Add(this);
return container;
}
}
private class MyContainer : IContainer
{
private ComponentCollection components = new ComponentCollection(
new Component[0]);
public ComponentCollection Components
{
get { return components; }
}
public void Add(IComponent component)
{
}
public void Add(IComponent component, string name)
{
}
public void Remove(IComponent component)
{
}
public void Dispose()
{
}
}
public class GetServiceContainer : Container
{
public new object GetService(Type service)
{
return base.GetService(service);
}
}
}
}
| |
/*
* DcopRef.cs - Base class for remote dcop objects with callable methods.
* Is is fairly low-level, don't use it directly.
*
* Copyright (C) 2004 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace Xsharp.Dcop
{
using System;
using Xsharp;
/// <summary>
/// <para>The <see cref="T:Xsharp.Dcop.DcopRef"/> class represents remote object
/// with callable methods. Base class for all other DCOP object (see DcopBuilder
/// exapmle).
///
/// Remote object is identified by application-object-(optional)type triad.
/// Latter is not used by this implementation and have limited use in KDE (inheritance
/// mostly).
///
/// Remote object have a set of functions implemented.</para>
/// </summary>
// TODO: Split this into factory and simplier DcopRef
public class DcopRef : ICloneable
{
private string app = null;
private string obj = null;
private DcopClient client;
/// <summary>
/// <para>Tells if this DcopRef was initialised or still under construction.</para>
/// </summary>
protected bool initialised = false;
// They should not change in runtime, o cache them
protected string[] inter = null;
/// <summary>
/// <para>Constructs an empty DCOP ref. Useful if you planning to fill in and initialise
/// it later.</para>
/// </summary>
public DcopRef()
{
// TODO: Add some code there?
}
/// <summary>
/// <para>This meant to be called by QDataStream. You should use DcopRef() & Discover*()</para>
/// </summary>
///
/// <param name="app">
/// <para>'Application' identifier of this DcopRef.</para>
/// </param>
///
/// <param name="obj">
/// <para>'Object' identifier of this DcopRef.</para>
/// </param>
public DcopRef(string app, string obj)
{
this.app = app;
this.obj = obj;
}
/// <summary>
/// <para>This is used to cast DcopRefs to subclasses in marshal code. You should use DcopRef() &
/// Discover*()</para>
/// </summary>
///
/// <param name="parent">
/// <para>DcopRef to copy identifiers from.</para>
/// </param>
public DcopRef(DcopRef parent)
{
if(parent == null)
{
throw new ArgumentNullException("parent", "Argument cannot be null");
}
this.app = parent.App;
this.obj = parent.Obj;
}
/// <summary>
/// <para>Tries to find application on server and bind reference to application.</para>
/// </summary>
///
/// <param name="app">
/// <para>'Application' to lookup on server.</para>
/// </param>
///
/// <param name="sessioned">
/// <para>Some applications are sessioned ('app-pid'), some are not (just 'app').</para>
/// </param>
///
/// <param name="createIfNotExists">
/// <para>If this application is absent, try to start it or not.</para>
/// </param>
///
/// <exception cref="T:Xsharp.Dcop.DcopException">
/// <para>Raised if connection to application has failed.</para>
/// </exception>
public void DiscoverApplication(string app, bool sessioned, bool createIfNotExists)
{
// Discovers object
string[] apps;
string[] bits;
if(client == null)
{
DiscoverClient();
}
apps = client.registeredApplications();
for(int i = 0; i < apps.Length; i++)
{
if(sessioned)
{
bits = apps[i].Split(new char[]{'-'});
if( (String.Join("-", bits, 0, bits.Length - 1) == app) &&
(Int32.Parse(bits[bits.Length - 1]) > 0) )
{
this.app = apps[i];
return; // Will discover first found
}
}
else
{
if(apps[i] == app)
{
this.app = apps[i];
return;
}
}
}
if(createIfNotExists)
{
ServiceResult res = (ServiceResult)client.Call("klauncher", "klauncher", "serviceResult start_service_by_desktop_name(QString,QStringList)", app, null);
if(res.Result > 0) // Yes, >0, it's not error
{
throw new DcopNamingException(String.Format("Failed to discover, klauncher returned: {0}", res.ErrorMessage));
}
this.app = res.DcopName;
return;
}
throw new DcopNamingException("Failed to discover application");
}
/// <summary>
/// <para>Initialises DcopRef, checking if object exists on server.
/// You cannot change internals after calling Initialise()</para>
/// </summary>
///
/// <exception cref="T:Xsharp.Dcop.DcopException">
/// <para>Raised if connection to object has failed.</para>
/// </exception>
public void Initialise()
{
if(client == null)
{
DiscoverClient();
}
if(app == null)
{
throw new DcopConnectionException("`app' was not initialised");
}
if(obj == null)
{
this.obj = ""; // Just use default one
}
initialised = true;
string[] inter = interfaces();
for(int i = 0; i < inter.Length; i++)
{
if(inter[i] == "DCOPObject")
{
return;
}
}
initialised = false;
throw new DcopNamingException("Not an object or naming fault");
}
/// <summary>
/// <para>Calls function on this DCOP object.
/// This should be called in subclasses' stubs.</para>
/// </summary>
///
/// <param name="fun">
/// <para>Remote function to call. See DcopFunction class for syntax.</para>
/// </param>
///
/// <param name="parameters">
/// <para>Parameters to pass to function. Keep them in sync with function definition.</para>
/// </param>
///
/// <value>
/// <para>Object, received from remote app. Its type depends on remote app not function name.</para>
/// </value>
///
/// <exception cref="T:Xsharp.DcopException">
/// <para>Exception raised if there are problems either with connection or naming.</para>
/// </exception>
public Object Call(string fun, params Object[] args)
{
if(!initialised)
{
throw new DcopConnectionException("Attempt to do Call()s on non-initialised Dcop reference");
}
return client.Call(app, obj, fun, args);
}
public Object Clone()
{
DcopRef res = new DcopRef();
res.Obj = obj;
res.Client = client;
if(!initialised)
{
res.App = app;
}
else
{
res.DiscoverApplication(app, false, false);
res.Initialise();
}
return res;
}
protected void DiscoverClient()
{
if(DcopClient.MainClient == null)
{
if(Application.Primary != null)
DcopClient.MainClient = new DcopClient(Application.Primary.Display, null);
}
this.client = DcopClient.MainClient;
}
/// <summary>
/// <para>Lists objects, contained in this DcopRef's application.</para>
/// </summary>
///
/// <value>
/// <para>List of object.</para>
/// </value>
///
/// <exception cref="T:Xsharp.DcopException">
/// <para>Exception raised if there are problems either with connection or naming.</para>
/// </exception>
[DcopCall("QCStringList objects()")]
public string[] objects()
{
if(app == null)
{
throw new DcopConnectionException("`app' is null");
}
if(client == null)
{
DiscoverClient();
}
return (string[])client.Call(app, "DCOPClient", "QCStringList objects()");
}
/// <summary>
/// <para>Lists functions, avaliable in this DcopRef's object.</para>
/// </summary>
///
/// <value>
/// <para>List of functions.</para>
/// </value>
///
/// <exception cref="T:Xsharp.DcopException">
/// <para>Exception raised if there are problems either with connection or naming.</para>
/// </exception>
[DcopCall("QCStringList functions()")]
public string[] functions()
{
return (string[])Call("QCStringList functions()");
}
/// <summary>
/// <para>Lists interfaces, implemented in this DcopRef's object.</para>
/// </summary>
///
/// <value>
/// <para>List of interfaces.</para>
/// </value>
///
/// <exception cref="T:Xsharp.DcopException">
/// <para>Exception raised if there are problems either with connection or naming.</para>
/// </exception>
[DcopCall("QCStringList interfaces()")]
public string[] interfaces()
{
if(inter == null)
{
inter = (string[])Call("QCStringList interfaces()");
}
return inter;
}
/// <summary>
/// <para>Application identifier. Can not be set after DcopRef is Initialised().</para>
/// </summary>
public string App
{
get
{
return app;
}
set
{
if(initialised)
{
throw new DcopConnectionException("Attempt to change internal state while already initialised");
}
app = value;
}
}
/// <summary>
/// <para>Object identifier. Can not be set after DcopRef is Initialised().</para>
/// </summary>
public string Obj
{
get
{
return obj;
}
set
{
if(initialised)
{
throw new DcopConnectionException("Attempt to change internal state while already initialised");
}
obj = value;
}
}
/* public string Type
{
get
{
return Type;
}
}*/
/// <summary>
/// <para>DCOP client used to do calls. Can not be set after DcopRef is Initialised().</para>
/// </summary>
public DcopClient Client
{
get
{
return client;
}
set
{
if(initialised)
{
throw new DcopConnectionException("Attempt to change internal state while already initialised");
}
client = value;
}
}
}; // Class DcopRef
} // Namespace Xsharp.Dcop
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using Microsoft.Test.ModuleCore;
namespace XLinqTests
{
public class TreeManipulationTests : TestModule
{
[Fact]
[OuterLoop]
public static void ConstructorXDocument()
{
RunTestCase(new ParamsObjectsCreation { Attribute = new TestCaseAttribute { Name = "Constructors with params - XDocument" } });
}
[Fact]
[OuterLoop]
public static void ConstructorXElementArray()
{
RunTestCase(new ParamsObjectsCreationElem { Attribute = new TestCaseAttribute { Name = "Constructors with params - XElement - array", Param = 0 } }); //Param = InputParamStyle.Array
}
[Fact]
[OuterLoop]
public static void ConstructorXElementIEnumerable()
{
RunTestCase(new ParamsObjectsCreationElem { Attribute = new TestCaseAttribute { Name = "Constructors with params - XElement - IEnumerable", Param = 2 } }); //InputParamStyle.IEnumerable
}
[Fact]
[OuterLoop]
public static void ConstructorXElementNodeArray()
{
RunTestCase(new ParamsObjectsCreationElem { Attribute = new TestCaseAttribute { Name = "Constructors with params - XElement - node + array", Param = 1 } }); //InputParamStyle.SingleAndArray
}
[Fact]
[OuterLoop]
public static void IEnumerableOfXAttributeRemove()
{
RunTestCase(new XAttributeEnumRemove { Attribute = new TestCaseAttribute { Name = "IEnumerable<XAttribute>.Remove()", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void IEnumerableOfXAttributeRemoveWithRemove()
{
RunTestCase(new XAttributeEnumRemove { Attribute = new TestCaseAttribute { Name = "IEnumerable<XAttribute>.Remove() with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void IEnumerableOfXNodeRemove()
{
RunTestCase(new XNodeSequenceRemove { Attribute = new TestCaseAttribute { Name = "IEnumerable<XNode>.Remove()", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void IEnumerableOfXNodeRemoveWithEvents()
{
RunTestCase(new XNodeSequenceRemove { Attribute = new TestCaseAttribute { Name = "IEnumerable<XNode>.Remove() with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void LoadFromReader()
{
RunTestCase(new LoadFromReader { Attribute = new TestCaseAttribute { Name = "Load from Reader" } });
}
[Fact]
[OuterLoop]
public static void LoadFromStreamSanity()
{
RunTestCase(new LoadFromStream { Attribute = new TestCaseAttribute { Name = "Load from Stream - sanity" } });
}
[Fact]
[OuterLoop]
public static void SaveWithWriter()
{
RunTestCase(new SaveWithWriter { Attribute = new TestCaseAttribute { Name = "Save with Writer" } });
}
[Fact]
[OuterLoop]
public static void SimpleConstructors()
{
RunTestCase(new SimpleObjectsCreation { Attribute = new TestCaseAttribute { Name = "Simple constructors" } });
}
[Fact]
[OuterLoop]
public static void XAttributeRemove()
{
RunTestCase(new XAttributeRemove { Attribute = new TestCaseAttribute { Name = "XAttribute.Remove", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void XAttributeRemoveWithEvents()
{
RunTestCase(new XAttributeRemove { Attribute = new TestCaseAttribute { Name = "XAttribute.Remove with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void XContainerAddIntoElement()
{
RunTestCase(new XContainerAddIntoElement { Attribute = new TestCaseAttribute { Name = "XContainer.Add1", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void XContainerAddIntoDocument()
{
RunTestCase(new XContainerAddIntoDocument { Attribute = new TestCaseAttribute { Name = "XContainer.Add2", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void XContainerAddFirstInvalidIntoXDocument()
{
RunTestCase(new AddFirstInvalidIntoXDocument { Attribute = new TestCaseAttribute { Name = "XContainer.AddFirst", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void XContainerAddFirstInvalidIntoXDocumentWithEvents()
{
RunTestCase(new AddFirstInvalidIntoXDocument { Attribute = new TestCaseAttribute { Name = "XContainer.AddFirst with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void AddFirstSingeNodeAddIntoElement()
{
RunTestCase(new AddFirstSingeNodeAddIntoElement { Attribute = new TestCaseAttribute { Name = "XContainer.AddFirstAddFirstSingeNodeAddIntoElement", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void AddFirstSingeNodeAddIntoElementWithEvents()
{
RunTestCase(new AddFirstSingeNodeAddIntoElement { Attribute = new TestCaseAttribute { Name = "XContainer.AddFirstAddFirstSingeNodeAddIntoElement with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void AddFirstAddFirstIntoDocument()
{
RunTestCase(new AddFirstAddFirstIntoDocument { Attribute = new TestCaseAttribute { Name = "XContainer.AddFirstAddFirstAddFirstIntoDocument", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void AddFirstAddFirstIntoDocumentWithEvents()
{
RunTestCase(new AddFirstAddFirstIntoDocument { Attribute = new TestCaseAttribute { Name = "XContainer.AddFirstAddFirstAddFirstIntoDocument with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void XContainerAddIntoElementWithEvents()
{
RunTestCase(new XContainerAddIntoElement { Attribute = new TestCaseAttribute { Name = "XContainer.Add with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void XContainerAddIntoDocumentWithEvents()
{
RunTestCase(new XContainerAddIntoDocument { Attribute = new TestCaseAttribute { Name = "XContainer.Add with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void XContainerFirstNode()
{
RunTestCase(new FirstNode { Attribute = new TestCaseAttribute { Name = "XContainer.FirstNode", Param = true } });
}
[Fact]
[OuterLoop]
public static void XContainerLastNode()
{
RunTestCase(new FirstNode { Attribute = new TestCaseAttribute { Name = "XContainer.LastNode", Param = false } });
}
[Fact]
[OuterLoop]
public static void XContainerNextPreviousNode()
{
RunTestCase(new NextNode { Attribute = new TestCaseAttribute { Name = "XContainer.Next/PreviousNode" } });
}
[Fact]
[OuterLoop]
public static void XContainerRemoveNodesOnXElement()
{
RunTestCase(new XContainerRemoveNodesOnXElement { Attribute = new TestCaseAttribute { Name = "XContainer.RemoveNodes()", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void XContainerRemoveNodesOnXElementWithEvents()
{
RunTestCase(new XContainerRemoveNodesOnXElement { Attribute = new TestCaseAttribute { Name = "XContainer.RemoveNodes() with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void XContainerRemoveNodesOnXDocument()
{
RunTestCase(new XContainerRemoveNodesOnXDocument { Attribute = new TestCaseAttribute { Name = "XContainer.RemoveNodes()", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void XContainerRemoveNodesOnXDocumentWithEvents()
{
RunTestCase(new XContainerRemoveNodesOnXDocument { Attribute = new TestCaseAttribute { Name = "XContainer.RemoveNodes() with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void XContainerReplaceNodesOnDocument()
{
RunTestCase(new XContainerReplaceNodesOnDocument { Attribute = new TestCaseAttribute { Name = "XContainer.ReplaceNodesOnXDocument()", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void XContainerReplaceNodesOnDocumentWithEvents()
{
RunTestCase(new XContainerReplaceNodesOnDocument { Attribute = new TestCaseAttribute { Name = "XContainer.ReplaceNodesOnXDocument() with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void XContainerReplaceNodesOnXElement()
{
RunTestCase(new XContainerReplaceNodesOnXElement { Attribute = new TestCaseAttribute { Name = "XContainer.ReplaceNodesOnXElement()", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void XContainerReplaceNodesOnXElementWithEvents()
{
RunTestCase(new XContainerReplaceNodesOnXElement { Attribute = new TestCaseAttribute { Name = "XContainer.ReplaceNodesOnXElement() with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void XElementRemoveAttributes()
{
RunTestCase(new RemoveAttributes { Attribute = new TestCaseAttribute { Name = "XElement.RemoveAttributes", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void XElementRemoveAttributesWithEvents()
{
RunTestCase(new RemoveAttributes { Attribute = new TestCaseAttribute { Name = "XElement.RemoveAttributes with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void XElementSetAttributeValue()
{
RunTestCase(new XElement_SetAttributeValue { Attribute = new TestCaseAttribute { Name = "XElement.SetAttributeValue()", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void XElementSetAttributeValueWithEvents()
{
RunTestCase(new XElement_SetAttributeValue { Attribute = new TestCaseAttribute { Name = "XElement.SetAttributeValue() with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void XElementSetElementValue()
{
RunTestCase(new XElement_SetElementValue { Attribute = new TestCaseAttribute { Name = "XElement.SetElementValue()", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void XElementSetElementValueWithEvents()
{
RunTestCase(new XElement_SetElementValue { Attribute = new TestCaseAttribute { Name = "XElement.SetElementValue() with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void XNodeAddAfter()
{
RunTestCase(new AddNodeAfter { Attribute = new TestCaseAttribute { Name = "XNode.AddAfter", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void XNodeAddAfterWithEvents()
{
RunTestCase(new AddNodeAfter { Attribute = new TestCaseAttribute { Name = "XNode.AddAfter with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void XNodeAddBefore()
{
RunTestCase(new AddNodeBefore { Attribute = new TestCaseAttribute { Name = "XNode.AddBefore", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void XNodeAddBeforeWithEvents()
{
RunTestCase(new AddNodeBefore { Attribute = new TestCaseAttribute { Name = "XNode.AddBefore with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void XNodeRemoveNodeMisc()
{
RunTestCase(new XNodeRemoveNodeMisc { Attribute = new TestCaseAttribute { Name = "XNode.Remove", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void XNodeRemoveNodeMiscWithEvents()
{
RunTestCase(new XNodeRemoveNodeMisc { Attribute = new TestCaseAttribute { Name = "XNode.Remove with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void XNodeRemoveOnDocument()
{
RunTestCase(new XNodeRemoveOnDocument { Attribute = new TestCaseAttribute { Name = "XNode.Remove", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void XNodeRemoveOnDocumentWithEvents()
{
RunTestCase(new XNodeRemoveOnDocument { Attribute = new TestCaseAttribute { Name = "XNode.Remove with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void XNodeRemoveOnElement()
{
RunTestCase(new XNodeRemoveOnElement { Attribute = new TestCaseAttribute { Name = "XNode.Remove", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void XNodeRemoveOnElementWithEvents()
{
RunTestCase(new XNodeRemoveOnElement { Attribute = new TestCaseAttribute { Name = "XNode.Remove with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void XNodeReplaceOnDocument1()
{
RunTestCase(new XNodeReplaceOnDocument1 { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void XNodeReplaceOnDocument1WithEvents()
{
RunTestCase(new XNodeReplaceOnDocument1 { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void XNodeReplaceOnDocument2()
{
RunTestCase(new XNodeReplaceOnDocument2 { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void XNodeReplaceOnDocument2WithEvents()
{
RunTestCase(new XNodeReplaceOnDocument2 { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void XNodeReplaceOnDocument3()
{
RunTestCase(new XNodeReplaceOnDocument3 { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void XNodeReplaceOnDocument3WithEvents()
{
RunTestCase(new XNodeReplaceOnDocument3 { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith with Events", Params = new object[] { true } } });
}
[Fact]
[OuterLoop]
public static void XNodeReplaceOnElement()
{
RunTestCase(new XNodeReplaceOnElement { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith", Params = new object[] { false } } });
}
[Fact]
[OuterLoop]
public static void XNodeReplaceOnElementWithEvents()
{
RunTestCase(new XNodeReplaceOnElement { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith with Events", Params = new object[] { true } } });
}
private static void RunTestCase(TestItem testCase)
{
var module = new TreeManipulationTests();
module.Init();
module.AddChild(testCase);
module.Execute();
Assert.Equal(0, module.FailCount);
}
}
}
| |
// <copyright file="Path.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System;
using System.Linq;
using System.Security;
using IX.StandardExtensions.Contracts;
using JetBrains.Annotations;
using FS = System.IO;
namespace IX.System.IO;
/// <summary>
/// A class for implementing <see cref="IX.System.IO.IPath" /> with <see cref="FS.Path" />.
/// </summary>
/// <seealso cref="IX.System.IO.IPath" />
/// <seealso cref="FS.Path" />
[PublicAPI]
public class Path : IPath
{
#region Properties and indexers
/// <summary>
/// Gets a platform-specific alternate character used to separate directory levels in a path string that reflects a
/// hierarchical file system organization.
/// </summary>
public char AltDirectorySeparatorChar => FS.Path.AltDirectorySeparatorChar;
/// <summary>
/// Gets a platform-specific character used to separate directory levels in a path string that reflects a hierarchical
/// file system organization.
/// </summary>
public char DirectorySeparatorChar => FS.Path.DirectorySeparatorChar;
/// <summary>
/// Gets a platform-specific separator character used to separate path strings in environment variables.
/// </summary>
public char PathSeparator => FS.Path.PathSeparator;
/// <summary>
/// Gets a platform-specific volume separator character.
/// </summary>
public char VolumeSeparatorChar => FS.Path.VolumeSeparatorChar;
#endregion
#region Methods
#region Interface implementations
/// <summary>
/// Changes the extension of a path string.
/// </summary>
/// <param name="path">
/// The path information to modify. The path cannot contain any of the characters defined in
/// <see cref="GetInvalidPathChars" />.
/// </param>
/// <param name="extension">
/// The new extension (with or without a leading period). Specify <see langword="null" /> (
/// <see langword="Nothing" /> in Visual Basic) to remove an existing extension from path.
/// </param>
/// <returns>The modified path information.</returns>
/// <exception cref="ArgumentException">
/// <paramref name="path" /> contains one or more of the invalid characters
/// defined in <see cref="GetInvalidPathChars" />.
/// </exception>
/// <remarks>
/// <para>
/// On Windows-based desktop platforms, if path is <see langword="null" /> or an empty string (""), the path
/// information is returned unmodified.
/// </para>
/// <para>
/// If extension is <see langword="null" />, the returned string contains the specified path with its extension
/// removed. If path has no extension, and extension is not <see langword="null" />, the returned path string
/// contains extension appended to the end of path.
/// </para>
/// </remarks>
public string ChangeExtension(
string path,
string? extension) =>
FS.Path.ChangeExtension(
path,
extension);
/// <summary>
/// Combines an array of strings into a path.
/// </summary>
/// <param name="paths">An array of parts of the path.</param>
/// <returns>The combined paths.</returns>
/// <exception cref="ArgumentException">
/// One of the strings in the array contains one or more of the invalid characters
/// defined in <see cref="GetInvalidPathChars" />.
/// </exception>
/// <exception cref="ArgumentNullException">One of the strings in the array is <see langword="null" />.</exception>
public string Combine(params string[] paths) => FS.Path.Combine(paths);
/// <summary>
/// Escapes the illegal characters from the given string, by eliminating them out, in order to render a proper file
/// name.
/// </summary>
/// <param name="stringToEscape">The input string, to escape.</param>
/// <returns>The escaped string.</returns>
/// <exception cref="InvalidOperationException">
/// The string to escape is made entirely out of whitespace and illegal
/// characters.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="stringToEscape" /> is <c>null</c> (<c>Nothing</c> in Visual Basic).
/// </exception>
public string EscapeFileName(string stringToEscape)
{
Requires.NotNullOrWhiteSpace(stringToEscape);
var invalidChars = this.GetInvalidFileNameChars();
var newString = new char[stringToEscape.Length];
ReadOnlySpan<char> oldString = stringToEscape.AsSpan();
int oldIndex = 0, newIndex = 0;
while (oldIndex < oldString.Length)
{
var currentChar = oldString[oldIndex];
if (!invalidChars.Contains(currentChar))
{
newString[newIndex] = currentChar;
newIndex++;
}
oldIndex++;
}
string resultingString = new(
newString,
0,
newIndex);
if (string.IsNullOrWhiteSpace(resultingString))
{
throw new InvalidOperationException();
}
return resultingString;
}
/// <summary>
/// Returns the directory information for the specified path string.
/// </summary>
/// <param name="path">The path of a file or directory.</param>
/// <returns>
/// Directory information for path, or <see langword="null" /> if path denotes a root directory or is
/// <see langword="null" />. Returns <see cref="string.Empty" /> if path does not contain directory information.
/// </returns>
/// <exception cref="ArgumentException">
/// The <paramref name="path" /> contains invalid characters, is empty, or contains
/// only white spaces.
/// </exception>
/// <exception cref="FS.PathTooLongException">
/// In the .NET for Windows Store apps or the Portable Class Library, catch the
/// base class exception, <see cref="FS.IOException" />, instead.The path parameter is longer than the system-defined
/// maximum length.
/// </exception>
public string GetDirectoryName(string? path) => FS.Path.GetDirectoryName(path)!;
/// <summary>
/// Returns the extension of the specified path string.
/// </summary>
/// <param name="path">The path string from which to get the extension.</param>
/// <returns>
/// The extension of the specified path (including the period "."), or <see langword="null" />, or
/// <see cref="string.Empty" />. If path is <see langword="null" />, the method returns <see langword="null" />. If
/// path does not have extension information, the method returns <see cref="string.Empty" />.
/// </returns>
public string GetExtension(string path) => FS.Path.GetExtension(path);
/// <summary>
/// Returns the file name and extension of the specified path string.
/// </summary>
/// <param name="path">The path string from which to obtain the file name and extension.</param>
/// <returns>
/// The characters after the last directory character in path. If the last character of path is a directory or
/// volume separator character, this method returns <see cref="string.Empty" />. If path is <see langword="null" />,
/// this method returns <see langword="null" />.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="path" /> contains one or more of the invalid characters defined in
/// <see cref="GetInvalidPathChars" />.
/// </exception>
public string GetFileName(string path) => FS.Path.GetFileName(path);
/// <summary>
/// Returns the file name of the specified path string without the extension.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>
/// The string returned by <see cref="GetFileName(string)" /> , minus the last period (.) and all characters
/// following it.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="path" /> contains one or more of the invalid characters defined in
/// <see cref="GetInvalidPathChars" />.
/// </exception>
public string GetFileNameWithoutExtension(string path) => FS.Path.GetFileNameWithoutExtension(path);
/// <summary>
/// Returns the absolute path for the specified path string.
/// </summary>
/// <param name="path">The file or directory for which to obtain absolute path information.</param>
/// <returns>The fully qualified location of path, such as "C:\MyFile.txt".</returns>
/// <exception cref="ArgumentException">
/// <paramref name="path" /> is a zero-length string, contains only white space, or
/// contains one or more of the invalid characters defined in <see cref="GetInvalidPathChars" />. -or- The system could
/// not retrieve the absolute path.
/// </exception>
/// <exception cref="SecurityException">The caller does not have the required permissions.</exception>
/// <exception cref="ArgumentNullException"><paramref name="path" /> is <see langword="null" />.</exception>
/// <exception cref="NotSupportedException">
/// <paramref name="path" /> contains a colon (":") that is not part of a
/// volume identifier (for example, "c:\").
/// </exception>
/// <exception cref="FS.PathTooLongException">
/// The specified path, file name, or both exceed the system-defined maximum
/// length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be
/// less than 260 characters.
/// </exception>
public string GetFullPath(string path) => FS.Path.GetFullPath(path);
/// <summary>
/// Gets an array containing the characters that are not allowed in file names.
/// </summary>
/// <returns>An array containing the characters that are not allowed in file names.</returns>
public char[] GetInvalidFileNameChars() => FS.Path.GetInvalidFileNameChars();
/// <summary>
/// Gets an array containing the characters that are not allowed in path names.
/// </summary>
/// <returns>An array containing the characters that are not allowed in path names.</returns>
public char[] GetInvalidPathChars() => FS.Path.GetInvalidPathChars();
/// <summary>
/// Gets the root directory information of the specified path.
/// </summary>
/// <param name="path">The path from which to obtain root directory information.</param>
/// <returns>
/// The root directory of path, such as "C:\", or <see langword="null" /> if <paramref name="path" /> is
/// <see langword="null" />, or an empty string if <paramref name="path" /> does not contain root directory
/// information.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="path" /> contains one or more of the invalid characters defined in
/// <see cref="GetInvalidPathChars" />. -or- <see cref="string.Empty" /> was passed to <paramref name="path" />.
/// </exception>
public string? GetPathRoot(string path) => FS.Path.GetPathRoot(path);
/// <summary>
/// Returns a random folder name or file name.
/// </summary>
/// <returns>A random folder name or file name.</returns>
public string GetRandomFileName() => FS.Path.GetRandomFileName();
/// <summary>
/// Creates a uniquely named, zero-byte temporary file on disk and returns the full path of that file.
/// </summary>
/// <returns>The full path of the temporary file.</returns>
/// <exception cref="FS.IOException">
/// An I/O error occurs, such as no unique temporary file name is available. -or- This
/// method was unable to create a temporary file.
/// </exception>
public string GetTempFileName() => FS.Path.GetTempFileName();
/// <summary>
/// Returns the path of the current user's temporary folder.
/// </summary>
/// <returns>The path to the temporary folder, ending with a backslash.</returns>
/// <exception cref="SecurityException">The caller does not have the required permissions.</exception>
public string GetTempPath() => FS.Path.GetTempPath();
/// <summary>
/// Determines whether a path includes a file name extension.
/// </summary>
/// <param name="path">The path to search for an extension.</param>
/// <returns>
/// <see langword="true" /> if the characters that follow the last directory separator (\\ or /) or volume
/// separator (:) in the path include a period (.) followed by one or more characters; otherwise,
/// <see langword="false" />.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="path" /> contains one or more of the invalid characters defined in
/// <see cref="GetInvalidPathChars" />.
/// </exception>
public bool HasExtension(string path) => FS.Path.HasExtension(path);
/// <summary>
/// Gets a value indicating whether the specified path string contains a root.
/// </summary>
/// <param name="path">The path to test.</param>
/// <returns><see langword="true" /> if path contains a root; otherwise, <see langword="false" />.</returns>
/// <exception cref="ArgumentException">
/// <paramref name="path" /> contains one or more of the invalid characters defined in
/// <see cref="GetInvalidPathChars" />.
/// </exception>
public bool IsPathRooted(string path) => FS.Path.IsPathRooted(path);
#endregion
#endregion
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the cloudtrail-2013-11-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using Amazon.CloudTrail.Model;
using Amazon.CloudTrail.Model.Internal.MarshallTransformations;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.CloudTrail
{
/// <summary>
/// Implementation for accessing CloudTrail
///
/// AWS CloudTrail
/// <para>
/// This is the CloudTrail API Reference. It provides descriptions of actions, data types,
/// common parameters, and common errors for CloudTrail.
/// </para>
///
/// <para>
/// CloudTrail is a web service that records AWS API calls for your AWS account and delivers
/// log files to an Amazon S3 bucket. The recorded information includes the identity of
/// the user, the start time of the AWS API call, the source IP address, the request parameters,
/// and the response elements returned by the service.
/// </para>
/// <note> As an alternative to using the API, you can use one of the AWS SDKs, which
/// consist of libraries and sample code for various programming languages and platforms
/// (Java, Ruby, .NET, iOS, Android, etc.). The SDKs provide a convenient way to create
/// programmatic access to AWSCloudTrail. For example, the SDKs take care of cryptographically
/// signing requests, managing errors, and retrying requests automatically. For information
/// about the AWS SDKs, including how to download and install them, see the <a href="http://aws.amazon.com/tools/">Tools
/// for Amazon Web Services page</a>. </note>
/// <para>
/// See the CloudTrail User Guide for information about the data that is included with
/// each AWS API call listed in the log files.
/// </para>
/// </summary>
public partial class AmazonCloudTrailClient : AmazonServiceClient, IAmazonCloudTrail
{
#region Constructors
/// <summary>
/// Constructs AmazonCloudTrailClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonCloudTrailClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonCloudTrailConfig()) { }
/// <summary>
/// Constructs AmazonCloudTrailClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonCloudTrailClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonCloudTrailConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonCloudTrailClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonCloudTrailClient Configuration Object</param>
public AmazonCloudTrailClient(AmazonCloudTrailConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonCloudTrailClient(AWSCredentials credentials)
: this(credentials, new AmazonCloudTrailConfig())
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonCloudTrailClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonCloudTrailConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Credentials and an
/// AmazonCloudTrailClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonCloudTrailClient Configuration Object</param>
public AmazonCloudTrailClient(AWSCredentials credentials, AmazonCloudTrailConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonCloudTrailClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonCloudTrailConfig())
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonCloudTrailClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonCloudTrailConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonCloudTrailClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonCloudTrailClient Configuration Object</param>
public AmazonCloudTrailClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonCloudTrailConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonCloudTrailClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCloudTrailConfig())
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonCloudTrailClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCloudTrailConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonCloudTrailClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonCloudTrailClient Configuration Object</param>
public AmazonCloudTrailClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonCloudTrailConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region CreateTrail
/// <summary>
/// From the command line, use <code>create-subscription</code>.
///
///
/// <para>
/// Creates a trail that specifies the settings for delivery of log data to an Amazon
/// S3 bucket.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateTrail service method.</param>
///
/// <returns>The response from the CreateTrail service method, as returned by CloudTrail.</returns>
/// <exception cref="Amazon.CloudTrail.Model.CloudWatchLogsDeliveryUnavailableException">
/// Cannot set a CloudWatch Logs delivery for this region.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InsufficientS3BucketPolicyException">
/// This exception is thrown when the policy on the S3 bucket is not sufficient.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InsufficientSnsTopicPolicyException">
/// This exception is thrown when the policy on the SNS topic is not sufficient.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidCloudWatchLogsLogGroupArnException">
/// This exception is thrown when the provided CloudWatch log group is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidCloudWatchLogsRoleArnException">
/// This exception is thrown when the provided role is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidS3BucketNameException">
/// This exception is thrown when the provided S3 bucket name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidS3PrefixException">
/// This exception is thrown when the provided S3 prefix is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidSnsTopicNameException">
/// This exception is thrown when the provided SNS topic name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidTrailNameException">
/// This exception is thrown when the provided trail name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.MaximumNumberOfTrailsExceededException">
/// This exception is thrown when the maximum number of trails is reached.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.S3BucketDoesNotExistException">
/// This exception is thrown when the specified S3 bucket does not exist.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.TrailAlreadyExistsException">
/// This exception is thrown when the specified trail already exists.
/// </exception>
public CreateTrailResponse CreateTrail(CreateTrailRequest request)
{
var marshaller = new CreateTrailRequestMarshaller();
var unmarshaller = CreateTrailResponseUnmarshaller.Instance;
return Invoke<CreateTrailRequest,CreateTrailResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateTrail operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateTrail operation on AmazonCloudTrailClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateTrail
/// operation.</returns>
public IAsyncResult BeginCreateTrail(CreateTrailRequest request, AsyncCallback callback, object state)
{
var marshaller = new CreateTrailRequestMarshaller();
var unmarshaller = CreateTrailResponseUnmarshaller.Instance;
return BeginInvoke<CreateTrailRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateTrail operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateTrail.</param>
///
/// <returns>Returns a CreateTrailResult from CloudTrail.</returns>
public CreateTrailResponse EndCreateTrail(IAsyncResult asyncResult)
{
return EndInvoke<CreateTrailResponse>(asyncResult);
}
#endregion
#region DeleteTrail
/// <summary>
/// Deletes a trail.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteTrail service method.</param>
///
/// <returns>The response from the DeleteTrail service method, as returned by CloudTrail.</returns>
/// <exception cref="Amazon.CloudTrail.Model.InvalidTrailNameException">
/// This exception is thrown when the provided trail name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.TrailNotFoundException">
/// This exception is thrown when the trail with the given name is not found.
/// </exception>
public DeleteTrailResponse DeleteTrail(DeleteTrailRequest request)
{
var marshaller = new DeleteTrailRequestMarshaller();
var unmarshaller = DeleteTrailResponseUnmarshaller.Instance;
return Invoke<DeleteTrailRequest,DeleteTrailResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteTrail operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteTrail operation on AmazonCloudTrailClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteTrail
/// operation.</returns>
public IAsyncResult BeginDeleteTrail(DeleteTrailRequest request, AsyncCallback callback, object state)
{
var marshaller = new DeleteTrailRequestMarshaller();
var unmarshaller = DeleteTrailResponseUnmarshaller.Instance;
return BeginInvoke<DeleteTrailRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DeleteTrail operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteTrail.</param>
///
/// <returns>Returns a DeleteTrailResult from CloudTrail.</returns>
public DeleteTrailResponse EndDeleteTrail(IAsyncResult asyncResult)
{
return EndInvoke<DeleteTrailResponse>(asyncResult);
}
#endregion
#region DescribeTrails
/// <summary>
/// Retrieves settings for the trail associated with the current region for your account.
/// </summary>
///
/// <returns>The response from the DescribeTrails service method, as returned by CloudTrail.</returns>
public DescribeTrailsResponse DescribeTrails()
{
return DescribeTrails(new DescribeTrailsRequest());
}
/// <summary>
/// Retrieves settings for the trail associated with the current region for your account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeTrails service method.</param>
///
/// <returns>The response from the DescribeTrails service method, as returned by CloudTrail.</returns>
public DescribeTrailsResponse DescribeTrails(DescribeTrailsRequest request)
{
var marshaller = new DescribeTrailsRequestMarshaller();
var unmarshaller = DescribeTrailsResponseUnmarshaller.Instance;
return Invoke<DescribeTrailsRequest,DescribeTrailsResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeTrails operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeTrails operation on AmazonCloudTrailClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeTrails
/// operation.</returns>
public IAsyncResult BeginDescribeTrails(DescribeTrailsRequest request, AsyncCallback callback, object state)
{
var marshaller = new DescribeTrailsRequestMarshaller();
var unmarshaller = DescribeTrailsResponseUnmarshaller.Instance;
return BeginInvoke<DescribeTrailsRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DescribeTrails operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeTrails.</param>
///
/// <returns>Returns a DescribeTrailsResult from CloudTrail.</returns>
public DescribeTrailsResponse EndDescribeTrails(IAsyncResult asyncResult)
{
return EndInvoke<DescribeTrailsResponse>(asyncResult);
}
#endregion
#region GetTrailStatus
/// <summary>
/// Returns a JSON-formatted list of information about the specified trail. Fields include
/// information on delivery errors, Amazon SNS and Amazon S3 errors, and start and stop
/// logging times for each trail.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetTrailStatus service method.</param>
///
/// <returns>The response from the GetTrailStatus service method, as returned by CloudTrail.</returns>
/// <exception cref="Amazon.CloudTrail.Model.InvalidTrailNameException">
/// This exception is thrown when the provided trail name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.TrailNotFoundException">
/// This exception is thrown when the trail with the given name is not found.
/// </exception>
public GetTrailStatusResponse GetTrailStatus(GetTrailStatusRequest request)
{
var marshaller = new GetTrailStatusRequestMarshaller();
var unmarshaller = GetTrailStatusResponseUnmarshaller.Instance;
return Invoke<GetTrailStatusRequest,GetTrailStatusResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the GetTrailStatus operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetTrailStatus operation on AmazonCloudTrailClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetTrailStatus
/// operation.</returns>
public IAsyncResult BeginGetTrailStatus(GetTrailStatusRequest request, AsyncCallback callback, object state)
{
var marshaller = new GetTrailStatusRequestMarshaller();
var unmarshaller = GetTrailStatusResponseUnmarshaller.Instance;
return BeginInvoke<GetTrailStatusRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetTrailStatus operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetTrailStatus.</param>
///
/// <returns>Returns a GetTrailStatusResult from CloudTrail.</returns>
public GetTrailStatusResponse EndGetTrailStatus(IAsyncResult asyncResult)
{
return EndInvoke<GetTrailStatusResponse>(asyncResult);
}
#endregion
#region LookupEvents
/// <summary>
/// Looks up API activity events captured by CloudTrail that create, update, or delete
/// resources in your account. Events for a region can be looked up for the times in which
/// you had CloudTrail turned on in that region during the last seven days. Lookup supports
/// five different attributes: time range (defined by a start time and end time), user
/// name, event name, resource type, and resource name. All attributes are optional. The
/// maximum number of attributes that can be specified in any one lookup request are time
/// range and one other attribute. The default number of results returned is 10, with
/// a maximum of 50 possible. The response includes a token that you can use to get the
/// next page of results. The rate of lookup requests is limited to one per second per
/// account.
///
/// <important>Events that occurred during the selected time range will not be available
/// for lookup if CloudTrail logging was not enabled when the events occurred.</important>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the LookupEvents service method.</param>
///
/// <returns>The response from the LookupEvents service method, as returned by CloudTrail.</returns>
/// <exception cref="Amazon.CloudTrail.Model.InvalidLookupAttributesException">
/// Occurs when an invalid lookup attribute is specified.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidMaxResultsException">
/// This exception is thrown if the limit specified is invalid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidNextTokenException">
/// Invalid token or token that was previously used in a request with different parameters.
/// This exception is thrown if the token is invalid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidTimeRangeException">
/// Occurs if the timestamp values are invalid. Either the start time occurs after the
/// end time or the time range is outside the range of possible values.
/// </exception>
public LookupEventsResponse LookupEvents(LookupEventsRequest request)
{
var marshaller = new LookupEventsRequestMarshaller();
var unmarshaller = LookupEventsResponseUnmarshaller.Instance;
return Invoke<LookupEventsRequest,LookupEventsResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the LookupEvents operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the LookupEvents operation on AmazonCloudTrailClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndLookupEvents
/// operation.</returns>
public IAsyncResult BeginLookupEvents(LookupEventsRequest request, AsyncCallback callback, object state)
{
var marshaller = new LookupEventsRequestMarshaller();
var unmarshaller = LookupEventsResponseUnmarshaller.Instance;
return BeginInvoke<LookupEventsRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the LookupEvents operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginLookupEvents.</param>
///
/// <returns>Returns a LookupEventsResult from CloudTrail.</returns>
public LookupEventsResponse EndLookupEvents(IAsyncResult asyncResult)
{
return EndInvoke<LookupEventsResponse>(asyncResult);
}
#endregion
#region StartLogging
/// <summary>
/// Starts the recording of AWS API calls and log file delivery for a trail.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StartLogging service method.</param>
///
/// <returns>The response from the StartLogging service method, as returned by CloudTrail.</returns>
/// <exception cref="Amazon.CloudTrail.Model.InvalidTrailNameException">
/// This exception is thrown when the provided trail name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.TrailNotFoundException">
/// This exception is thrown when the trail with the given name is not found.
/// </exception>
public StartLoggingResponse StartLogging(StartLoggingRequest request)
{
var marshaller = new StartLoggingRequestMarshaller();
var unmarshaller = StartLoggingResponseUnmarshaller.Instance;
return Invoke<StartLoggingRequest,StartLoggingResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the StartLogging operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the StartLogging operation on AmazonCloudTrailClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStartLogging
/// operation.</returns>
public IAsyncResult BeginStartLogging(StartLoggingRequest request, AsyncCallback callback, object state)
{
var marshaller = new StartLoggingRequestMarshaller();
var unmarshaller = StartLoggingResponseUnmarshaller.Instance;
return BeginInvoke<StartLoggingRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the StartLogging operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginStartLogging.</param>
///
/// <returns>Returns a StartLoggingResult from CloudTrail.</returns>
public StartLoggingResponse EndStartLogging(IAsyncResult asyncResult)
{
return EndInvoke<StartLoggingResponse>(asyncResult);
}
#endregion
#region StopLogging
/// <summary>
/// Suspends the recording of AWS API calls and log file delivery for the specified trail.
/// Under most circumstances, there is no need to use this action. You can update a trail
/// without stopping it first. This action is the only way to stop recording.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StopLogging service method.</param>
///
/// <returns>The response from the StopLogging service method, as returned by CloudTrail.</returns>
/// <exception cref="Amazon.CloudTrail.Model.InvalidTrailNameException">
/// This exception is thrown when the provided trail name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.TrailNotFoundException">
/// This exception is thrown when the trail with the given name is not found.
/// </exception>
public StopLoggingResponse StopLogging(StopLoggingRequest request)
{
var marshaller = new StopLoggingRequestMarshaller();
var unmarshaller = StopLoggingResponseUnmarshaller.Instance;
return Invoke<StopLoggingRequest,StopLoggingResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the StopLogging operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the StopLogging operation on AmazonCloudTrailClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStopLogging
/// operation.</returns>
public IAsyncResult BeginStopLogging(StopLoggingRequest request, AsyncCallback callback, object state)
{
var marshaller = new StopLoggingRequestMarshaller();
var unmarshaller = StopLoggingResponseUnmarshaller.Instance;
return BeginInvoke<StopLoggingRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the StopLogging operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginStopLogging.</param>
///
/// <returns>Returns a StopLoggingResult from CloudTrail.</returns>
public StopLoggingResponse EndStopLogging(IAsyncResult asyncResult)
{
return EndInvoke<StopLoggingResponse>(asyncResult);
}
#endregion
#region UpdateTrail
/// <summary>
/// From the command line, use <code>update-subscription</code>.
///
///
/// <para>
/// Updates the settings that specify delivery of log files. Changes to a trail do not
/// require stopping the CloudTrail service. Use this action to designate an existing
/// bucket for log delivery. If the existing bucket has previously been a target for CloudTrail
/// log files, an IAM policy exists for the bucket.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateTrail service method.</param>
///
/// <returns>The response from the UpdateTrail service method, as returned by CloudTrail.</returns>
/// <exception cref="Amazon.CloudTrail.Model.CloudWatchLogsDeliveryUnavailableException">
/// Cannot set a CloudWatch Logs delivery for this region.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InsufficientS3BucketPolicyException">
/// This exception is thrown when the policy on the S3 bucket is not sufficient.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InsufficientSnsTopicPolicyException">
/// This exception is thrown when the policy on the SNS topic is not sufficient.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidCloudWatchLogsLogGroupArnException">
/// This exception is thrown when the provided CloudWatch log group is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidCloudWatchLogsRoleArnException">
/// This exception is thrown when the provided role is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidS3BucketNameException">
/// This exception is thrown when the provided S3 bucket name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidS3PrefixException">
/// This exception is thrown when the provided S3 prefix is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidSnsTopicNameException">
/// This exception is thrown when the provided SNS topic name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidTrailNameException">
/// This exception is thrown when the provided trail name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.S3BucketDoesNotExistException">
/// This exception is thrown when the specified S3 bucket does not exist.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.TrailNotFoundException">
/// This exception is thrown when the trail with the given name is not found.
/// </exception>
public UpdateTrailResponse UpdateTrail(UpdateTrailRequest request)
{
var marshaller = new UpdateTrailRequestMarshaller();
var unmarshaller = UpdateTrailResponseUnmarshaller.Instance;
return Invoke<UpdateTrailRequest,UpdateTrailResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the UpdateTrail operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateTrail operation on AmazonCloudTrailClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateTrail
/// operation.</returns>
public IAsyncResult BeginUpdateTrail(UpdateTrailRequest request, AsyncCallback callback, object state)
{
var marshaller = new UpdateTrailRequestMarshaller();
var unmarshaller = UpdateTrailResponseUnmarshaller.Instance;
return BeginInvoke<UpdateTrailRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the UpdateTrail operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateTrail.</param>
///
/// <returns>Returns a UpdateTrailResult from CloudTrail.</returns>
public UpdateTrailResponse EndUpdateTrail(IAsyncResult asyncResult)
{
return EndInvoke<UpdateTrailResponse>(asyncResult);
}
#endregion
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;
public class AvatarController : MonoBehaviour
{
// Bool that determines whether the avatar is active.
//public bool Active = true;
// Bool that has the characters (facing the player) actions become mirrored. Default false.
public bool MirroredMovement = false;
// Bool that determines whether the avatar will move or not in space.
//public bool MovesInSpace = true;
// Bool that determines whether the avatar is allowed to jump -- vertical movement
// can cause some models to behave strangely, so use at your own discretion.
public bool VerticalMovement = false;
// Rate at which avatar will move through the scene. The rate multiplies the movement speed (.001f, i.e dividing by 1000, unity's framerate).
public int MoveRate = 1;
// Slerp smooth factor
public float SmoothFactor = 10.0f;
// Public variables that will get matched to bones. If empty, the kinect will simply not track it.
// These bones can be set within the Unity interface.
public Transform Hips;
public Transform Spine;
public Transform Neck;
public Transform Head;
public Transform LeftShoulder;
public Transform LeftUpperArm;
public Transform LeftElbow;
//public Transform LeftWrist;
public Transform LeftHand;
//public Transform LeftFingers;
public Transform RightShoulder;
public Transform RightUpperArm;
public Transform RightElbow;
//public Transform RightWrist;
public Transform RightHand;
//public Transform RightFingers;
public Transform LeftThigh;
public Transform LeftKnee;
public Transform LeftFoot;
public Transform LeftToes;
public Transform RightThigh;
public Transform RightKnee;
public Transform RightFoot;
public Transform RightToes;
public Transform Root;
// A required variable if you want to rotate the model in space.
public GameObject offsetNode;
// Variable to hold all them bones. It will initialize the same size as initialRotations.
private Transform[] bones;
// Rotations of the bones when the Kinect tracking starts.
private Quaternion[] initialRotations;
private Quaternion[] initialLocalRotations;
// Rotations of the bones when the Kinect tracking starts.
private Vector3[] initialDirections;
// Calibration Offset Variables for Character Position.
private bool OffsetCalibrated = false;
private float XOffset, YOffset, ZOffset;
private Quaternion originalRotation;
// Lastly used Kinect UserID
//private uint LastUserID;
// private instance of the KinectManager
private KinectManager kinectManager;
private Vector3 hipsUp; // up vector of the hips
private Vector3 hipsRight; // right vector of the hips
private Vector3 chestRight; // right vectory of the chest
public void Start()
{
//GestureInfo = GameObject.Find("GestureInfo");
//HandCursor = GameObject.Find("HandCursor");
// Holds our bones for later.
bones = new Transform[25];
// Initial rotations and directions of the bones.
initialRotations = new Quaternion[bones.Length];
initialLocalRotations = new Quaternion[bones.Length];
initialDirections = new Vector3[bones.Length];
// Map bones to the points the Kinect tracks
MapBones();
// Get initial bone directions
GetInitialDirections();
// Get initial bone rotations
GetInitialRotations();
// Set the model to the calibration pose
RotateToCalibrationPose(0, KinectManager.IsCalibrationNeeded());
}
// Update the avatar each frame.
public void UpdateAvatar(uint UserID)
{
//LastUserID = UserID;
bool flipJoint = !MirroredMovement;
// Get the KinectManager instance
if(kinectManager == null)
{
kinectManager = KinectManager.Instance;
}
// Update Head, Neck, Spine, and Hips normally.
TransformBone(UserID, KinectWrapper.SkeletonJoint.HIPS, 1, flipJoint);
TransformBone(UserID, KinectWrapper.SkeletonJoint.SPINE, 2, flipJoint);
TransformBone(UserID, KinectWrapper.SkeletonJoint.NECK, 3, flipJoint);
TransformBone(UserID, KinectWrapper.SkeletonJoint.HEAD, 4, flipJoint);
// Beyond this, switch the arms and legs.
// Left Arm --> Right Arm
TransformSpecialBone(UserID, KinectWrapper.SkeletonJoint.LEFT_COLLAR, !MirroredMovement ? 5 : 11, flipJoint);
TransformBone(UserID, KinectWrapper.SkeletonJoint.LEFT_SHOULDER, !MirroredMovement ? 6 : 12, flipJoint);
TransformBone(UserID, KinectWrapper.SkeletonJoint.LEFT_ELBOW, !MirroredMovement ? 7 : 13, flipJoint);
//TransformBone(UserID, KinectWrapper.SkeletonJoint.LEFT_WRIST, !MirroredMovement ? 8 : 14, flipJoint);
TransformBone(UserID, KinectWrapper.SkeletonJoint.LEFT_HAND, !MirroredMovement ? 8 : 14, flipJoint);
//TransformBone(UserID, KinectWrapper.SkeletonJoint.LEFT_FINGERTIP, !MirroredMovement ? 10 : 16, flipJoint);
// Right Arm --> Left Arm
TransformSpecialBone(UserID, KinectWrapper.SkeletonJoint.RIGHT_COLLAR, !MirroredMovement ? 11 : 5, flipJoint);
TransformBone(UserID, KinectWrapper.SkeletonJoint.RIGHT_SHOULDER, !MirroredMovement ? 12 : 6, flipJoint);
TransformBone(UserID, KinectWrapper.SkeletonJoint.RIGHT_ELBOW, !MirroredMovement ? 13 : 7, flipJoint);
//TransformBone(UserID, KinectWrapper.SkeletonJoint.RIGHT_WRIST, !MirroredMovement ? 14 : 8, flipJoint);
TransformBone(UserID, KinectWrapper.SkeletonJoint.RIGHT_HAND, !MirroredMovement ? 14 : 8, flipJoint);
TransformBone(UserID, KinectWrapper.SkeletonJoint.RIGHT_FINGERTIP, !MirroredMovement ? 16 : 10, flipJoint);
// Hips 2
TransformSpecialBone(UserID, KinectWrapper.SkeletonJoint.HIPS, 16, flipJoint);
//if(!IsNearMode)
{
// Left Leg --> Right Leg
TransformBone(UserID, KinectWrapper.SkeletonJoint.LEFT_HIP, !MirroredMovement ? 17 : 21, flipJoint);
TransformBone(UserID, KinectWrapper.SkeletonJoint.LEFT_KNEE, !MirroredMovement ? 18 : 22, flipJoint);
TransformBone(UserID, KinectWrapper.SkeletonJoint.LEFT_ANKLE, !MirroredMovement ? 19 : 23, flipJoint);
TransformBone(UserID, KinectWrapper.SkeletonJoint.LEFT_FOOT, !MirroredMovement ? 20 : 24, flipJoint);
// Right Leg --> Left Leg
TransformBone(UserID, KinectWrapper.SkeletonJoint.RIGHT_HIP, !MirroredMovement ? 21 : 17, flipJoint);
TransformBone(UserID, KinectWrapper.SkeletonJoint.RIGHT_KNEE, !MirroredMovement ? 22 : 18, flipJoint);
TransformBone(UserID, KinectWrapper.SkeletonJoint.RIGHT_ANKLE, !MirroredMovement ? 23 : 19, flipJoint);
TransformBone(UserID, KinectWrapper.SkeletonJoint.RIGHT_FOOT, !MirroredMovement ? 24 : 20, flipJoint);
}
// If the avatar is supposed to move in the space, move it.
//if (MovesInSpace)
{
MoveAvatar(UserID);
}
}
// Calibration pose is simply initial position with hands raised up. Rotation must be 0,0,0 to calibrate.
public void RotateToCalibrationPose(uint userId, bool needCalibration)
{
// Reset the rest of the model to the original position.
RotateToInitialPosition();
if(needCalibration)
{
if(offsetNode != null)
{
// Set the offset's rotation to 0.
offsetNode.transform.rotation = Quaternion.Euler(Vector3.zero);
}
// // Right Elbow
// if(RightElbow != null)
// RightElbow.rotation = Quaternion.Euler(0, -90, 90) *
// initialRotations[(int)KinectWrapper.SkeletonJoint.RIGHT_ELBOW];
//
// // Left Elbow
// if(LeftElbow != null)
// LeftElbow.rotation = Quaternion.Euler(0, 90, -90) *
// initialRotations[(int)KinectWrapper.SkeletonJoint.LEFT_ELBOW];
if(offsetNode != null)
{
// Restore the offset's rotation
offsetNode.transform.rotation = originalRotation;
}
}
}
// Invoked on the successful calibration of a player.
public void SuccessfulCalibration(uint userId)
{
// reset the models position
if(offsetNode != null)
{
offsetNode.transform.rotation = originalRotation;
}
// re-calibrate the position offset
OffsetCalibrated = false;
}
// Apply the rotations tracked by kinect to the joints.
void TransformBone(uint userId, KinectWrapper.SkeletonJoint joint, int boneIndex, bool flip)
{
Transform boneTransform = bones[boneIndex];
if(boneTransform == null || kinectManager == null)
return;
int iJoint = (int)joint;
if(iJoint < 0)
return;
// Get Kinect joint orientation
Quaternion jointRotation = kinectManager.GetJointOrientation(userId, iJoint, flip);
if(jointRotation == Quaternion.identity)
return;
// Smoothly transition to the new rotation
Quaternion newRotation = Kinect2AvatarRot(jointRotation, boneIndex);
if(SmoothFactor != 0f)
boneTransform.rotation = Quaternion.Slerp(boneTransform.rotation, newRotation, SmoothFactor * Time.deltaTime);
else
boneTransform.rotation = newRotation;
}
// Apply the rotations tracked by kinect to a special joint
void TransformSpecialBone(uint userId, KinectWrapper.SkeletonJoint joint, int boneIndex, bool flip)
{
Transform boneTransform = bones[boneIndex];
if(boneTransform == null || kinectManager == null)
return;
// Get initial bone direction
Vector3 initialDir = initialDirections[boneIndex];
if(initialDir == Vector3.zero)
return;
int iJoint = (int)joint;
// if(iJoint < 0)
// return;
// Get Kinect joint orientation
Vector3 jointDir = Vector3.zero;
if(boneIndex == 16) // Hip_center
{
initialDir = hipsUp;
// target is a vector from hip_center to average of hips left and right
jointDir = ((kinectManager.GetJointPosition(userId, (int)KinectWrapper.NuiSkeletonPositionIndex.HipLeft) +
kinectManager.GetJointPosition(userId, (int)KinectWrapper.NuiSkeletonPositionIndex.HipRight)) / 2.0f) -
kinectManager.GetJointPosition(userId, (int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter);
jointDir.z = -jointDir.z;
if(!flip)
jointDir.x = -jointDir.x;
}
else if(boneIndex == 5 || boneIndex == 11) // Clavicle_left or Clavicle_right
{
// target is a vector from shoulder_center to bone
jointDir = kinectManager.GetDirectionBetweenJoints(userId, (int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderCenter, iJoint, !flip, true);
}
else
{
jointDir = kinectManager.GetDirectionBetweenJoints(userId, iJoint - 1, iJoint, !flip, true);
}
if(jointDir == Vector3.zero)
return;
// Vector3 upDir = Vector3.zero;
// Vector3 rightDir = Vector3.zero;
//
// if(joint == KinectWrapper.SkeletonJoint.SPINE)
// {
//// // the spine in the Kinect data is ~40 degrees back from the hip
//// jointDir = Quaternion.Euler(40, 0, 0) * jointDir;
//
// if(Hips && LeftThigh && RightThigh)
// {
// upDir = ((LeftThigh.position + RightThigh.position) / 2.0f) - Hips.transform.position;
// rightDir = RightThigh.transform.position - LeftThigh.transform.position;
// }
// }
boneTransform.localRotation = initialLocalRotations[boneIndex];
// transform it into bone-local space
jointDir = transform.TransformDirection(jointDir);
jointDir = boneTransform.InverseTransformDirection(jointDir);
//create a rotation that rotates dir into target
Quaternion quat = Quaternion.FromToRotation(initialDir, jointDir);
//if bone is the hip override, add in the rotation along the hips
if(boneIndex == 16)
{
//rotate the hips so they face forward (determined by the hips)
initialDir = hipsRight;
jointDir = kinectManager.GetDirectionBetweenJoints(userId, (int)KinectWrapper.NuiSkeletonPositionIndex.HipLeft, (int)KinectWrapper.NuiSkeletonPositionIndex.HipRight, false, flip);
if(jointDir != Vector3.zero)
{
jointDir = transform.TransformDirection(jointDir);
jointDir = boneTransform.InverseTransformDirection(jointDir);
jointDir -= Vector3.Project(jointDir, initialDirections[boneIndex]);
quat *= Quaternion.FromToRotation(initialDir, jointDir);
}
}
// //if bone is the spine, add in the rotation along the spine
// else if(joint == KinectWrapper.SkeletonJoint.SPINE)
// {
// //rotate the chest so that it faces forward (determined by the shoulders)
// initialDir = chestRight;
// jointDir = kinectManager.GetDirectionBetweenJoints(userId, (int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderLeft, (int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderRight, false, flip);
//
// if(jointDir != Vector3.zero)
// {
// jointDir = transform.TransformDirection(jointDir);
// jointDir = boneTransform.InverseTransformDirection(jointDir);
// jointDir -= Vector3.Project(jointDir, initialDirections[boneIndex]);
//
// quat *= Quaternion.FromToRotation(initialDir, jointDir);
// }
// }
boneTransform.localRotation *= quat;
// if(joint == KinectWrapper.SkeletonJoint.SPINE && upDir != Vector3.zero && rightDir != Vector3.zero)
// {
// RestoreBone(bones[1], hipsUp, upDir);
// RestoreBone(bones[1], hipsRight, rightDir);
// }
}
// Transform targetDir into bone-local space (independant of the transform of the controller)
void RestoreBone(Transform boneTransform, Vector3 initialDir, Vector3 targetDir)
{
//targetDir = transform.TransformDirection(targetDir);
targetDir = boneTransform.InverseTransformDirection(targetDir);
//create a rotation that rotates dir into target
Quaternion quat = Quaternion.FromToRotation(initialDir, targetDir);
boneTransform.localRotation *= quat;
}
// Moves the avatar in 3D space - pulls the tracked position of the spine and applies it to root.
// Only pulls positional, not rotational.
void MoveAvatar(uint UserID)
{
if(Root == null || kinectManager == null)
return;
if(!kinectManager.IsJointTracked(UserID, (int)KinectWrapper.SkeletonJoint.HIPS))
return;
// Get the position of the body and store it.
Vector3 trans = kinectManager.GetUserPosition(UserID);
// If this is the first time we're moving the avatar, set the offset. Otherwise ignore it.
if (!OffsetCalibrated)
{
OffsetCalibrated = true;
XOffset = !MirroredMovement ? trans.x * MoveRate : -trans.x * MoveRate;
YOffset = trans.y * MoveRate;
ZOffset = -trans.z * MoveRate;
}
// Smoothly transition to the new position
Vector3 targetPos = Kinect2AvatarPos(trans, VerticalMovement);
Root.localPosition = Vector3.Lerp(Root.localPosition, targetPos, SmoothFactor * Time.deltaTime);
}
// If the bones to be mapped have been declared, map that bone to the model.
void MapBones()
{
// If they're not empty, pull in the values from Unity and assign them to the array.
if(Hips != null)
bones[1] = Hips;
if(Spine != null)
bones[2] = Spine;
if(Neck != null)
bones[3] = Neck;
if(Head != null)
bones[4] = Head;
if(LeftShoulder != null)
bones[5] = LeftShoulder;
if(LeftUpperArm != null)
bones[6] = LeftUpperArm;
if(LeftElbow != null)
bones[7] = LeftElbow;
// if(LeftWrist != null)
// bones[8] = LeftWrist;
if(LeftHand != null)
bones[8] = LeftHand;
// if(LeftFingers != null)
// bones[10] = LeftFingers;
if(RightShoulder != null)
bones[11] = RightShoulder;
if(RightUpperArm != null)
bones[12] = RightUpperArm;
if(RightElbow != null)
bones[13] = RightElbow;
// if(RightWrist != null)
// bones[14] = RightWrist;
if(RightHand != null)
bones[14] = RightHand;
// if(RightFingers != null)
// bones[16] = RightFingers;
// Hips 2
if(Hips != null)
bones[16] = Hips;
if(LeftThigh != null)
bones[17] = LeftThigh;
if(LeftKnee != null)
bones[18] = LeftKnee;
if(LeftFoot != null)
bones[19] = LeftFoot;
if(LeftToes != null)
bones[20] = LeftToes;
if(RightThigh != null)
bones[21] = RightThigh;
if(RightKnee != null)
bones[22] = RightKnee;
if(RightFoot != null)
bones[23] = RightFoot;
if(RightToes!= null)
bones[24] = RightToes;
}
// Capture the initial directions of the bones
void GetInitialDirections()
{
int[] intermediateBone = { 1, 2, 3, 5, 6, 7, 11, 12, 13, 17, 18, 19, 21, 22, 23};
for (int i = 0; i < bones.Length; i++)
{
if(Array.IndexOf(intermediateBone, i) >= 0)
{
// intermediary joint
if(bones[i] && bones[i + 1])
{
initialDirections[i] = bones[i + 1].position - bones[i].position;
initialDirections[i] = bones[i].InverseTransformDirection(initialDirections[i]);
}
else
{
initialDirections[i] = Vector3.zero;
}
}
// else if(i == 16)
// {
// // Hips 2
// initialDirections[i] = Vector3.zero;
// }
else
{
// end joint
initialDirections[i] = Vector3.zero;
}
}
// special directions
if(Hips && LeftThigh && RightThigh)
{
hipsUp = ((RightThigh.position + LeftThigh.position) / 2.0f) - Hips.position;
hipsUp = Hips.InverseTransformDirection(hipsUp);
hipsRight = RightThigh.position - LeftThigh.position;
hipsRight = Hips.InverseTransformDirection(hipsRight);
// make hipRight orthogonal to the direction of the hips
Vector3.OrthoNormalize(ref hipsUp, ref hipsRight);
initialDirections[16] = hipsUp;
}
if(Spine && LeftUpperArm && RightUpperArm)
{
chestRight = RightUpperArm.position - LeftUpperArm.position;
chestRight = Spine.InverseTransformDirection(chestRight);
// make chestRight orthogonal to the direction of the spine
chestRight -= Vector3.Project(chestRight, initialDirections[2]);
}
}
// Capture the initial rotations of the bones
void GetInitialRotations()
{
if(offsetNode != null)
{
// Store the original offset's rotation.
originalRotation = offsetNode.transform.rotation;
// Set the offset's rotation to 0.
offsetNode.transform.rotation = Quaternion.Euler(Vector3.zero);
}
for (int i = 0; i < bones.Length; i++)
{
if (bones[i] != null)
{
initialRotations[i] = bones[i].rotation;
initialLocalRotations[i] = bones[i].localRotation;
}
}
if(offsetNode != null)
{
// Restore the offset's rotation
offsetNode.transform.rotation = originalRotation;
}
}
// Set bones to initial position.
public void RotateToInitialPosition()
{
if(bones == null)
return;
if(offsetNode != null)
{
// Set the offset's rotation to 0.
offsetNode.transform.rotation = Quaternion.Euler(Vector3.zero);
}
// For each bone that was defined, reset to initial position.
for (int i = 0; i < bones.Length; i++)
{
if (bones[i] != null)
{
bones[i].rotation = initialRotations[i];
}
}
if(Root != null)
{
Root.localPosition = Vector3.zero;
}
if(offsetNode != null)
{
// Restore the offset's rotation
offsetNode.transform.rotation = originalRotation;
}
}
// Converts kinect joint rotation to avatar joint rotation, depending on joint initial rotation and offset rotation
Quaternion Kinect2AvatarRot(Quaternion jointRotation, int boneIndex)
{
// Apply the new rotation.
Quaternion newRotation = jointRotation * initialRotations[boneIndex];
//If an offset node is specified, combine the transform with its
//orientation to essentially make the skeleton relative to the node
if (offsetNode != null)
{
// Grab the total rotation by adding the Euler and offset's Euler.
Vector3 totalRotation = newRotation.eulerAngles + offsetNode.transform.rotation.eulerAngles;
// Grab our new rotation.
newRotation = Quaternion.Euler(totalRotation);
}
return newRotation;
}
// Converts Kinect position to avatar skeleton position, depending on initial position, mirroring and move rate
Vector3 Kinect2AvatarPos(Vector3 jointPosition, bool bMoveVertically)
{
float xPos;
float yPos;
float zPos;
// If movement is mirrored, reverse it.
if(!MirroredMovement)
xPos = jointPosition.x * MoveRate - XOffset;
else
xPos = -jointPosition.x * MoveRate - XOffset;
yPos = jointPosition.y * MoveRate - YOffset;
zPos = -jointPosition.z * MoveRate - ZOffset;
// If we are tracking vertical movement, update the y. Otherwise leave it alone.
Vector3 avatarJointPos = new Vector3(xPos, bMoveVertically ? yPos : 0f, zPos);
return avatarJointPos;
}
// converts Kinect joint position to position relative to the user position (Hips)
Vector3 Kinect2AvatarRelPos(Vector3 jointPosition, Vector3 userPosition)
{
jointPosition.z = !MirroredMovement ? -jointPosition.z : jointPosition.z;
jointPosition -= userPosition;
jointPosition.z = -jointPosition.z;
// if(MirroredMovement)
// {
// jointPosition.x = -jointPosition.x;
// }
return jointPosition;
}
}
| |
using GuiLabs.Editor.Blocks;
using GuiLabs.Canvas.Controls;
using System.Collections.Generic;
using GuiLabs.Utils;
using GuiLabs.Editor.UI;
using GuiLabs.Canvas.DrawStyle;
namespace GuiLabs.Editor.CSharp
{
[BlockSerialization("foreach")]
public class ForeachBlock : ControlStructureBlock
{
#region ctor
public ForeachBlock()
: base("foreach")
{
IteratorType = new ExpressionBlock();
IteratorType.MyControl.Style = StyleFactory.Instance.GetStyle(StyleNames.TypeName);
IteratorType.MyControl.SelectedStyle = StyleFactory.Instance.GetStyle(StyleNames.TypeNameSel);
IteratorName = new ExpressionBlock();
EnumeratedExpression = new ExpressionBlock();
this.HMembers.Add(IteratorType);
this.HMembers.Add(IteratorName);
this.HMembers.Add(new KeywordLabel("in"));
this.HMembers.Add(EnumeratedExpression);
const int x = ShapeStyle.DefaultFontSize;
const int x2 = ShapeStyle.DefaultFontSize / 2;
InitExpr(IteratorType);
IteratorType.MyControl.Box.Margins.SetLeftAndRight(x, x2);
InitExpr(IteratorName);
IteratorName.MyControl.Box.Margins.SetLeftAndRight(x2, x);
InitExpr(EnumeratedExpression);
EnumeratedExpression.MyControl.Box.Margins.SetLeftAndRight(x, x);
IteratorType.ProvideHelpStrings += new StringsProvider(IteratorType_ProvideHelpStrings);
IteratorName.ProvideHelpStrings += new StringsProvider(IteratorName_ProvideHelpStrings);
EnumeratedExpression.ProvideHelpStrings += ProvideHelpStringsForTab;
}
private void InitExpr(ExpressionBlock e)
{
e.MyControl.Box.MouseSensitivityArea = IteratorType.MyControl.Box.Margins;
e.MyTextBox.MinWidth = ShapeStyle.DefaultFontSize;
}
#endregion
#region IteratorType
private ExpressionBlock mIteratorType;
public ExpressionBlock IteratorType
{
get { return mIteratorType; }
private set
{
if (mIteratorType != null)
{
mIteratorType.MyTextBox.PreviewKeyPress -= IteratorType_KeyPress;
mIteratorType.KeyDown -= IteratorType_KeyDown;
mIteratorType.CustomItemsRequested -= FillTypes;
}
mIteratorType = value;
if (mIteratorType != null)
{
mIteratorType.MyTextBox.PreviewKeyPress += IteratorType_KeyPress;
mIteratorType.KeyDown += IteratorType_KeyDown;
mIteratorType.CustomItemsRequested += FillTypes;
mIteratorType.Context = CompletionContext.ForeachType;
}
}
}
public void FillTypes(CustomItemsRequestEventArgs e)
{
LanguageService ls = LanguageService.Get(this);
ClassOrStructBlock parentClass = ClassNavigator.FindContainingClassOrStruct(this);
if (ls != null)
{
ls.FillTypeItems(parentClass, e.Items);
}
e.ShouldCallFillItems = false;
e.ShowOnlyCustomItems = true;
}
#endregion
#region IteratorName
private ExpressionBlock mIteratorName = new ExpressionBlock();
public ExpressionBlock IteratorName
{
get { return mIteratorName; }
set
{
if (mIteratorName != null)
{
mIteratorName.MyTextBox.PreviewKeyPress -= IteratorName_KeyPress;
mIteratorName.KeyDown -= IteratorName_KeyDown;
}
mIteratorName = value;
if (mIteratorName != null)
{
mIteratorName.MyTextBox.PreviewKeyPress += IteratorName_KeyPress;
mIteratorName.KeyDown += IteratorName_KeyDown;
mIteratorName.Context = null;
}
}
}
#endregion
#region EnumeratedExpression
private ExpressionBlock mCollectionName = new ExpressionBlock();
public ExpressionBlock EnumeratedExpression
{
get { return mCollectionName; }
set
{
if (mCollectionName != null)
{
mCollectionName.MyControl.KeyPress -= EnumeratedExpression_KeyPress;
mCollectionName.KeyDown -= CollectionName_KeyDown;
}
mCollectionName = value;
if (mCollectionName != null)
{
mCollectionName.MyControl.KeyPress += EnumeratedExpression_KeyPress;
mCollectionName.KeyDown += CollectionName_KeyDown;
mCollectionName.Context = CompletionContext.ForeachCollection;
}
}
}
#endregion
#region Variable
private Variable mVariable = new Variable();
public Variable IterationVariable
{
get
{
mVariable.Name = this.IteratorName.Text;
mVariable.Type = this.IteratorType.Text;
return mVariable;
}
}
#endregion
#region Keyboard
void IteratorType_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == System.Windows.Forms.Keys.Tab)
{
IteratorName.SetFocus();
e.Handled = true;
}
if (e.KeyCode == System.Windows.Forms.Keys.Back)
{
this.SetFocus();
e.Handled = true;
}
}
void IteratorName_KeyDown(Block block, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == System.Windows.Forms.Keys.Tab)
{
EnumeratedExpression.SetFocus();
e.Handled = true;
}
if (e.KeyCode == System.Windows.Forms.Keys.Back)
{
IteratorType.SetCursorToTheEnd();
e.Handled = true;
}
}
void CollectionName_KeyDown(Block block, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == System.Windows.Forms.Keys.Tab)
{
IteratorType.SetFocus();
e.Handled = true;
}
if (e.KeyCode == System.Windows.Forms.Keys.Back)
{
IteratorName.SetCursorToTheEnd();
e.Handled = true;
}
}
void IteratorType_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (e.KeyChar == ' '
//&& IteratorType.MyTextBox.CaretIsAtEnd
)
{
IteratorName.SetCursorToTheBeginning();
e.Handled = true;
}
}
void IteratorName_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (e.KeyChar == ' '
//&& IteratorName.MyTextBox.CaretIsAtEnd
)
{
EnumeratedExpression.SetCursorToTheBeginning();
e.Handled = true;
}
}
void EnumeratedExpression_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
}
#endregion
#region Memento
public override void ReadFromMemento(Memento storage)
{
IteratorType.Text = storage["type"];
IteratorName.Text = storage["name"];
EnumeratedExpression.Text = storage["collection"];
}
public override void WriteToMemento(Memento storage)
{
storage["type"] = IteratorType.Text;
storage["name"] = IteratorName.Text;
storage["collection"] = EnumeratedExpression.Text;
}
#endregion
#region AcceptVisitor
public override void AcceptVisitor(IVisitor Visitor)
{
Visitor.Visit(this);
}
#endregion
#region Help
private static string PressHomeOrLeft = "Press [Home] or [LeftArrow] to select the foreach block.";
private static string PressHome = "Press [Home] to select the foreach block.";
private static string PressEnter = "Press [Enter] to jump to the body of the foreach block.";
IEnumerable<string> IteratorType_ProvideHelpStrings()
{
yield return "Press [Tab] or [Space] to jump to the iteration variable name.";
yield return PressHomeOrLeft;
yield return PressEnter;
}
IEnumerable<string> IteratorName_ProvideHelpStrings()
{
yield return "Press [Tab] or [Space] to jump to the collection to iterate over.";
yield return PressHome;
yield return PressEnter;
}
IEnumerable<string> ProvideHelpStringsForTab()
{
yield return "Press [Tab] to jump to the type of an iteration.";
yield return PressHome;
yield return PressEnter;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityStandardAssets.ImageEffects;
/// <summary>
///
/// </summary>
public class GameManager : MonoBehaviour
{
[HideInInspector]
public bool newGame = false;
[HideInInspector]
public bool isLoading = false;
[HideInInspector]
public bool isSaving = false;
public MainGUI mainGUI;
public LoadingScreen loadingScreen;
public GameSession currentSession;
public GameSession[] allSessions = new GameSession[0]; //Tutti i salvataggi fatti fin'ora
private GameSession _tempSession; //Sessione temporanea di appoggio per il salvataggio/caricamento dati.
private GameSettings _gameSettings = new GameSettings();
private BaseCharacter _tempChar;
private SavedSettings _tempSettings;
private BinaryFormatter _binFormatter = new BinaryFormatter();
private FileStream _file = null;
private Camera _mainCamera;
private static List<GameSession> _savedSessions = new List<GameSession>();
private int _screenWidth = Screen.width;
private int _screenHeight = Screen.height;
private int _sessionToLoadIndex;
private static string _settingsPath;
private static string _savesPath;
private static string _dateTimeFormatString = "ddMMyyyyHHmmss";
/// <summary>
///
/// </summary>
public void Start()
{
this._mainCamera = Camera.main;
_settingsPath = Application.persistentDataPath + "/settings.ecd";
_savesPath = Application.persistentDataPath + "/Saves";
//Creates Saves directory and base settings file.
if (!Directory.Exists(Application.persistentDataPath + "/Saves"))
{
Directory.CreateDirectory(Application.persistentDataPath + "/Saves");
}
if (!File.Exists(Application.persistentDataPath + "/settings.ecd"))
{
File.Create(Application.persistentDataPath + "/settings.ecd");
}
LoadAndUpdateSessions();
//Load settings.
this._gameSettings = LoadSettings();
this._sessionToLoadIndex = -1;
//Check if there are any save files and let user chose.
if (allSessions.Length < 1)
{
//NEW GAME NEEDED.
newGame = true;
mainGUI.continueGameButton.gameObject.SetActive(false);
}
//texture2.LoadImage(texture.EncodeToPNG());
//mainMenu.optionsButton.onClick.AddListener(ShowOptionsMenu);
//UnityEngine.Object prefab = AssetDatabase.LoadAssetAtPath("Assets/8-Cores Custom Assets/Prefabs/LoadingScreen.prefab", typeof(GameObject));
//GameObject clone = Instantiate(prefab, Vector3.zero, Quaternion.identity) as GameObject;
//clone.name = "LoadingScreen";
}
/// <summary>
///
/// </summary>
public void Update()
{
if (Input.GetKeyDown(KeyCode.F3))
{
StartCoroutine(Save());
}
if (Input.GetKeyDown(KeyCode.F11))
{
SaveSettings(this._gameSettings);
}
else if (Input.GetKeyDown(KeyCode.F12))
{
this._gameSettings = LoadSettings();
}
}
/// <summary>
///
/// </summary>
private void NewGame() //FUNZIONE DEL RESET TOTALE GLOBALE DE CRISTO
{
if (newGame)
{
currentSession = new GameSession();
//currentSession.character = new SavedCharacter();
this._tempSession = currentSession;
SaveSession(this._tempSession);
UnityEngine.Debug.Log("New game created!");
}
else
{
//WE SHOULD NEVER GET HERE!
UnityEngine.Debug.LogError("GameManager.cs: NewGame() function error!");
}
}
/// <summary>
///
/// </summary>
/// <param name="flag"></param>
private void ShowOptionsMenu(bool flag)
{
//mainMenu.optionsMenu.gameObject.SetActive(!);
}
/// <summary>
///
/// </summary>
/// <param name="flag"></param>
private void ShowSelectSaveMenu(bool flag)
{
}
/// <summary>
///
/// </summary>
public void LoadGame()
{
StartCoroutine(LoadSceneWithPlayerProgress(currentSession, loadingScreen, false));
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IEnumerator Save() //WE SHOULD CHECK SAVING FUNCTION ACKNOWLEDGE MADONNADDIO
{
//PUT FUNC SHOW SAVING IN PROGRESS.
isSaving = true;
//Using lambda expression to return values from SaveMiniature iterator.
yield return SaveMiniature(value => currentSession.miniatureBytes = value);
//Using a temporary session for saving.
this._tempSession = currentSession;
//Save session with index increased.
SaveSession(this._tempSession);
//Re-load all sessions.
LoadAndUpdateSessions();
isSaving = false;
//PUT FUNC SHOW SAVING COMPLETE.
}
/// <summary>
///
/// </summary>
/// <param name="result"></param>
/// <returns></returns>
public IEnumerator SaveMiniature(System.Action<byte[]> result)
{
RenderTexture renderTexture;
Texture2D miniature;
BlurOptimized blur;
//Waiting for end of current frame.
yield return new WaitForEndOfFrame();
blur = this._mainCamera.GetComponent<BlurOptimized>();
renderTexture = new RenderTexture(Screen.width, Screen.height, 24, RenderTextureFormat.ARGB32);
renderTexture.useMipMap = false;
renderTexture.antiAliasing = 1;
RenderTexture.active = renderTexture;
this._mainCamera.targetTexture = renderTexture;
miniature = new Texture2D(Screen.width, Screen.height, TextureFormat.ARGB32, false);
blur.enabled = false; //Disable blur temporarly just for shot.
this._mainCamera.Render();
miniature.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0, false);
//blur.enabled = true;
miniature.Apply();
this._mainCamera.targetTexture = null;
RenderTexture.active = null;
Destroy(renderTexture);
//Return image encoded in byte array.
result(miniature.EncodeToPNG());
}
/// <summary>
///
/// </summary>
/// <param name="session"></param>
private void SaveSession(GameSession session)
{
try
{
this.PrepareSessionForSaving(session);
_savedSessions.Clear();
_savedSessions.Add(session);
this._file = File.Create(_savesPath + "/SAV_" + DateTime.Now.ToString(_dateTimeFormatString) + ".ecd");
this._binFormatter.Serialize(this._file, _savedSessions);
this._file.Close();
UnityEngine.Debug.Log("Saved new session -ID: " + _savedSessions[0].ID + "- to path: " + _savesPath + "/SAV_" + DateTime.Now.ToString(_dateTimeFormatString) + ".ecd");
}
catch (System.Exception)
{
UnityEngine.Debug.LogWarning("Failed to save session.");
throw;
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private GameSession LoadSession(int index)
{
DirectoryInfo dir = new DirectoryInfo(_savesPath);
FileInfo[] fi = dir.GetFiles();
List<GameSession> tempSessionList;
GameSession returnGameSession = null;
int count = fi.Length;
if (Directory.Exists(_savesPath))
{
UnityEngine.Debug.Log("Loading save file...");
for (int i = 0; i < count; i++)
{
string fileName = fi[i].FullName;
if (File.Exists(fileName))
{
this._file = File.Open(fileName, FileMode.Open);
tempSessionList = ((List<GameSession>)this._binFormatter.Deserialize(this._file));
if (tempSessionList[0].ID == index)
{
UnityEngine.Debug.Log("Loaded: " + fileName);
returnGameSession = tempSessionList[0];
continue;
}
}
else
{
//WE SHOULD NEVER GET THERE PORCODIO!!!
UnityEngine.Debug.LogWarning("Error while loading file: File '" + fileName + "' not found.");
break;
}
}
this._file.Close();
}
else
{
UnityEngine.Debug.LogWarning("Error while searching files: Directory '" + _savesPath + "' not found.");
}
return returnGameSession;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private List<GameSession> LoadAllSessions()
{
DirectoryInfo dir = new DirectoryInfo(_savesPath);
FileInfo[] fi = dir.GetFiles();
List<GameSession> tempSessionList;
int count = fi.Length;
_savedSessions.Clear();
if (Directory.Exists(_savesPath))
{
UnityEngine.Debug.Log("Updating save files list...");
for (int i = 0; i < count; i++)
{
string fileName = fi[i].FullName;
if (File.Exists(fileName))
{
this._file = File.Open(fileName, FileMode.Open);
tempSessionList = ((List<GameSession>)this._binFormatter.Deserialize(this._file));
_savedSessions.Add(tempSessionList[0]);
tempSessionList.Clear();
this._file.Close();
UnityEngine.Debug.Log("Found: " + fileName);
}
else
{
//WE SHOULD NEVER GET THERE PORCODIO!!!
UnityEngine.Debug.LogWarning("Error while loading file: File '" + fileName + "' not found.");
}
}
UnityEngine.Debug.Log("Done updating list!");
}
else
{
UnityEngine.Debug.LogWarning("Error while searching files: Directory '" + _savesPath + "' not found.");
}
return _savedSessions;
}
/// <summary>
///
/// </summary>
/// <param name="gameSession"></param>
private void UpdateSession(GameSession gameSession)
{
this._tempChar = GameObject.FindGameObjectWithTag("Player").GetComponent<BaseCharacter>();
//Update player stats.
ClassMerger.MergeClassProperties(gameSession.character, this._tempChar);
//Update player position.
this._tempChar.transform.position = gameSession.character.GetPosition();
this._tempChar.transform.rotation = Quaternion.Euler(gameSession.character.GetRotation());
}
/// <summary>
///
/// </summary>
/// <param name="gameSession"></param>
private void PrepareSessionForSaving(GameSession gameSession)
{
this._tempChar = GameObject.FindGameObjectWithTag("Player").GetComponent<BaseCharacter>();
ClassMerger.MergeClassProperties(this._tempChar, gameSession.character);
gameSession.lastSaveDate = DateTime.Now.ToString();
gameSession.ID = this.GetSavesNumber();
}
/// <summary>
///
/// </summary>
/// <param name="settings"></param>
private void SaveSettings(GameSettings settings)
{
this._tempSettings = new SavedSettings();
ClassMerger.MergeClassProperties(settings, this._tempSettings);
this._file = File.Create(_settingsPath);
this._binFormatter.Serialize(this._file, this._tempSettings);
this._file.Close();
UnityEngine.Debug.Log("Data settings to path: " + _settingsPath);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private GameSettings LoadSettings()
{
GameSettings retSettings = new GameSettings();
this._tempSettings = null;
if (File.Exists(_settingsPath))
{
this._file = File.Open(_settingsPath, FileMode.Open);
this._tempSettings = (SavedSettings)this._binFormatter.Deserialize(this._file);
this._file.Close();
}
else
{
this._tempSettings = new SavedSettings();
UnityEngine.Debug.LogWarning("No settings found, default ones loaded");
}
ClassMerger.MergeClassProperties(this._tempSettings, retSettings);
return retSettings;
}
/// <summary>
/// Load scene in background with loading screen.
/// </summary>
/// <example>
/// This could be the possible usage of <see cref="LoadScene(int, LoadingScreen, bool)"/> method.
/// <code>
/// StartCoroutine(GameSceneManager.LoadSceneAysnc(0, loadingScreen, false));
/// </code>
/// </example>
/// <param name="sceneIndex">Index of scene to load</param>
/// <param name="loadingScreen">Loading screen instance</param>
/// <param name="showProgress">If true, shows the loading text and logo. This should be set to false when loading fast scenes such as house rooms.</param>
/// <returns></returns>
private IEnumerator LoadScene(int sceneIndex, LoadingScreen loadingScreen, bool showProgress)
{
AsyncOperation asyncOp = null;
//Wait for fade in effect before loading the scene.
yield return new WaitForSeconds(0.5f);
//Start loading scene.
asyncOp = SceneManager.LoadSceneAsync(sceneIndex);
//Update progress.
if (showProgress) //If we are not showing progress we don't need to update it.
{
StartCoroutine(UpdateLoadingProgress(loadingScreen, asyncOp));
}
//Busy wait.
while (!asyncOp.isDone)
{
yield return new WaitForSeconds(0.1f);
}
yield return new WaitForSeconds(0.5f); //Just to make sure we loaded everything
}
/// <summary>
///
/// </summary>
/// <param name="sceneIndex"></param>
/// <param name="gameSession"></param>
/// <param name="loadingScreen"></param>
/// <param name="showProgress"></param>
/// <returns></returns>
private IEnumerator LoadSceneWithPlayerProgress(GameSession gameSession, LoadingScreen loadingScreen, bool showProgress)
{
//We have to lock player movement/all types of input while loading.
//player.LockInputs() or maybe player.LockMovement()
//Disable GUI so that the player understands that inputs are temporarly disabled.
mainGUI.gameObject.SetActive(false);
Camera.main.GetComponent<CameraController>().enabled = false;
loadingScreen.showProgress = showProgress;
loadingScreen.enabled = true;
if (gameSession.SceneIndex > -1)
{
currentSession = LoadSession(gameSession.SceneIndex);
this.UpdateSession(currentSession);
}
else
{
//WE SHOULD NEVER GET HERE!
UnityEngine.Debug.LogError("GameManager.cs: LoadGame() function error!");
}
//Wait for scene to be loaded.
yield return LoadScene(gameSession.SceneIndex, loadingScreen, showProgress);
//
//Now we can update everything
Transform tempTransform;
tempTransform = GetPlayerSpawnPosInCurrentScene();
gameSession.character.SetPosition(tempTransform.position);
gameSession.character.SetRotation(tempTransform.rotation.eulerAngles);
UpdateSession(gameSession);
Camera.main.GetComponent<CameraController>().enabled = true;
//
yield return new WaitForSeconds(0.5f);
//When we finished updating, restore GUI and player movement.
loadingScreen.enabled = false;
//Enable GUI so that the player understands that inputs are re-enabled.
mainGUI.gameObject.SetActive(true);
//Now we can restore player inputs.
//player.UnlockInputs() or maybe player.UnlockMovement()
}
/// <summary>
///
/// </summary>
/// <param name="loadingScreen"></param>
/// <param name="asyncOp"></param>
/// <returns></returns>
private IEnumerator UpdateLoadingProgress(LoadingScreen loadingScreen, AsyncOperation asyncOp)
{
while (loadingScreen.enabled)
{
if (asyncOp != null && loadingScreen != null)
{
loadingScreen.text.text = string.Format("Now Loading... {0}%", asyncOp.progress * 100);
}
else
{
UnityEngine.Debug.Log("GameManager.cs: Error while updating loading progress, variables 'loadingScreen' and 'asyncOp' can't be null.");
}
yield return new WaitForSecondsRealtime(0.05f);
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private int GetSavesNumber()
{
DirectoryInfo dir = new DirectoryInfo(_savesPath);
FileInfo[] fi = dir.GetFiles();
return fi.Length;
}
/// <summary>
///
/// </summary>
/// <param name="index"></param>
private void UpdateSessionToLoadIndex(int index)
{
this._sessionToLoadIndex = index;
}
/// <summary>
///
/// </summary>
private void PopulateSaveList()
{
mainGUI.PopulateSaveList(this);
}
/// <summary>
///
/// </summary>
private void LoadAndUpdateSessions()
{
//Resize array lenght according to saves number.
Array.Resize(ref allSessions, GetSavesNumber());
//Load all sessions, user will chose wich one to load.
allSessions = LoadAllSessions().ToArray();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private Transform GetPlayerSpawnPosInCurrentScene()
{
return GameObject.FindGameObjectWithTag("PlayerSpawnPoint").transform;
}
}
| |
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace NGnono.Framework.Security.Cryptography
{
public static class CryptoHelper
{
#region base64 AES
/// <summary>
/// Encrypts specified plaintext using Rijndael symmetric key algorithm
/// and returns a base64-encoded result.
/// </summary>
/// <param name="plainText">
/// Plaintext value to be encrypted.
/// </param>
/// <param name="passPhrase">
/// Passphrase from which a pseudo-random password will be derived. The
/// derived password will be used to generate the encryption key.
/// Passphrase can be any string. In this example we assume that this
/// passphrase is an ASCII string.
/// </param>
/// <param name="saltValue">
/// Salt value used along with passphrase to generate password. Salt can
/// be any string. In this example we assume that salt is an ASCII string.
/// </param>
/// <param name="hashAlgorithm">
/// Hash algorithm used to generate password. Allowed values are: "MD5" and
/// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
/// </param>
/// <param name="passwordIterations">
/// Number of iterations used to generate password. One or two iterations
/// should be enough.
/// </param>
/// <param name="initVector">
/// Initialization vector (or IV). This value is required to encrypt the
/// first block of plaintext data. For RijndaelManaged class IV must be
/// exactly 16 ASCII characters long.
/// </param>
/// <param name="keySize">
/// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
/// Longer keys are more secure than shorter keys.
/// </param>
/// <returns>
/// Encrypted value formatted as a base64-encoded string.
/// </returns>
public static string Base64AESEncrypt(string plainText,
string passPhrase,
string saltValue,
string hashAlgorithm,
int passwordIterations,
string initVector,
int keySize)
{
//safety check
if (string.IsNullOrEmpty(plainText))
{
plainText = string.Empty;
}
// Convert strings into byte arrays.
// Let us assume that strings only contain ASCII codes.
// If strings include Unicode characters, use Unicode, UTF7, or UTF8
// encoding.
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
// Convert our plaintext into a byte array.
// Let us assume that plaintext contains UTF8-encoded characters.
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
// First, we must create a password, from which the key will be derived.
// This password will be generated from the specified passphrase and
// salt value. The password will be created using the specified hash
// algorithm. Password creation can be done in several iterations.
PasswordDeriveBytes password = new PasswordDeriveBytes(
passPhrase,
saltValueBytes,
hashAlgorithm,
passwordIterations);
// Use the password to generate pseudo-random bytes for the encryption
// key. Specify the size of the key in bytes (instead of bits).
byte[] keyBytes = password.GetBytes(keySize / 8);
// Create uninitialized Rijndael encryption object.
RijndaelManaged symmetricKey = new RijndaelManaged();
// It is reasonable to set encryption mode to Cipher Block Chaining
// (CBC). Use default options for other symmetric key parameters.
symmetricKey.Mode = CipherMode.CBC;
// Generate encryptor from the existing key bytes and initialization
// vector. Key size will be defined based on the number of the key
// bytes.
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
keyBytes,
initVectorBytes);
// Define memory stream which will be used to hold encrypted data.
MemoryStream memoryStream = new MemoryStream();
// Define cryptographic stream (always use Write mode for encryption).
CryptoStream cryptoStream = new CryptoStream(memoryStream,
encryptor,
CryptoStreamMode.Write);
// Start encrypting.
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
// Finish encrypting.
cryptoStream.FlushFinalBlock();
// Convert our encrypted data from a memory stream into a byte array.
byte[] cipherTextBytes = memoryStream.ToArray();
// Close both streams.
memoryStream.Close();
cryptoStream.Close();
// Convert encrypted data into a base64-encoded string.
string cipherText = Convert.ToBase64String(cipherTextBytes);
// Return encrypted string.
return cipherText;
}
/// <summary>
/// Decrypts specified ciphertext using Rijndael symmetric key algorithm.
/// </summary>
/// <param name="cipherText">
/// Base64-formatted ciphertext value.
/// </param>
/// <param name="passPhrase">
/// Passphrase from which a pseudo-random password will be derived. The
/// derived password will be used to generate the encryption key.
/// Passphrase can be any string. In this example we assume that this
/// passphrase is an ASCII string.
/// </param>
/// <param name="saltValue">
/// Salt value used along with passphrase to generate password. Salt can
/// be any string. In this example we assume that salt is an ASCII string.
/// </param>
/// <param name="hashAlgorithm">
/// Hash algorithm used to generate password. Allowed values are: "MD5" and
/// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
/// </param>
/// <param name="passwordIterations">
/// Number of iterations used to generate password. One or two iterations
/// should be enough.
/// </param>
/// <param name="initVector">
/// Initialization vector (or IV). This value is required to encrypt the
/// first block of plaintext data. For RijndaelManaged class IV must be
/// exactly 16 ASCII characters long.
/// </param>
/// <param name="keySize">
/// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
/// Longer keys are more secure than shorter keys.
/// </param>
/// <returns>
/// Decrypted string value.
/// </returns>
/// <remarks>
/// Most of the logic in this function is similar to the Encrypt
/// logic. In order for decryption to work, all parameters of this function
/// - except cipherText value - must match the corresponding parameters of
/// the Encrypt function which was called to generate the
/// ciphertext.
/// </remarks>
public static string Base64AESDecrypt(string cipherText,
string passPhrase,
string saltValue,
string hashAlgorithm,
int passwordIterations,
string initVector,
int keySize)
{
//safety check
if (string.IsNullOrEmpty(cipherText))
{
return "";
}
// Convert strings defining encryption key characteristics into byte
// arrays. Let us assume that strings only contain ASCII codes.
// If strings include Unicode characters, use Unicode, UTF7, or UTF8
// encoding.
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
// Convert our ciphertext into a byte array.
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
// First, we must create a password, from which the key will be
// derived. This password will be generated from the specified
// passphrase and salt value. The password will be created using
// the specified hash algorithm. Password creation can be done in
// several iterations.
PasswordDeriveBytes password = new PasswordDeriveBytes(
passPhrase,
saltValueBytes,
hashAlgorithm,
passwordIterations);
// Use the password to generate pseudo-random bytes for the encryption
// key. Specify the size of the key in bytes (instead of bits).
byte[] keyBytes = password.GetBytes(keySize / 8);
// Create uninitialized Rijndael encryption object.
RijndaelManaged symmetricKey = new RijndaelManaged();
// It is reasonable to set encryption mode to Cipher Block Chaining
// (CBC). Use default options for other symmetric key parameters.
symmetricKey.Mode = CipherMode.CBC;
// Generate decryptor from the existing key bytes and initialization
// vector. Key size will be defined based on the number of the key
// bytes.
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
keyBytes,
initVectorBytes);
// Define memory stream which will be used to hold encrypted data.
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
// Define cryptographic stream (always use Read mode for encryption).
CryptoStream cryptoStream = new CryptoStream(memoryStream,
decryptor,
CryptoStreamMode.Read);
// Since at this point we don't know what the size of decrypted data
// will be, allocate the buffer long enough to hold ciphertext;
// plaintext is never longer than ciphertext.
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
// Start decrypting.
int decryptedByteCount = cryptoStream.Read(plainTextBytes,
0,
plainTextBytes.Length);
// Close both streams.
memoryStream.Close();
cryptoStream.Close();
// Convert decrypted data into a string.
// Let us assume that the original plaintext string was UTF8-encoded.
string plainText = Encoding.UTF8.GetString(plainTextBytes,
0,
decryptedByteCount);
// Return decrypted string.
return plainText;
}
#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.
namespace System.DirectoryServices.Protocols
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Collections;
using System.Text;
public sealed class BerConverter
{
private BerConverter() { }
public static byte[] Encode(string format, params object[] value)
{
if (format == null)
throw new ArgumentNullException("format");
// no need to turn on invalid encoding detection as we just do string->byte[] conversion.
UTF8Encoding utf8Encoder = new UTF8Encoding();
byte[] encodingResult = null;
// value is allowed to be null in certain scenario, so if it is null, just set it to empty array.
if (value == null)
value = new object[0];
Debug.WriteLine("Begin encoding\n");
// allocate the berelement
BerSafeHandle berElement = new BerSafeHandle();
int valueCount = 0;
int error = 0;
for (int formatCount = 0; formatCount < format.Length; formatCount++)
{
char fmt = format[formatCount];
if (fmt == '{' || fmt == '}' || fmt == '[' || fmt == ']' || fmt == 'n')
{
// no argument needed
error = Wldap32.ber_printf_emptyarg(berElement, new string(fmt, 1));
}
else if (fmt == 't' || fmt == 'i' || fmt == 'e')
{
if (valueCount >= value.Length)
{
// we don't have enough argument for the format string
Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
if (!(value[valueCount] is int))
{
// argument is wrong
Debug.WriteLine("type should be int\n");
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
// one int argument
error = Wldap32.ber_printf_int(berElement, new string(fmt, 1), (int)value[valueCount]);
// increase the value count
valueCount++;
}
else if (fmt == 'b')
{
if (valueCount >= value.Length)
{
// we don't have enough argument for the format string
Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
if (!(value[valueCount] is bool))
{
// argument is wrong
Debug.WriteLine("type should be boolean\n");
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
// one int argument
error = Wldap32.ber_printf_int(berElement, new string(fmt, 1), (bool)value[valueCount] ? 1 : 0);
// increase the value count
valueCount++;
}
else if (fmt == 's')
{
if (valueCount >= value.Length)
{
// we don't have enough argument for the format string
Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
if (value[valueCount] != null && !(value[valueCount] is string))
{
// argument is wrong
Debug.WriteLine("type should be string, but receiving value has type of ");
Debug.WriteLine(value[valueCount].GetType());
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
// one string argument
byte[] tempValue = null;
if (value[valueCount] != null)
{
tempValue = utf8Encoder.GetBytes((string)value[valueCount]);
}
error = EncodingByteArrayHelper(berElement, tempValue, 'o');
// increase the value count
valueCount++;
}
else if (fmt == 'o' || fmt == 'X')
{
// we need to have one arguments
if (valueCount >= value.Length)
{
// we don't have enough argument for the format string
Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
if (value[valueCount] != null && !(value[valueCount] is byte[]))
{
// argument is wrong
Debug.WriteLine("type should be byte[], but receiving value has type of ");
Debug.WriteLine(value[valueCount].GetType());
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
byte[] tempValue = (byte[])value[valueCount];
error = EncodingByteArrayHelper(berElement, tempValue, fmt);
valueCount++;
}
else if (fmt == 'v')
{
// we need to have one arguments
if (valueCount >= value.Length)
{
// we don't have enough argument for the format string
Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
if (value[valueCount] != null && !(value[valueCount] is string[]))
{
// argument is wrong
Debug.WriteLine("type should be string[], but receiving value has type of ");
Debug.WriteLine(value[valueCount].GetType());
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
string[] stringValues = (string[])value[valueCount];
byte[][] tempValues = null;
if (stringValues != null)
{
tempValues = new byte[stringValues.Length][];
for (int i = 0; i < stringValues.Length; i++)
{
string s = stringValues[i];
if (s == null)
tempValues[i] = null;
else
{
tempValues[i] = utf8Encoder.GetBytes(s);
}
}
}
error = EncodingMultiByteArrayHelper(berElement, tempValues, 'V');
valueCount++;
}
else if (fmt == 'V')
{
// we need to have one arguments
if (valueCount >= value.Length)
{
// we don't have enough argument for the format string
Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
if (value[valueCount] != null && !(value[valueCount] is byte[][]))
{
// argument is wrong
Debug.WriteLine("type should be byte[][], but receiving value has type of ");
Debug.WriteLine(value[valueCount].GetType());
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
}
byte[][] tempValue = (byte[][])value[valueCount];
error = EncodingMultiByteArrayHelper(berElement, tempValue, fmt);
valueCount++;
}
else
{
Debug.WriteLine("Format string contains undefined character: ");
Debug.WriteLine(new string(fmt, 1));
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterUndefineChar));
}
// process the return value
if (error == -1)
{
Debug.WriteLine("ber_printf failed\n");
throw new BerConversionException();
}
}
// get the binary value back
berval binaryValue = new berval();
IntPtr flattenptr = (IntPtr)0;
try
{
// can't use SafeBerval here as CLR creates a SafeBerval which points to a different memory location, but when doing memory
// deallocation, wldap has special check. So have to use IntPtr directly here.
error = Wldap32.ber_flatten(berElement, ref flattenptr);
if (error == -1)
{
Debug.WriteLine("ber_flatten failed\n");
throw new BerConversionException();
}
if (flattenptr != (IntPtr)0)
{
Marshal.PtrToStructure(flattenptr, binaryValue);
}
if (binaryValue == null || binaryValue.bv_len == 0)
{
encodingResult = new byte[0];
}
else
{
encodingResult = new byte[binaryValue.bv_len];
Marshal.Copy(binaryValue.bv_val, encodingResult, 0, binaryValue.bv_len);
}
}
finally
{
if (flattenptr != (IntPtr)0)
Wldap32.ber_bvfree(flattenptr);
}
return encodingResult;
}
public static object[] Decode(string format, byte[] value)
{
bool decodeSucceeded;
object[] decodeResult = TryDecode(format, value, out decodeSucceeded);
if (decodeSucceeded)
return decodeResult;
else
throw new BerConversionException();
}
internal static object[] TryDecode(string format, byte[] value, out bool decodeSucceeded)
{
if (format == null)
throw new ArgumentNullException("format");
Debug.WriteLine("Begin decoding\n");
UTF8Encoding utf8Encoder = new UTF8Encoding(false, true);
berval berValue = new berval();
ArrayList resultList = new ArrayList();
BerSafeHandle berElement = null;
object[] decodeResult = null;
decodeSucceeded = false;
if (value == null)
{
berValue.bv_len = 0;
berValue.bv_val = (IntPtr)0;
}
else
{
berValue.bv_len = value.Length;
berValue.bv_val = Marshal.AllocHGlobal(value.Length);
Marshal.Copy(value, 0, berValue.bv_val, value.Length);
}
try
{
berElement = new BerSafeHandle(berValue);
}
finally
{
if (berValue.bv_val != (IntPtr)0)
Marshal.FreeHGlobal(berValue.bv_val);
}
int error = 0;
for (int formatCount = 0; formatCount < format.Length; formatCount++)
{
char fmt = format[formatCount];
if (fmt == '{' || fmt == '}' || fmt == '[' || fmt == ']' || fmt == 'n' || fmt == 'x')
{
error = Wldap32.ber_scanf(berElement, new string(fmt, 1));
if (error != 0)
Debug.WriteLine("ber_scanf for {, }, [, ], n or x failed");
}
else if (fmt == 'i' || fmt == 'e' || fmt == 'b')
{
int result = 0;
error = Wldap32.ber_scanf_int(berElement, new string(fmt, 1), ref result);
if (error == 0)
{
if (fmt == 'b')
{
// should return a bool
bool boolResult = false;
if (result == 0)
boolResult = false;
else
boolResult = true;
resultList.Add(boolResult);
}
else
{
resultList.Add(result);
}
}
else
Debug.WriteLine("ber_scanf for format character 'i', 'e' or 'b' failed");
}
else if (fmt == 'a')
{
// return a string
byte[] byteArray = DecodingByteArrayHelper(berElement, 'O', ref error);
if (error == 0)
{
string s = null;
if (byteArray != null)
s = utf8Encoder.GetString(byteArray);
resultList.Add(s);
}
}
else if (fmt == 'O')
{
// return berval
byte[] byteArray = DecodingByteArrayHelper(berElement, fmt, ref error);
if (error == 0)
{
// add result to the list
resultList.Add(byteArray);
}
}
else if (fmt == 'B')
{
// return a bitstring and its length
IntPtr ptrResult = (IntPtr)0;
int length = 0;
error = Wldap32.ber_scanf_bitstring(berElement, "B", ref ptrResult, ref length);
if (error == 0)
{
byte[] byteArray = null;
if (ptrResult != (IntPtr)0)
{
byteArray = new byte[length];
Marshal.Copy(ptrResult, byteArray, 0, length);
}
resultList.Add(byteArray);
}
else
Debug.WriteLine("ber_scanf for format character 'B' failed");
// no need to free memory as wldap32 returns the original pointer instead of a duplicating memory pointer that
// needs to be freed
}
else if (fmt == 'v')
{
//null terminate strings
byte[][] byteArrayresult = null;
string[] stringArray = null;
byteArrayresult = DecodingMultiByteArrayHelper(berElement, 'V', ref error);
if (error == 0)
{
if (byteArrayresult != null)
{
stringArray = new string[byteArrayresult.Length];
for (int i = 0; i < byteArrayresult.Length; i++)
{
if (byteArrayresult[i] == null)
{
stringArray[i] = null;
}
else
{
stringArray[i] = utf8Encoder.GetString(byteArrayresult[i]);
}
}
}
resultList.Add(stringArray);
}
}
else if (fmt == 'V')
{
byte[][] result = null;
result = DecodingMultiByteArrayHelper(berElement, fmt, ref error);
if (error == 0)
{
resultList.Add(result);
}
}
else
{
Debug.WriteLine("Format string contains undefined character\n");
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterUndefineChar));
}
if (error != 0)
{
// decode failed, just return
return decodeResult;
}
}
decodeResult = new object[resultList.Count];
for (int count = 0; count < resultList.Count; count++)
{
decodeResult[count] = resultList[count];
}
decodeSucceeded = true;
return decodeResult;
}
private static int EncodingByteArrayHelper(BerSafeHandle berElement, byte[] tempValue, char fmt)
{
int error = 0;
// one byte array, one int arguments
if (tempValue != null)
{
IntPtr tmp = Marshal.AllocHGlobal(tempValue.Length);
Marshal.Copy(tempValue, 0, tmp, tempValue.Length);
HGlobalMemHandle memHandle = new HGlobalMemHandle(tmp);
error = Wldap32.ber_printf_bytearray(berElement, new string(fmt, 1), memHandle, tempValue.Length);
}
else
{
error = Wldap32.ber_printf_bytearray(berElement, new string(fmt, 1), new HGlobalMemHandle((IntPtr)0), 0);
}
return error;
}
private static byte[] DecodingByteArrayHelper(BerSafeHandle berElement, char fmt, ref int error)
{
error = 0;
IntPtr result = (IntPtr)0;
berval binaryValue = new berval();
byte[] byteArray = null;
// can't use SafeBerval here as CLR creates a SafeBerval which points to a different memory location, but when doing memory
// deallocation, wldap has special check. So have to use IntPtr directly here.
error = Wldap32.ber_scanf_ptr(berElement, new string(fmt, 1), ref result);
try
{
if (error == 0)
{
if (result != (IntPtr)0)
{
Marshal.PtrToStructure(result, binaryValue);
byteArray = new byte[binaryValue.bv_len];
Marshal.Copy(binaryValue.bv_val, byteArray, 0, binaryValue.bv_len);
}
}
else
Debug.WriteLine("ber_scanf for format character 'O' failed");
}
finally
{
if (result != (IntPtr)0)
Wldap32.ber_bvfree(result);
}
return byteArray;
}
private static int EncodingMultiByteArrayHelper(BerSafeHandle berElement, byte[][] tempValue, char fmt)
{
IntPtr berValArray = (IntPtr)0;
IntPtr tempPtr = (IntPtr)0;
SafeBerval[] managedBerVal = null;
int error = 0;
try
{
if (tempValue != null)
{
int i = 0;
berValArray = Utility.AllocHGlobalIntPtrArray(tempValue.Length + 1);
int structSize = Marshal.SizeOf(typeof(SafeBerval));
managedBerVal = new SafeBerval[tempValue.Length];
for (i = 0; i < tempValue.Length; i++)
{
byte[] byteArray = tempValue[i];
// construct the managed berval
managedBerVal[i] = new SafeBerval();
if (byteArray == null)
{
managedBerVal[i].bv_len = 0;
managedBerVal[i].bv_val = (IntPtr)0;
}
else
{
managedBerVal[i].bv_len = byteArray.Length;
managedBerVal[i].bv_val = Marshal.AllocHGlobal(byteArray.Length);
Marshal.Copy(byteArray, 0, managedBerVal[i].bv_val, byteArray.Length);
}
// allocate memory for the unmanaged structure
IntPtr valPtr = Marshal.AllocHGlobal(structSize);
Marshal.StructureToPtr(managedBerVal[i], valPtr, false);
tempPtr = (IntPtr)((long)berValArray + IntPtr.Size * i);
Marshal.WriteIntPtr(tempPtr, valPtr);
}
tempPtr = (IntPtr)((long)berValArray + IntPtr.Size * i);
Marshal.WriteIntPtr(tempPtr, (IntPtr)0);
}
error = Wldap32.ber_printf_berarray(berElement, new string(fmt, 1), berValArray);
GC.KeepAlive(managedBerVal);
}
finally
{
if (berValArray != (IntPtr)0)
{
for (int i = 0; i < tempValue.Length; i++)
{
IntPtr ptr = Marshal.ReadIntPtr(berValArray, IntPtr.Size * i);
if (ptr != (IntPtr)0)
Marshal.FreeHGlobal(ptr);
}
Marshal.FreeHGlobal(berValArray);
}
}
return error;
}
private static byte[][] DecodingMultiByteArrayHelper(BerSafeHandle berElement, char fmt, ref int error)
{
error = 0;
// several berval
IntPtr ptrResult = (IntPtr)0;
int i = 0;
ArrayList binaryList = new ArrayList();
IntPtr tempPtr = (IntPtr)0;
byte[][] result = null;
try
{
error = Wldap32.ber_scanf_ptr(berElement, new string(fmt, 1), ref ptrResult);
if (error == 0)
{
if (ptrResult != (IntPtr)0)
{
tempPtr = Marshal.ReadIntPtr(ptrResult);
while (tempPtr != (IntPtr)0)
{
berval ber = new berval();
Marshal.PtrToStructure(tempPtr, ber);
byte[] berArray = new byte[ber.bv_len];
Marshal.Copy(ber.bv_val, berArray, 0, ber.bv_len);
binaryList.Add(berArray);
i++;
tempPtr = Marshal.ReadIntPtr(ptrResult, i * IntPtr.Size);
}
result = new byte[binaryList.Count][];
for (int j = 0; j < binaryList.Count; j++)
{
result[j] = (byte[])binaryList[j];
}
}
}
else
Debug.WriteLine("ber_scanf for format character 'V' failed");
}
finally
{
if (ptrResult != (IntPtr)0)
{
Wldap32.ber_bvecfree(ptrResult);
}
}
return result;
}
}
}
| |
/*********************************************************************
*
* Main Dialog for MPFS21
*
*********************************************************************
* FileName: MPFS21Form.cs
* Dependencies: Microsoft .NET Framework 2.0
* Processor: x86
* Complier: Microsoft Visual C# 2008 Express Edition
* Company: Microchip Technology, Inc.
*
* Software License Agreement
*
* This software is owned by Microchip Technology Inc. ("Microchip")
* and is supplied to you for use exclusively as described in the
* associated software agreement. This software is protected by
* software and other intellectual property laws. Any use in
* violation of the software license may subject the user to criminal
* sanctions as well as civil liability. Copyright 2008 Microchip
* Technology Inc. All rights reserved.
*
*
* THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT
* WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF
* PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
* BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE
* THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER
* SIMILAR COSTS, WHETHER ASSERTED ON THE BASIS OF CONTRACT, TORT
* (INCLUDING NEGLIGENCE), BREACH OF WARRANTY, OR OTHERWISE.
*
*
* Author Date Comment
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Elliott Wood 4/17/2008 Original
********************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using Microchip;
using System.IO;
using System.Net;
namespace MPFS21
{
public partial class MPFS21Form : Form
{
#region Fields
private int groupBox1Height, groupBox2Height, groupBox3Height, groupBox4Height;
private String strVersion, strBuildDate, strWebPageDestpathMDD;
private bool lockDisplay = true;
private MPFS2WebClient web;
private bool generationResult;
private List<string> generateLog;
#endregion
public MPFS21Form()
{
InitializeComponent();
groupBox1Height = groupBox1.Height;
groupBox2Height = groupBox2.Height;
groupBox3Height = groupBox3.Height;
groupBox4Height = groupBox4.Height;
}
#region Form Load and Unload Functions
/// <summary>
/// Configures the form on load
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MPFS21Form_Load(object sender, EventArgs e)
{
// Load version and build date
Version ver = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
strVersion = ver.Major + "." + ver.Minor + "." + ver.Build + "." + ver.Revision;
strBuildDate = new DateTime(2000, 1, 1).AddDays(ver.Build).ToString("MMMM d, yyyy");
lblAbout.Text = strBuildDate + "\nVersion " + strVersion;
lblAbout.Margin = new Padding(190 - lblAbout.Width, 3, 0, 0);
// Marshal in a few config things
if (Settings.Default.StartWithDirectory)
radStartDir.Checked = true;
else
radStartImg.Checked = true;
switch (Settings.Default.OutputFormat)
{
case 1:
radOutputC18.Checked = true;
break;
case 2:
radOutputASM30.Checked = true;
break;
case 3:
radOutputMDD.Checked = true;
break;
default:
radOutputBIN.Checked = true;
break;
}
txtSourceDir.Text = Settings.Default.SourceDirectory;
txtSourceImage.Text = Settings.Default.SourceImage;
txtImageName.Text = Settings.Default.ImageName;
txtProjectDir.Text = Settings.Default.ProjectDirectory;
lockDisplay = false;
CorrectDisplay(sender, e);
}
/// <summary>
/// Saves application settings before exiting
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MPFS21Form_FormClosing(object sender, FormClosingEventArgs e)
{
// Marshal out a few config things
if (radStartDir.Checked)
Settings.Default.StartWithDirectory = true;
else
Settings.Default.StartWithDirectory = false;
if (radOutputBIN.Checked)
Settings.Default.OutputFormat = 0;
else if (radOutputC18.Checked)
Settings.Default.OutputFormat = 1;
else if (radOutputASM30.Checked)
Settings.Default.OutputFormat = 2;
else if (radOutputMDD.Checked)
Settings.Default.OutputFormat = 3;
Settings.Default.SourceDirectory = txtSourceDir.Text;
Settings.Default.SourceImage = txtSourceImage.Text;
Settings.Default.ImageName = txtImageName.Text;
Settings.Default.ProjectDirectory = txtProjectDir.Text;
// Save application settings
global::MPFS21.Settings.Default.Save();
}
#endregion
#region Display Option Manager
/// <summary>
/// Makes sure the proper options are visible at all times
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void CorrectDisplay(object sender, EventArgs e)
{
if (lockDisplay)
return;
lockDisplay = true;
// Correct the display settings as per MDD requirement
if (radOutputMDD.Checked)
{
// Disable Pre built MPFS image option when MDD is selected
radStartImg.Enabled = false;
// Disable advanced setting option when MDD is selected
btnAdvanced.Enabled = false;
// No file name option when MDD is selected
txtImageName.Visible = false;
label10.Visible = false;
lblType.Visible = false;
}
else
{
radStartImg.Enabled = true;
btnAdvanced.Enabled = true;
txtImageName.Visible = true;
label10.Visible = true;
lblType.Visible = true;
}
// Properly configure the output extension
if (radOutputBIN.Checked)
lblType.Text = "(*.bin)";
else if (radOutputC18.Checked)
lblType.Text = "(*.c)";
else if (radOutputASM30.Checked)
lblType.Text = "(*.s)";
// else if (radOutputMDD.Checked)
// lblType.Text = "(*.c)";
// Configure upload settings enabled/disbled
if (chkUpload.Checked || radStartImg.Checked)
{
txtUploadDestination.Enabled = true;
btnUploadSettings.Enabled = true;
}
else
{
txtUploadDestination.Enabled = false;
btnUploadSettings.Enabled = false;
}
// Show correct input label
if (radStartImg.Checked)
lblInput.Text = "Source Image:";
else
lblInput.Text = "Source Directory:";
// Show the correct text on the button
if (radStartImg.Checked)
btnGenerate.Text = "Upload";
else if (radOutputBIN.Checked && chkUpload.Checked)
btnGenerate.Text = "Generate and Upload";
else
btnGenerate.Text = "Generate";
// Show the correct upload path option
txtUploadDestination.Text = GetProtocol() + "://" + Settings.Default.UploadUser +
"@" + Settings.Default.UploadAddress + "/";
txtUploadDestination.Text += " ( ==> to modify ==> )";
// Show only the appropriate steps
if (radStartImg.Checked)
{
txtSourceImage.Visible = true;
txtSourceDir.Visible = false;
chkUpload.Visible = false;
this.ToggleSteps(0, 0, groupBox4Height);
}
else if (radOutputBIN.Checked)
{
txtSourceImage.Visible = false;
txtSourceDir.Visible = true;
chkUpload.Visible = true;
this.ToggleSteps(groupBox2Height, groupBox3Height, groupBox4Height);
}
else
{
txtSourceImage.Visible = false;
txtSourceDir.Visible = true;
chkUpload.Visible = true;
this.ToggleSteps(groupBox2Height, groupBox3Height, 0);
}
lockDisplay = false;
}
#endregion
#region Animation Functions
/// <summary>
/// Hides or shows the various steps
/// </summary>
/// <param name="g2Target">Target height for groupBox2</param>
/// <param name="g3Target">Target height for groupBox3</param>
/// <param name="g4Target">Target height for groupBox4</param>
private void ToggleSteps(int g2Target, int g3Target, int g4Target)
{
// Step towards the target height slowly
while(groupBox2.Height != g2Target ||
groupBox3.Height != g3Target ||
groupBox4.Height != g4Target)
{
StepToTarget(groupBox2, g2Target);
StepToTarget(groupBox3, g3Target);
StepToTarget(groupBox4, g4Target);
this.Refresh();
Thread.Sleep(20);
}
}
/// <summary>
/// Steps a GroupBox towards its target size
/// </summary>
/// <param name="obj">The GroupBox to step</param>
/// <param name="target">Target size for the object</param>
private void StepToTarget(GroupBox obj, int target)
{
if (obj.Height == target)
return;
int step = (int)((obj.Height - target) * 0.25);
if (obj.Height > target)
step += 1;
else
step -= 1;
obj.Height -= step;
this.Height -= step;
}
#endregion
/// <summary>
/// Handles the generation when clicked.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGenerate_Click(object sender, EventArgs e)
{
// Disable the button
btnGenerate.Enabled = false;
// Build an image
if(radStartDir.Checked)
{
//// Make sure the project directory is correct
//if(txtProjectDir.Text.Contains(txtSourceDir.Text))
//{
// generationResult = false;
// generateLog = new List<string>();
// generateLog.Add("ERROR: The project directory is located in the source " +
// "directory. The generator cannot run if the image is to be placed " +
// "in the source directory. Please select the base MPLAB project " +
// "directory before continuing.");
// generationResult = false;
// ShowResultDialog("The image could not be built.");
// return;
//}
// Set up an appropriate builder
MPFSBuilder builder;
if(Settings.Default.OutputVersion == 2)
{
builder = new MPFS2Builder(txtProjectDir.Text, txtImageName.Text);
((MPFS2Builder)builder).DynamicTypes = Settings.Default.DynamicFiles;
((MPFS2Builder)builder).NonGZipTypes = Settings.Default.NoCompressFiles;
}
else
{
builder = new MPFSClassicBuilder(txtProjectDir.Text, txtImageName.Text);
((MPFSClassicBuilder)builder).ReserveBlock = (UInt32)Settings.Default.ReserveBlockClassic;
}
// Add the files to the image
myStatusMsg.Text = "Adding source files to image...";
builder.AddDirectory(txtSourceDir.Text, "");
// Generate the image
myStatusMsg.Text = "Generating output image...";
myProgress.Value = (radOutputBIN.Checked && chkUpload.Checked) ? 20 : 70;
if (radOutputBIN.Checked)
generationResult = builder.Generate(MPFSOutputFormat.BIN);
else if (radOutputC18.Checked)
generationResult = builder.Generate(MPFSOutputFormat.C18);
else if (radOutputMDD.Checked)
generationResult = builder.Generate(MPFSOutputFormat.MDD);
else if (radOutputASM30.Checked)
generationResult = builder.Generate(MPFSOutputFormat.ASM30);
// Indicate full progress for non-uploads
myProgress.Value = (radOutputBIN.Checked && chkUpload.Checked) ? 20 : 120;
Thread.Sleep(10);
// Retrieve the log
generateLog = builder.Log;
// Perform the upload if needed
if (radOutputBIN.Checked && chkUpload.Checked && generationResult)
{
UploadImage(builder.GeneratedImageFileName);
}
else
{
if (generationResult)
ShowResultDialog("The MPFS" + ((Settings.Default.OutputVersion == 1) ? "" : "2") +
" image was successfully generated.");
else
ShowResultDialog("Errors were encountered while generating the MPFS image.");
}
// Show a warning if index has changed
if (builder.IndexUpdated)
{
MessageBox.Show("The dynamic variables in your web pages have changed!\n\n" +
"Remember to recompile your MPLAB project before continuing\n" +
"to ensure that the project is in sync.",
"MPFS2 Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
// This is just an upload
else
{
generationResult = true;
generateLog = new List<string>();
UploadImage(txtSourceImage.Text);
}
}
/// <summary>
/// Upload a file from disk to the board
/// </summary>
/// <param name="filename"></param>
private void UploadImage(String filename)
{
if (!File.Exists(filename))
{
generateLog.Add("ERROR: Could not open " + filename);
generationResult = false;
ShowResultDialog("The image could not be uploaded.");
}
String protocol = GetProtocol();
FileInfo fileinfo = new FileInfo(filename);
if (protocol == "http")
generateLog.Add("\r\nUploading MPFS2 image: " + fileinfo.Length + " bytes");
else
generateLog.Add("\r\nUploading MPFS Classic image: " + fileinfo.Length + " bytes");
// Set up web client and the credentials
web = new MPFS2WebClient();
if (Settings.Default.UploadUser.Length > 0)
{
web.UseDefaultCredentials = false;
web.Credentials = new NetworkCredential(Settings.Default.UploadUser, Settings.Default.UploadPass);
}
// Update the status bar display
myStatusMsg.Text = "Contacting device for upload...";
myProgress.Style = ProgressBarStyle.Marquee;
Refresh();
// Register event handlers and start the upload
web.UploadProgressChanged += new UploadProgressChangedEventHandler(web_UploadProgressChanged);
web.UploadFileCompleted += new UploadFileCompletedEventHandler(web_UploadFileCompleted);
web.UploadFileAsync(new Uri(
protocol + "://" +
Settings.Default.UploadAddress + "/" +
Settings.Default.UploadPath),
filename);
}
/// <summary>
/// Handle status updates from the web client
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void web_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
myProgress.Style = ProgressBarStyle.Blocks;
myStatusMsg.Text = "Uploading image (" + e.BytesSent + " / " + e.TotalBytesToSend + " bytes)";
if(e.ProgressPercentage < 50 && e.ProgressPercentage >= 0)
myProgress.Value = 20 + (int)(1.5*e.ProgressPercentage);
if (e.ProgressPercentage == 50)
{
myStatusMsg.Text = "Waiting for upload to complete...";
myProgress.Style = ProgressBarStyle.Marquee;
}
}
/// <summary>
/// Handles the completion event from the web client
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void web_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
{
// First, stop the marquee
myProgress.Style = ProgressBarStyle.Blocks;
myProgress.Value = 120;
myStatusMsg.Text = "Process Complete... See status dialog.";
// Display the results
if (e.Error == null)
ShowResultDialog("The MPFS image upload was successfully completed.");
else
{
generationResult = false;
generateLog.Add("\r\nERROR: Could not contact remote device for upload.");
generateLog.Add("ERROR: " + e.Error.Message);
ShowResultDialog("The MPFS image could not be uploaded.");
}
}
/// <summary>
/// Displays the results of a generation / upload routine
/// </summary>
/// <param name="message"></param>
private void ShowResultDialog(String message)
{
LogWindow dlg = new LogWindow();
if (generationResult)
dlg.Image = SystemIcons.Asterisk;
else
dlg.Image = SystemIcons.Error;
dlg.Message = message;
dlg.Log = generateLog;
// This forces the log window to the top if
// the application is behind another.
this.Focus();
// Show the log window
dlg.ShowDialog();
myProgress.Style = ProgressBarStyle.Blocks;
myProgress.Value = 0;
myStatusMsg.Text = "[Generator Idle]";
btnGenerate.Enabled = true;
}
#region Button Handlers
/// <summary>
/// Selects the source file or directory
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSourceDir_Click(object sender, EventArgs e)
{
if (radStartDir.Checked)
{
FolderBrowserDialog dlg = new FolderBrowserDialog();
dlg.SelectedPath = txtSourceDir.Text;
dlg.Description = "Select the directory in which your web pages are stored:";
if (dlg.ShowDialog() == DialogResult.OK)
txtSourceDir.Text = dlg.SelectedPath;
DirectoryInfo dir = new DirectoryInfo(dlg.SelectedPath);
txtProjectDir.Text = dir.Parent.FullName;
}
else
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "MPFS Image (*.bin)|*.bin";
dlg.FileName = txtSourceImage.Text;
if (dlg.ShowDialog() == DialogResult.OK)
txtSourceImage.Text = dlg.FileName;
}
}
/// <summary>
/// Selects the project directory
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnProjectDir_Click(object sender, EventArgs e)
{
FolderBrowserDialog dlg = new FolderBrowserDialog();
dlg.SelectedPath = txtProjectDir.Text;
dlg.Description = "Select the directory in which your MPLAB project is located:";
if (dlg.ShowDialog() == DialogResult.OK)
txtProjectDir.Text = dlg.SelectedPath;
}
/// <summary>
/// Shows the advanced options dialog
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAdvanced_Click(object sender, EventArgs e)
{
AdvancedOptions dlg = new AdvancedOptions();
dlg.ShowDialog();
CorrectDisplay(sender, e);
}
/// <summary>
/// Shows the About box when the version label is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lblAbout_Click(object sender, EventArgs e)
{
AboutBox dlg = new AboutBox();
dlg.ShowDialog();
}
/// <summary>
/// Shows the upload settings dialog when the button is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnUploadSettings_Click(object sender, EventArgs e)
{
UploadSettings dlg = new UploadSettings();
dlg.ShowDialog();
CorrectDisplay(sender, e);
}
#endregion
/// <summary>
/// Obtains the protocol to be used for uploading
/// </summary>
/// <returns></returns>
private String GetProtocol()
{
// For images being built, base on the output version
if (radStartDir.Checked)
{
if (Settings.Default.OutputVersion == 2)
return "http";
else
return "ftp";
}
// For images being uploaded from disk, try to read the file header
// If file does not exist, default to http
else
{
try
{
BinaryReader bin = new BinaryReader(new FileStream(txtSourceImage.Text, FileMode.Open), Encoding.ASCII);
if (bin.ReadByte() == (byte)'M' && bin.ReadByte() == (byte)'P' &&
bin.ReadByte() == (byte)'F' && bin.ReadByte() == (byte)'S' &&
bin.ReadByte() == (byte)0x02)
{
// Upload an MPFS2 image
bin.Close();
return "http";
}
else
{
// Upload an MPFS Classic image
bin.Close();
return "ftp";
}
}
catch
{
// Will trap if the file did not exist or was unreadable
return "http";
}
}
}
}
/// <summary>
/// Overrides the WebClient class to force all FTP connections to passive mode
/// </summary>
public class MPFS2WebClient : System.Net.WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest req = base.GetWebRequest(address);
if (req is FtpWebRequest)
((FtpWebRequest)req).UsePassive = false;
return req;
}
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Store
{
/*
* 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 BytesRef = Lucene.Net.Util.BytesRef;
using UnicodeUtil = Lucene.Net.Util.UnicodeUtil;
/// <summary>
/// Abstract base class for performing write operations of Lucene's low-level
/// data types.
///
/// <para/><see cref="DataOutput"/> may only be used from one thread, because it is not
/// thread safe (it keeps internal state like file position).
/// </summary>
public abstract class DataOutput
{
/// <summary>
/// Writes a single byte.
/// <para/>
/// The most primitive data type is an eight-bit byte. Files are
/// accessed as sequences of bytes. All other data types are defined
/// as sequences of bytes, so file formats are byte-order independent.
/// </summary>
/// <seealso cref="DataInput.ReadByte()"/>
public abstract void WriteByte(byte b);
/// <summary>
/// Writes an array of bytes.
/// </summary>
/// <param name="b">the bytes to write</param>
/// <param name="length">the number of bytes to write</param>
/// <seealso cref="DataInput.ReadBytes(byte[], int, int)"/>
public virtual void WriteBytes(byte[] b, int length)
{
WriteBytes(b, 0, length);
}
/// <summary>
/// Writes an array of bytes. </summary>
/// <param name="b"> the bytes to write </param>
/// <param name="offset"> the offset in the byte array </param>
/// <param name="length"> the number of bytes to write </param>
/// <seealso cref="DataInput.ReadBytes(byte[], int, int)"/>
public abstract void WriteBytes(byte[] b, int offset, int length);
/// <summary>
/// Writes an <see cref="int"/> as four bytes.
/// <para/>
/// 32-bit unsigned integer written as four bytes, high-order bytes first.
/// <para/>
/// NOTE: this was writeInt() in Lucene
/// </summary>
/// <seealso cref="DataInput.ReadInt32()"/>
public virtual void WriteInt32(int i)
{
WriteByte((byte)(sbyte)(i >> 24));
WriteByte((byte)(sbyte)(i >> 16));
WriteByte((byte)(sbyte)(i >> 8));
WriteByte((byte)(sbyte)i);
}
/// <summary>
/// Writes a short as two bytes.
/// <para/>
/// NOTE: this was writeShort() in Lucene
/// </summary>
/// <seealso cref="DataInput.ReadInt16()"/>
public virtual void WriteInt16(short i)
{
WriteByte((byte)(sbyte)((ushort)i >> 8));
WriteByte((byte)(sbyte)(ushort)i);
}
/// <summary>
/// Writes an <see cref="int"/> in a variable-length format. Writes between one and
/// five bytes. Smaller values take fewer bytes. Negative numbers are
/// supported, but should be avoided.
/// <para>VByte is a variable-length format for positive integers is defined where the
/// high-order bit of each byte indicates whether more bytes remain to be read. The
/// low-order seven bits are appended as increasingly more significant bits in the
/// resulting integer value. Thus values from zero to 127 may be stored in a single
/// byte, values from 128 to 16,383 may be stored in two bytes, and so on.</para>
/// <para>VByte Encoding Example</para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Byte 1</term>
/// <term>Byte 2</term>
/// <term>Byte 3</term>
/// </listheader>
/// <item>
/// <term>0</term>
/// <term>00000000</term>
/// <term></term>
/// <term></term>
/// </item>
/// <item>
/// <term>1</term>
/// <term>00000001</term>
/// <term></term>
/// <term></term>
/// </item>
/// <item>
/// <term>2</term>
/// <term>00000010</term>
/// <term></term>
/// <term></term>
/// </item>
/// <item>
/// <term>...</term>
/// <term></term>
/// <term></term>
/// <term></term>
/// </item>
/// <item>
/// <term>127</term>
/// <term>01111111</term>
/// <term></term>
/// <term></term>
/// </item>
/// <item>
/// <term>128</term>
/// <term>10000000</term>
/// <term>00000001</term>
/// <term></term>
/// </item>
/// <item>
/// <term>129</term>
/// <term>10000001</term>
/// <term>00000001</term>
/// <term></term>
/// </item>
/// <item>
/// <term>130</term>
/// <term>10000010</term>
/// <term>00000001</term>
/// <term></term>
/// </item>
/// <item>
/// <term>...</term>
/// <term></term>
/// <term></term>
/// <term></term>
/// </item>
/// <item>
/// <term>16,383</term>
/// <term>11111111</term>
/// <term>01111111</term>
/// <term></term>
/// </item>
/// <item>
/// <term>16,384</term>
/// <term>10000000</term>
/// <term>10000000</term>
/// <term>00000001</term>
/// </item>
/// <item>
/// <term>16,385</term>
/// <term>10000001</term>
/// <term>10000000</term>
/// <term>00000001</term>
/// </item>
/// <item>
/// <term>...</term>
/// <term></term>
/// <term></term>
/// <term></term>
/// </item>
/// </list>
///
/// <para>this provides compression while still being efficient to decode.</para>
/// <para/>
/// NOTE: this was writeVInt() in Lucene
/// </summary>
/// <param name="i"> Smaller values take fewer bytes. Negative numbers are
/// supported, but should be avoided. </param>
/// <exception cref="System.IO.IOException"> If there is an I/O error writing to the underlying medium. </exception>
/// <seealso cref="DataInput.ReadVInt32()"/>
public void WriteVInt32(int i)
{
while ((i & ~0x7F) != 0)
{
WriteByte((byte)unchecked((sbyte)((i & 0x7F) | 0x80)));
i = (int)((uint)i >> 7);
}
WriteByte((byte)(sbyte)i);
}
/// <summary>
/// Writes a <see cref="long"/> as eight bytes.
/// <para/>
/// 64-bit unsigned integer written as eight bytes, high-order bytes first.
/// <para/>
/// NOTE: this was writeLong() in Lucene
/// </summary>
/// <seealso cref="DataInput.ReadInt64()"/>
public virtual void WriteInt64(long i)
{
WriteInt32((int)(i >> 32));
WriteInt32((int)i);
}
/// <summary>
/// Writes an <see cref="long"/> in a variable-length format. Writes between one and nine
/// bytes. Smaller values take fewer bytes. Negative numbers are not
/// supported.
/// <para/>
/// The format is described further in <see cref="DataOutput.WriteVInt32(int)"/>.
/// <para/>
/// NOTE: this was writeVLong() in Lucene
/// </summary>
/// <seealso cref="DataInput.ReadVInt64()"/>
public void WriteVInt64(long i)
{
Debug.Assert(i >= 0L);
while ((i & ~0x7FL) != 0L)
{
WriteByte((byte)unchecked((sbyte)((i & 0x7FL) | 0x80L)));
i = (long)((ulong)i >> 7);
}
WriteByte((byte)(sbyte)i);
}
/// <summary>
/// Writes a string.
/// <para/>
/// Writes strings as UTF-8 encoded bytes. First the length, in bytes, is
/// written as a <see cref="WriteVInt32"/>, followed by the bytes.
/// </summary>
/// <seealso cref="DataInput.ReadString()"/>
public virtual void WriteString(string s)
{
var utf8Result = new BytesRef(10);
UnicodeUtil.UTF16toUTF8(s, 0, s.Length, utf8Result);
WriteVInt32(utf8Result.Length);
WriteBytes(utf8Result.Bytes, 0, utf8Result.Length);
}
private const int COPY_BUFFER_SIZE = 16384;
private byte[] copyBuffer;
/// <summary>
/// Copy numBytes bytes from input to ourself. </summary>
public virtual void CopyBytes(DataInput input, long numBytes)
{
Debug.Assert(numBytes >= 0, "numBytes=" + numBytes);
long left = numBytes;
if (copyBuffer == null)
{
copyBuffer = new byte[COPY_BUFFER_SIZE];
}
while (left > 0)
{
int toCopy;
if (left > COPY_BUFFER_SIZE)
{
toCopy = COPY_BUFFER_SIZE;
}
else
{
toCopy = (int)left;
}
input.ReadBytes(copyBuffer, 0, toCopy);
WriteBytes(copyBuffer, 0, toCopy);
left -= toCopy;
}
}
/// <summary>
/// Writes a <see cref="T:IDictionary{string, string}"/>.
/// <para/>
/// First the size is written as an <see cref="WriteInt32(int)"/>,
/// followed by each key-value pair written as two consecutive
/// <see cref="WriteString(string)"/>s.
/// </summary>
/// <param name="map"> Input <see cref="T:IDictionary{string, string}"/>. May be <c>null</c> (equivalent to an empty dictionary) </param>
public virtual void WriteStringStringMap(IDictionary<string, string> map)
{
if (map == null)
{
WriteInt32(0);
}
else
{
WriteInt32(map.Count);
foreach (KeyValuePair<string, string> entry in map)
{
WriteString(entry.Key);
WriteString(entry.Value);
}
}
}
/// <summary>
/// Writes a <see cref="string"/> set.
/// <para/>
/// First the size is written as an <see cref="WriteInt32(int)"/>,
/// followed by each value written as a
/// <see cref="WriteString(string)"/>.
/// </summary>
/// <param name="set"> Input <see cref="T:ISet{string}"/>. May be <c>null</c> (equivalent to an empty set) </param>
public virtual void WriteStringSet(ISet<string> set)
{
if (set == null)
{
WriteInt32(0);
}
else
{
WriteInt32(set.Count);
foreach (string value in set)
{
WriteString(value);
}
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Directives.cs" company="Solidsoft Reply Ltd.">
// Copyright (c) 2015 Solidsoft Reply Limited. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace SolidsoftReply.Esb.Libraries.BizTalk.Orchestration
{
using System;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// Class containing the result of the resolution
/// </summary>
[Serializable]
public class Directives : IEnumerable<Directive>
{
/// <summary>
/// Directives enumerator.
/// </summary>
private readonly IEnumerator<Directive> enumerator;
/// <summary>
/// The resolver directive items.
/// </summary>
private readonly Resolution.Directives directives;
/// <summary>
/// Initializes a new instance of the <see cref="Directives"/> class.
/// </summary>
/// <param name="directives">
/// The original set of resolution directives.
/// </param>
public Directives(Resolution.Directives directives)
{
if (directives == null)
{
return;
}
this.directives = directives;
this.enumerator = new DirectivesEnumerator(directives);
}
/// <summary>
/// Gets a value indicating whether any of the directives define a service windows.
/// Returns true if the current time is in any of those service windows. Otherwise
/// returns false. If no service windows are defined, always returns true.
/// </summary>
public bool InAnyServiceWindow
{
get
{
return this.directives.InAnyServiceWindow;
}
}
/// <summary>
/// Gets a TimeSpan for the time of day at which the next service window opens.
/// If no service window later than now is defined, returns TimeSpan.MaxValue.
/// </summary>
public TimeSpan NextWindowOpen
{
get
{
return this.directives.NextWindowOpen;
}
}
/// <summary>
/// Gets a TimeSpan for the time of day at which the current service window closes.
/// If no service window later than now is defined, returns TimeSpan.MaxValue.
/// </summary>
public TimeSpan CurrentWindowClose
{
get
{
return this.directives.CurrentWindowClose;
}
}
/// <summary>
/// Gets the number of directives.
/// </summary>
public int Count
{
get
{
return this.directives.Count;
}
}
/// <summary>
/// Gets a directive by index.
/// </summary>
/// <param name="index">The directive index.</param>
/// <returns>The indexed resolver directive.</returns>
public Directive this[int index]
{
get
{
return this.GetDirective(index);
}
}
/// <summary>
/// Gets a directive by name.
/// </summary>
/// <param name="name">The directive name.</param>
/// <returns>The named resolver directive.</returns>
public Directive this[string name]
{
get
{
return this.GetDirective(name);
}
}
/// <summary>
/// Returns the indexed directive.
/// </summary>
/// <param name="index">The directive index.</param>
/// <returns>A named resolver directive.</returns>
public Directive GetDirective(int index)
{
return new Directive(this.directives.GetDirective(index));
}
/// <summary>
/// Returns the named directive.
/// </summary>
/// <param name="name">The directive name.</param>
/// <returns>A named resolver directive.</returns>
public Directive GetDirective(string name)
{
return new Directive(this.directives.GetDirective(name));
}
/// <summary>
/// Returns the first directive. If no directive exists, returns null.
/// </summary>
/// <returns>The first directive, or null.</returns>
public Directive FirstOrDefault()
{
return new Directive(this.directives.FirstOrDefault());
}
/// <summary>
/// Performs all BAM actions for configured BAM steps in all the directives.
/// </summary>
/// <param name="data">The BAM step data.</param>
public void OnStep(BamStepData data)
{
this.directives.OnStep(data, Resolution.MultiStepControl.AllSteps, false);
}
/// <summary>
/// Performs all BAM actions for configured BAM steps in all the directives. This method
/// can optionally handle step processing after application of a map.
/// </summary>
/// <param name="data">The BAM step data.</param>
/// <param name="afterMap">Indicates if the step is after the application of a map.</param>
public void OnStep(BamStepData data, bool afterMap)
{
this.directives.OnStep(data, Resolution.MultiStepControl.AllSteps, afterMap);
}
/// <summary>
/// Performs all BAM actions for configured BAM steps in either the first or
/// all the directives. Optionally perform BAM actions for all step extensions.
/// </summary>
/// <param name="data">The BAM step data.</param>
/// <param name="depth">
/// Specify the depth of BAM processing; first or all steps and, optionally,
/// each step extension.
/// </param>
public void OnStep(BamStepData data, Resolution.MultiStepControl depth)
{
this.directives.OnStep(data, depth, false);
}
/// <summary>
/// Performs all BAM actions for configured BAM steps in either the first or all
/// the directives. Optionally perform BAM actions for all step extensions.
/// This method can optionally handle step processing after application of a map.
/// </summary>
/// <param name="data">The BAM step data.</param>
/// <param name="depth">
/// Specify the depth of BAM processing; first or all steps and, optionally,
/// each step extension.
/// </param>
/// <param name="afterMap">Indicates if the step is after the application of a map.</param>
public void OnStep(BamStepData data, Resolution.MultiStepControl depth, bool afterMap)
{
this.directives.OnStep(data, depth, afterMap);
}
/// <summary>
/// Performs all BAM actions for a BAM steps in a specified directive.
/// </summary>
/// <param name="directiveName">The name of the directive that defines the BAM step.</param>
/// <param name="data">The BAM step data.</param>
public void OnStep(string directiveName, BamStepData data)
{
this.directives.OnStep(directiveName, data);
}
/// <summary>
/// Performs all BAM actions for a BAM steps in a specified directive. This method can
/// optionally handle step processing after application of a map.
/// </summary>
/// <param name="directiveName">The name of the directive that defines the BAM step.</param>
/// <param name="data">The BAM step data.</param>
/// <param name="afterMap">Indicates if the step is after the application of a map.</param>
public void OnStep(string directiveName, BamStepData data, bool afterMap)
{
this.directives.OnStep(directiveName, data, afterMap);
}
/// <summary>
/// Return the item enumerator
/// </summary>
/// <returns>An IEnumerator interface</returns>
IEnumerator<Directive> IEnumerable<Directive>.GetEnumerator()
{
return this.enumerator;
}
/// <summary>
/// Return the item enumerator
/// </summary>
/// <returns>An IEnumerator interface</returns>
public IEnumerator GetEnumerator()
{
return this.enumerator;
}
/// <summary>
/// An enumerator for resolution directives.
/// </summary>
[Serializable]
public class DirectivesEnumerator : IEnumerator<Directive>
{
/// <summary>
/// The collection of resolution directives.
/// </summary>
private readonly Resolution.Directives directives;
/// <summary>
/// The current index.
/// </summary>
private int currentIndex;
/// <summary>
/// The current resolution directive.
/// </summary>
private Resolution.Directive currentDirective;
/// <summary>
/// Initializes a new instance of the <see cref="DirectivesEnumerator"/> class.
/// </summary>
/// <param name="directives">
/// The resolution directives to be enumerated.
/// </param>
public DirectivesEnumerator(Resolution.Directives directives)
{
this.directives = directives;
this.currentIndex = -1;
this.currentDirective = default(Resolution.Directive);
}
/// <summary>
/// Gets the current directive.
/// </summary>
object IEnumerator.Current
{
get { return this.Current; }
}
/// <summary>
/// Gets the current directive.
/// </summary>
public Directive Current
{
get
{
return new Directive(this.currentDirective);
}
}
/// <summary>
/// Move to the next directive in the collection.
/// </summary>
/// <returns>
/// True if the next directive exists; otherwise false.
/// </returns>
public bool MoveNext()
{
// Avoids going beyond the end of the collection.
if (++this.currentIndex >= this.directives.Count)
{
return false;
}
// Set current box to next item in collection.
this.currentDirective = this.directives[this.currentIndex];
return true;
}
/// <summary>
/// Reset the enumerator.
/// </summary>
public void Reset()
{
this.currentIndex = -1;
}
/// <summary>
/// Dispose the current enumerator.
/// </summary>
void IDisposable.Dispose()
{
}
}
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
using System.Reflection;
namespace NUnit.Framework.Internal
{
[TestFixture]
public class RuntimeFrameworkTests
{
#if NETCOREAPP
static readonly RuntimeType currentRuntime = RuntimeType.NetCore;
#else
static readonly RuntimeType currentRuntime =
Type.GetType("Mono.Runtime", false) != null
? RuntimeType.Mono
: RuntimeType.NetFramework;
#endif
[Test]
public void CanGetCurrentFramework()
{
RuntimeFramework framework = RuntimeFramework.CurrentFramework;
Assert.That(framework.Runtime, Is.EqualTo(currentRuntime), "#1");
Assert.That(framework.ClrVersion, Is.EqualTo(Environment.Version), "#2");
}
#if NET45
[Test]
public void TargetFrameworkIsSetCorrectly()
{
// We use reflection so it will compile and pass on Mono,
// including older versions that do not have the property.
var prop = typeof(AppDomainSetup).GetProperty("FrameworkName");
Assume.That(prop, Is.Not.Null);
Assert.That(
prop.GetValue(AppDomain.CurrentDomain.SetupInformation),
Is.EqualTo(".NETFramework,Version=v4.5"));
}
[Test]
public void DoesNotRunIn40CompatibilityModeWhenCompiled45()
{
var uri = new Uri( "http://host.com/path./" );
var uriStr = uri.ToString();
Assert.AreEqual( "http://host.com/path./", uriStr );
}
#endif
[Test]
[TestCaseSource(nameof(netcoreRuntimes))]
public void SpecifyingNetCoreVersioningThrowsPlatformException(string netcoreRuntime)
{
PlatformHelper platformHelper = new PlatformHelper();
Assert.Throws<PlatformNotSupportedException>(() => platformHelper.IsPlatformSupported(netcoreRuntime));
}
[Test]
public void SpecifyingNetCoreWithoutVersioningSucceeds()
{
PlatformHelper platformHelper = new PlatformHelper();
bool isNetCore;
#if NETCOREAPP
isNetCore = true;
#else
isNetCore = false;
#endif
Assert.AreEqual(isNetCore, platformHelper.IsPlatformSupported("netcore"));
}
[TestCaseSource(nameof(frameworkData))]
public void CanCreateUsingFrameworkVersion(FrameworkData data)
{
RuntimeFramework framework = new RuntimeFramework(data.Runtime, data.FrameworkVersion);
Assert.AreEqual(data.Runtime, framework.Runtime, "#1");
Assert.AreEqual(data.FrameworkVersion, framework.FrameworkVersion, "#2");
Assert.AreEqual(data.ClrVersion, framework.ClrVersion, "#3");
}
[TestCaseSource(nameof(frameworkData))]
public void CanCreateUsingClrVersion(FrameworkData data)
{
Assume.That(data.FrameworkVersion.Major != 3, "#0");
//.NET Framework 4.0+ and .NET Core 2.0+ all have the same CLR version
Assume.That(data.FrameworkVersion.Major != 4 && data.FrameworkVersion.Minor != 5, "#0");
Assume.That(data.Runtime != RuntimeType.NetCore, "#0");
RuntimeFramework framework = new RuntimeFramework(data.Runtime, data.ClrVersion);
Assert.AreEqual(data.Runtime, framework.Runtime, "#1");
Assert.AreEqual(data.FrameworkVersion, framework.FrameworkVersion, "#2");
Assert.AreEqual(data.ClrVersion, framework.ClrVersion, "#3");
}
[TestCaseSource(nameof(frameworkData))]
public void CanParseRuntimeFramework(FrameworkData data)
{
RuntimeFramework framework = RuntimeFramework.Parse(data.Representation);
Assert.AreEqual(data.Runtime, framework.Runtime, "#1");
Assert.AreEqual(data.ClrVersion, framework.ClrVersion, "#2");
}
[TestCaseSource(nameof(frameworkData))]
public void CanDisplayFrameworkAsString(FrameworkData data)
{
RuntimeFramework framework = new RuntimeFramework(data.Runtime, data.FrameworkVersion);
Assert.AreEqual(data.Representation, framework.ToString(), "#1");
Assert.AreEqual(data.DisplayName, framework.DisplayName, "#2");
}
[TestCaseSource(nameof(matchData))]
public bool CanMatchRuntimes(RuntimeFramework f1, RuntimeFramework f2)
{
return f1.Supports(f2);
}
internal static TestCaseData[] matchData = new TestCaseData[] {
new TestCaseData(
new RuntimeFramework(RuntimeType.NetFramework, new Version(3,5)),
new RuntimeFramework(RuntimeType.NetFramework, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetFramework, new Version(2,0)),
new RuntimeFramework(RuntimeType.NetFramework, new Version(3,5)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetFramework, new Version(3,5)),
new RuntimeFramework(RuntimeType.NetFramework, new Version(3,5)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetFramework, new Version(2,0)),
new RuntimeFramework(RuntimeType.NetFramework, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetFramework, new Version(2,0)),
new RuntimeFramework(RuntimeType.NetFramework, new Version(2,0,50727)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetFramework, new Version(2,0,50727)),
new RuntimeFramework(RuntimeType.NetFramework, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetFramework, new Version(2,0,50727)),
new RuntimeFramework(RuntimeType.NetFramework, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetFramework, new Version(2,0)),
new RuntimeFramework(RuntimeType.Mono, new Version(2,0)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetFramework, new Version(2,0)),
new RuntimeFramework(RuntimeType.NetFramework, new Version(1,1)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetFramework, new Version(2,0,50727)),
new RuntimeFramework(RuntimeType.NetFramework, new Version(2,0,40607)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetFramework, new Version(3,5)),
new RuntimeFramework(RuntimeType.NetFramework, new Version(4,0)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetFramework, new Version(4,0)),
new RuntimeFramework(RuntimeType.NetFramework, new Version(4,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetFramework, new Version(3,5)),
new RuntimeFramework(RuntimeType.NetFramework, new Version(4,5)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetFramework, new Version(4,0)),
new RuntimeFramework(RuntimeType.NetFramework, new Version(4,5)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetFramework, new Version(2,0)),
new RuntimeFramework(RuntimeType.NetFramework, new Version(4,5)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetFramework, new Version(4,5)),
new RuntimeFramework(RuntimeType.NetFramework, new Version(2,0)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetFramework, new Version(4,5)),
new RuntimeFramework(RuntimeType.NetFramework, new Version(3,5)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetFramework, new Version(4,5)),
new RuntimeFramework(RuntimeType.NetFramework, new Version(4,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(1,0)),
new RuntimeFramework(RuntimeType.NetCore, new Version(2,0)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(2,0)),
new RuntimeFramework(RuntimeType.NetCore, new Version(1,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(3,0)),
new RuntimeFramework(RuntimeType.NetCore, new Version(1,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(1,0)),
new RuntimeFramework(RuntimeType.NetCore, new Version(1,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(2,0)),
new RuntimeFramework(RuntimeType.NetCore, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(2,1)),
new RuntimeFramework(RuntimeType.NetCore, new Version(2,1)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(3,0)),
new RuntimeFramework(RuntimeType.NetCore, new Version(3,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(2,0)),
new RuntimeFramework(RuntimeType.NetCore, new Version(2,1)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(2,1)),
new RuntimeFramework(RuntimeType.NetCore, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(2,2)),
new RuntimeFramework(RuntimeType.NetCore, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(2,2)),
new RuntimeFramework(RuntimeType.NetCore, new Version(2,1)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(5,0)),
new RuntimeFramework(RuntimeType.NetCore, new Version(3,1)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(3,1)),
new RuntimeFramework(RuntimeType.NetCore, new Version(5,0)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(5,0)),
new RuntimeFramework(RuntimeType.NetCore, new Version(3,1)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(5,0)),
new RuntimeFramework(RuntimeType.NetFramework, new Version(4,8)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.Mono, new Version(1,1)), // non-existent version but it works
new RuntimeFramework(RuntimeType.Mono, new Version(1,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Mono, new Version(2,0)),
new RuntimeFramework(RuntimeType.Any, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Any, new Version(2,0)),
new RuntimeFramework(RuntimeType.Mono, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Any, new Version(2,0)),
new RuntimeFramework(RuntimeType.Any, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Any, new Version(2,0)),
new RuntimeFramework(RuntimeType.Any, new Version(4,0)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetFramework, RuntimeFramework.DefaultVersion),
new RuntimeFramework(RuntimeType.NetFramework, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetFramework, new Version(2,0)),
new RuntimeFramework(RuntimeType.NetFramework, RuntimeFramework.DefaultVersion))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Any, RuntimeFramework.DefaultVersion),
new RuntimeFramework(RuntimeType.NetFramework, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetFramework, new Version(2,0)),
new RuntimeFramework(RuntimeType.Any, RuntimeFramework.DefaultVersion))
.Returns(true)
};
public struct FrameworkData
{
public RuntimeType Runtime;
public Version FrameworkVersion;
public Version ClrVersion;
public string Representation;
public string DisplayName;
public FrameworkData(RuntimeType runtime, Version frameworkVersion, Version clrVersion,
string representation, string displayName)
{
Runtime = runtime;
FrameworkVersion = frameworkVersion;
ClrVersion = clrVersion;
Representation = representation;
DisplayName = displayName;
}
public override string ToString()
{
return string.Format("<{0},{1},{2}>", this.Runtime, this.FrameworkVersion, this.ClrVersion);
}
}
internal static FrameworkData[] frameworkData = new FrameworkData[] {
new FrameworkData(RuntimeType.NetFramework, new Version(1,0), new Version(1,0,3705), "net-1.0", "Net 1.0"),
new FrameworkData(RuntimeType.NetFramework, new Version(1,1), new Version(1,1,4322), "net-1.1", "Net 1.1"),
new FrameworkData(RuntimeType.NetFramework, new Version(2,0), new Version(2,0,50727), "net-2.0", "Net 2.0"),
new FrameworkData(RuntimeType.NetFramework, new Version(3,0), new Version(2,0,50727), "net-3.0", "Net 3.0"),
new FrameworkData(RuntimeType.NetFramework, new Version(3,5), new Version(2,0,50727), "net-3.5", "Net 3.5"),
new FrameworkData(RuntimeType.NetFramework, new Version(4,0), new Version(4,0,30319), "net-4.0", "Net 4.0"),
new FrameworkData(RuntimeType.NetFramework, new Version(4,5), new Version(4,0,30319), "net-4.5", "Net 4.5"),
new FrameworkData(RuntimeType.NetFramework, RuntimeFramework.DefaultVersion, RuntimeFramework.DefaultVersion, "net", "Net"),
new FrameworkData(RuntimeType.NetCore, new Version(2, 0), new Version(4,0,30319), "netcore-2.0", "NetCore 2.0"),
new FrameworkData(RuntimeType.NetCore, new Version(2, 1), new Version(4,0,30319), "netcore-2.1", "NetCore 2.1"),
new FrameworkData(RuntimeType.NetCore, new Version(5, 0), new Version(4,0,30319), "net-5.0", "Net 5.0"),
new FrameworkData(RuntimeType.NetCore, RuntimeFramework.DefaultVersion, RuntimeFramework.DefaultVersion, "netcore", "NetCore"),
new FrameworkData(RuntimeType.Mono, new Version(1,0), new Version(1,1,4322), "mono-1.0", "Mono 1.0"),
new FrameworkData(RuntimeType.Mono, new Version(2,0), new Version(2,0,50727), "mono-2.0", "Mono 2.0"),
new FrameworkData(RuntimeType.Mono, new Version(3,5), new Version(2,0,50727), "mono-3.5", "Mono 3.5"),
new FrameworkData(RuntimeType.Mono, new Version(4,0), new Version(4,0,30319), "mono-4.0", "Mono 4.0"),
new FrameworkData(RuntimeType.Mono, RuntimeFramework.DefaultVersion, RuntimeFramework.DefaultVersion, "mono", "Mono"),
new FrameworkData(RuntimeType.Any, new Version(1,1), new Version(1,1,4322), "v1.1", "v1.1"),
new FrameworkData(RuntimeType.Any, new Version(2,0), new Version(2,0,50727), "v2.0", "v2.0"),
new FrameworkData(RuntimeType.Any, new Version(3,5), new Version(2,0,50727), "v3.5", "v3.5"),
new FrameworkData(RuntimeType.Any, new Version(4,0), new Version(4,0,30319), "v4.0", "v4.0"),
new FrameworkData(RuntimeType.Any, RuntimeFramework.DefaultVersion, RuntimeFramework.DefaultVersion, "any", "Any")
};
internal static string[] netcoreRuntimes = new string[] {
"netcore-1.0",
"netcore-1.1",
"netcore-2.0",
"netcore-2.1",
"netcore-2.2",
"netcore-3.0",
"netcore-3.1",
};
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
namespace System.Diagnostics
{
/// <devdoc>
/// <para>
/// Provides access to local and remote
/// processes. Enables you to start and stop system processes.
/// </para>
/// </devdoc>
public partial class Process : Component
{
private bool _haveProcessId;
private int _processId;
private bool _haveProcessHandle;
private SafeProcessHandle _processHandle;
private bool _isRemoteMachine;
private string _machineName;
private ProcessInfo _processInfo;
private ProcessThreadCollection _threads;
private ProcessModuleCollection _modules;
private bool _haveWorkingSetLimits;
private IntPtr _minWorkingSet;
private IntPtr _maxWorkingSet;
private bool _haveProcessorAffinity;
private IntPtr _processorAffinity;
private bool _havePriorityClass;
private ProcessPriorityClass _priorityClass;
private ProcessStartInfo _startInfo;
private bool _watchForExit;
private bool _watchingForExit;
private EventHandler _onExited;
private bool _exited;
private int _exitCode;
private DateTime? _startTime;
private DateTime _exitTime;
private bool _haveExitTime;
private bool _priorityBoostEnabled;
private bool _havePriorityBoostEnabled;
private bool _raisedOnExited;
private RegisteredWaitHandle _registeredWaitHandle;
private WaitHandle _waitHandle;
private StreamReader _standardOutput;
private StreamWriter _standardInput;
private StreamReader _standardError;
private bool _disposed;
private static object s_createProcessLock = new object();
private bool _standardInputAccessed;
private StreamReadMode _outputStreamReadMode;
private StreamReadMode _errorStreamReadMode;
// Support for asynchronously reading streams
public event DataReceivedEventHandler OutputDataReceived;
public event DataReceivedEventHandler ErrorDataReceived;
// Abstract the stream details
internal AsyncStreamReader _output;
internal AsyncStreamReader _error;
internal bool _pendingOutputRead;
internal bool _pendingErrorRead;
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Diagnostics.Process'/> class.
/// </para>
/// </devdoc>
public Process()
{
// This class once inherited a finalizer. For backward compatibility it has one so that
// any derived class that depends on it will see the behaviour expected. Since it is
// not used by this class itself, suppress it immediately if this is not an instance
// of a derived class it doesn't suffer the GC burden of finalization.
if (GetType() == typeof(Process))
{
GC.SuppressFinalize(this);
}
_machineName = ".";
_outputStreamReadMode = StreamReadMode.Undefined;
_errorStreamReadMode = StreamReadMode.Undefined;
}
private Process(string machineName, bool isRemoteMachine, int processId, ProcessInfo processInfo)
{
GC.SuppressFinalize(this);
_processInfo = processInfo;
_machineName = machineName;
_isRemoteMachine = isRemoteMachine;
_processId = processId;
_haveProcessId = true;
_outputStreamReadMode = StreamReadMode.Undefined;
_errorStreamReadMode = StreamReadMode.Undefined;
}
public SafeProcessHandle SafeHandle
{
get
{
EnsureState(State.Associated);
return OpenProcessHandle();
}
}
public IntPtr Handle => SafeHandle.DangerousGetHandle();
/// <devdoc>
/// Returns whether this process component is associated with a real process.
/// </devdoc>
/// <internalonly/>
bool Associated
{
get { return _haveProcessId || _haveProcessHandle; }
}
/// <devdoc>
/// <para>
/// Gets the base priority of
/// the associated process.
/// </para>
/// </devdoc>
public int BasePriority
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.BasePriority;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the
/// value that was specified by the associated process when it was terminated.
/// </para>
/// </devdoc>
public int ExitCode
{
get
{
EnsureState(State.Exited);
return _exitCode;
}
}
/// <devdoc>
/// <para>
/// Gets a
/// value indicating whether the associated process has been terminated.
/// </para>
/// </devdoc>
public bool HasExited
{
get
{
if (!_exited)
{
EnsureState(State.Associated);
UpdateHasExited();
if (_exited)
{
RaiseOnExited();
}
}
return _exited;
}
}
/// <summary>Gets the time the associated process was started.</summary>
public DateTime StartTime
{
get
{
if (!_startTime.HasValue)
{
_startTime = StartTimeCore;
}
return _startTime.Value;
}
}
/// <devdoc>
/// <para>
/// Gets the time that the associated process exited.
/// </para>
/// </devdoc>
public DateTime ExitTime
{
get
{
if (!_haveExitTime)
{
EnsureState(State.Exited);
_exitTime = ExitTimeCore;
_haveExitTime = true;
}
return _exitTime;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the unique identifier for the associated process.
/// </para>
/// </devdoc>
public int Id
{
get
{
EnsureState(State.HaveId);
return _processId;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the name of the computer on which the associated process is running.
/// </para>
/// </devdoc>
public string MachineName
{
get
{
EnsureState(State.Associated);
return _machineName;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the maximum allowable working set for the associated
/// process.
/// </para>
/// </devdoc>
public IntPtr MaxWorkingSet
{
get
{
EnsureWorkingSetLimits();
return _maxWorkingSet;
}
set
{
SetWorkingSetLimits(null, value);
}
}
/// <devdoc>
/// <para>
/// Gets or sets the minimum allowable working set for the associated
/// process.
/// </para>
/// </devdoc>
public IntPtr MinWorkingSet
{
get
{
EnsureWorkingSetLimits();
return _minWorkingSet;
}
set
{
SetWorkingSetLimits(value, null);
}
}
public ProcessModuleCollection Modules
{
get
{
if (_modules == null)
{
EnsureState(State.HaveNonExitedId | State.IsLocal);
_modules = ProcessManager.GetModules(_processId);
}
return _modules;
}
}
public long NonpagedSystemMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PoolNonPagedBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.NonpagedSystemMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int NonpagedSystemMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PoolNonPagedBytes);
}
}
public long PagedMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PageFileBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PagedMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PageFileBytes);
}
}
public long PagedSystemMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PoolPagedBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedSystemMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PagedSystemMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PoolPagedBytes);
}
}
public long PeakPagedMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PageFileBytesPeak;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakPagedMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PeakPagedMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PageFileBytesPeak);
}
}
public long PeakWorkingSet64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.WorkingSetPeak;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakWorkingSet64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PeakWorkingSet
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.WorkingSetPeak);
}
}
public long PeakVirtualMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.VirtualBytesPeak;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakVirtualMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PeakVirtualMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.VirtualBytesPeak);
}
}
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether the associated process priority
/// should be temporarily boosted by the operating system when the main window
/// has focus.
/// </para>
/// </devdoc>
public bool PriorityBoostEnabled
{
get
{
if (!_havePriorityBoostEnabled)
{
_priorityBoostEnabled = PriorityBoostEnabledCore;
_havePriorityBoostEnabled = true;
}
return _priorityBoostEnabled;
}
set
{
PriorityBoostEnabledCore = value;
_priorityBoostEnabled = value;
_havePriorityBoostEnabled = true;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the overall priority category for the
/// associated process.
/// </para>
/// </devdoc>
public ProcessPriorityClass PriorityClass
{
get
{
if (!_havePriorityClass)
{
_priorityClass = PriorityClassCore;
_havePriorityClass = true;
}
return _priorityClass;
}
set
{
if (!Enum.IsDefined(typeof(ProcessPriorityClass), value))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ProcessPriorityClass));
}
PriorityClassCore = value;
_priorityClass = value;
_havePriorityClass = true;
}
}
public long PrivateMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PrivateBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PrivateMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PrivateMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PrivateBytes);
}
}
/// <devdoc>
/// <para>
/// Gets
/// the friendly name of the process.
/// </para>
/// </devdoc>
public string ProcessName
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.ProcessName;
}
}
/// <devdoc>
/// <para>
/// Gets
/// or sets which processors the threads in this process can be scheduled to run on.
/// </para>
/// </devdoc>
public IntPtr ProcessorAffinity
{
get
{
if (!_haveProcessorAffinity)
{
_processorAffinity = ProcessorAffinityCore;
_haveProcessorAffinity = true;
}
return _processorAffinity;
}
set
{
ProcessorAffinityCore = value;
_processorAffinity = value;
_haveProcessorAffinity = true;
}
}
public int SessionId
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.SessionId;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the properties to pass into the <see cref='System.Diagnostics.Process.Start'/> method for the <see cref='System.Diagnostics.Process'/>
/// .
/// </para>
/// </devdoc>
public ProcessStartInfo StartInfo
{
get
{
if (_startInfo == null)
{
if (Associated)
{
throw new InvalidOperationException(SR.CantGetProcessStartInfo);
}
_startInfo = new ProcessStartInfo();
}
return _startInfo;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (Associated)
{
throw new InvalidOperationException(SR.CantSetProcessStartInfo);
}
_startInfo = value;
}
}
/// <devdoc>
/// <para>
/// Gets the set of threads that are running in the associated
/// process.
/// </para>
/// </devdoc>
public ProcessThreadCollection Threads
{
get
{
if (_threads == null)
{
EnsureState(State.HaveProcessInfo);
int count = _processInfo._threadInfoList.Count;
ProcessThread[] newThreadsArray = new ProcessThread[count];
for (int i = 0; i < count; i++)
{
newThreadsArray[i] = new ProcessThread(_isRemoteMachine, _processId, (ThreadInfo)_processInfo._threadInfoList[i]);
}
ProcessThreadCollection newThreads = new ProcessThreadCollection(newThreadsArray);
_threads = newThreads;
}
return _threads;
}
}
public int HandleCount
{
get
{
EnsureState(State.HaveProcessInfo);
EnsureHandleCountPopulated();
return _processInfo.HandleCount;
}
}
partial void EnsureHandleCountPopulated();
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.VirtualMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public long VirtualMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.VirtualBytes;
}
}
public int VirtualMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.VirtualBytes);
}
}
/// <devdoc>
/// <para>
/// Gets or sets whether the <see cref='System.Diagnostics.Process.Exited'/>
/// event is fired
/// when the process terminates.
/// </para>
/// </devdoc>
public bool EnableRaisingEvents
{
get
{
return _watchForExit;
}
set
{
if (value != _watchForExit)
{
if (Associated)
{
if (value)
{
OpenProcessHandle();
EnsureWatchingForExit();
}
else
{
StopWatchingForExit();
}
}
_watchForExit = value;
}
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public StreamWriter StandardInput
{
get
{
if (_standardInput == null)
{
throw new InvalidOperationException(SR.CantGetStandardIn);
}
_standardInputAccessed = true;
return _standardInput;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public StreamReader StandardOutput
{
get
{
if (_standardOutput == null)
{
throw new InvalidOperationException(SR.CantGetStandardOut);
}
if (_outputStreamReadMode == StreamReadMode.Undefined)
{
_outputStreamReadMode = StreamReadMode.SyncMode;
}
else if (_outputStreamReadMode != StreamReadMode.SyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
return _standardOutput;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public StreamReader StandardError
{
get
{
if (_standardError == null)
{
throw new InvalidOperationException(SR.CantGetStandardError);
}
if (_errorStreamReadMode == StreamReadMode.Undefined)
{
_errorStreamReadMode = StreamReadMode.SyncMode;
}
else if (_errorStreamReadMode != StreamReadMode.SyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
return _standardError;
}
}
public long WorkingSet64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.WorkingSet;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.WorkingSet64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int WorkingSet
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.WorkingSet);
}
}
public event EventHandler Exited
{
add
{
_onExited += value;
}
remove
{
_onExited -= value;
}
}
/// <devdoc>
/// This is called from the threadpool when a process exits.
/// </devdoc>
/// <internalonly/>
private void CompletionCallback(object waitHandleContext, bool wasSignaled)
{
Debug.Assert(waitHandleContext != null, "Process.CompletionCallback called with no waitHandleContext");
lock (this)
{
// Check the exited event that we get from the threadpool
// matches the event we are waiting for.
if (waitHandleContext != _waitHandle)
{
return;
}
StopWatchingForExit();
RaiseOnExited();
}
}
/// <internalonly/>
/// <devdoc>
/// <para>
/// Free any resources associated with this component.
/// </para>
/// </devdoc>
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
//Dispose managed and unmanaged resources
Close();
}
_disposed = true;
}
}
public bool CloseMainWindow()
{
return CloseMainWindowCore();
}
public bool WaitForInputIdle()
{
return WaitForInputIdle(int.MaxValue);
}
public bool WaitForInputIdle(int milliseconds)
{
return WaitForInputIdleCore(milliseconds);
}
public ISynchronizeInvoke SynchronizingObject { get; set; }
/// <devdoc>
/// <para>
/// Frees any resources associated with this component.
/// </para>
/// </devdoc>
public void Close()
{
if (Associated)
{
if (_haveProcessHandle)
{
// We need to lock to ensure we don't run concurrently with CompletionCallback.
// Without this lock we could reset _raisedOnExited which causes CompletionCallback to
// raise the Exited event a second time for the same process.
lock (this)
{
// This sets _waitHandle to null which causes CompletionCallback to not emit events.
StopWatchingForExit();
}
_processHandle.Dispose();
_processHandle = null;
_haveProcessHandle = false;
}
_haveProcessId = false;
_isRemoteMachine = false;
_machineName = ".";
_raisedOnExited = false;
// Only call close on the streams if the user cannot have a reference on them.
// If they are referenced it is the user's responsibility to dispose of them.
try
{
if (_standardOutput != null && (_outputStreamReadMode == StreamReadMode.AsyncMode || _outputStreamReadMode == StreamReadMode.Undefined))
{
if (_outputStreamReadMode == StreamReadMode.AsyncMode)
{
_output.CancelOperation();
}
_standardOutput.Close();
}
if (_standardError != null && (_errorStreamReadMode == StreamReadMode.AsyncMode || _errorStreamReadMode == StreamReadMode.Undefined))
{
if (_errorStreamReadMode == StreamReadMode.AsyncMode)
{
_error.CancelOperation();
}
_standardError.Close();
}
if (_standardInput != null && !_standardInputAccessed)
{
_standardInput.Close();
}
}
finally
{
_standardOutput = null;
_standardInput = null;
_standardError = null;
_output = null;
_error = null;
CloseCore();
Refresh();
}
}
}
// Checks if the process hasn't exited on Unix systems.
// This is used to detect recycled child PIDs.
partial void ThrowIfExited(bool refresh);
/// <devdoc>
/// Helper method for checking preconditions when accessing properties.
/// </devdoc>
/// <internalonly/>
private void EnsureState(State state)
{
if ((state & State.Associated) != (State)0)
if (!Associated)
throw new InvalidOperationException(SR.NoAssociatedProcess);
if ((state & State.HaveId) != (State)0)
{
if (!_haveProcessId)
{
if (_haveProcessHandle)
{
SetProcessId(ProcessManager.GetProcessIdFromHandle(_processHandle));
}
else
{
EnsureState(State.Associated);
throw new InvalidOperationException(SR.ProcessIdRequired);
}
}
if ((state & State.HaveNonExitedId) == State.HaveNonExitedId)
{
ThrowIfExited(refresh: false);
}
}
if ((state & State.IsLocal) != (State)0 && _isRemoteMachine)
{
throw new NotSupportedException(SR.NotSupportedRemote);
}
if ((state & State.HaveProcessInfo) != (State)0)
{
if (_processInfo == null)
{
if ((state & State.HaveNonExitedId) != State.HaveNonExitedId)
{
EnsureState(State.HaveNonExitedId);
}
_processInfo = ProcessManager.GetProcessInfo(_processId, _machineName);
if (_processInfo == null)
{
throw new InvalidOperationException(SR.NoProcessInfo);
}
}
}
if ((state & State.Exited) != (State)0)
{
if (!HasExited)
{
throw new InvalidOperationException(SR.WaitTillExit);
}
if (!_haveProcessHandle)
{
throw new InvalidOperationException(SR.NoProcessHandle);
}
}
}
/// <devdoc>
/// Make sure we have obtained the min and max working set limits.
/// </devdoc>
/// <internalonly/>
private void EnsureWorkingSetLimits()
{
if (!_haveWorkingSetLimits)
{
GetWorkingSetLimits(out _minWorkingSet, out _maxWorkingSet);
_haveWorkingSetLimits = true;
}
}
/// <devdoc>
/// Helper to set minimum or maximum working set limits.
/// </devdoc>
/// <internalonly/>
private void SetWorkingSetLimits(IntPtr? min, IntPtr? max)
{
SetWorkingSetLimitsCore(min, max, out _minWorkingSet, out _maxWorkingSet);
_haveWorkingSetLimits = true;
}
/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/> component given a process identifier and
/// the name of a computer in the network.
/// </para>
/// </devdoc>
public static Process GetProcessById(int processId, string machineName)
{
if (!ProcessManager.IsProcessRunning(processId, machineName))
{
throw new ArgumentException(SR.Format(SR.MissingProccess, processId.ToString(CultureInfo.CurrentCulture)));
}
return new Process(machineName, ProcessManager.IsRemoteMachine(machineName), processId, null);
}
/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/> component given the
/// identifier of a process on the local computer.
/// </para>
/// </devdoc>
public static Process GetProcessById(int processId)
{
return GetProcessById(processId, ".");
}
/// <devdoc>
/// <para>
/// Creates an array of <see cref='System.Diagnostics.Process'/> components that are
/// associated
/// with process resources on the
/// local computer. These process resources share the specified process name.
/// </para>
/// </devdoc>
public static Process[] GetProcessesByName(string processName)
{
return GetProcessesByName(processName, ".");
}
/// <devdoc>
/// <para>
/// Creates a new <see cref='System.Diagnostics.Process'/>
/// component for each process resource on the local computer.
/// </para>
/// </devdoc>
public static Process[] GetProcesses()
{
return GetProcesses(".");
}
/// <devdoc>
/// <para>
/// Creates a new <see cref='System.Diagnostics.Process'/>
/// component for each
/// process resource on the specified computer.
/// </para>
/// </devdoc>
public static Process[] GetProcesses(string machineName)
{
bool isRemoteMachine = ProcessManager.IsRemoteMachine(machineName);
ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName);
Process[] processes = new Process[processInfos.Length];
for (int i = 0; i < processInfos.Length; i++)
{
ProcessInfo processInfo = processInfos[i];
processes[i] = new Process(machineName, isRemoteMachine, processInfo.ProcessId, processInfo);
}
return processes;
}
/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/>
/// component and associates it with the current active process.
/// </para>
/// </devdoc>
public static Process GetCurrentProcess()
{
return new Process(".", false, GetCurrentProcessId(), null);
}
/// <devdoc>
/// <para>
/// Raises the <see cref='System.Diagnostics.Process.Exited'/> event.
/// </para>
/// </devdoc>
protected void OnExited()
{
EventHandler exited = _onExited;
if (exited != null)
{
exited(this, EventArgs.Empty);
}
}
/// <devdoc>
/// Raise the Exited event, but make sure we don't do it more than once.
/// </devdoc>
/// <internalonly/>
private void RaiseOnExited()
{
if (!_raisedOnExited)
{
lock (this)
{
if (!_raisedOnExited)
{
_raisedOnExited = true;
OnExited();
}
}
}
}
/// <devdoc>
/// <para>
/// Discards any information about the associated process
/// that has been cached inside the process component. After <see cref='System.Diagnostics.Process.Refresh'/> is called, the
/// first request for information for each property causes the process component
/// to obtain a new value from the associated process.
/// </para>
/// </devdoc>
public void Refresh()
{
_processInfo = null;
_threads = null;
_modules = null;
_exited = false;
_haveWorkingSetLimits = false;
_haveProcessorAffinity = false;
_havePriorityClass = false;
_haveExitTime = false;
_havePriorityBoostEnabled = false;
RefreshCore();
}
/// <summary>
/// Opens a long-term handle to the process, with all access. If a handle exists,
/// then it is reused. If the process has exited, it throws an exception.
/// </summary>
private SafeProcessHandle OpenProcessHandle()
{
if (!_haveProcessHandle)
{
//Cannot open a new process handle if the object has been disposed, since finalization has been suppressed.
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
SetProcessHandle(GetProcessHandle());
}
return _processHandle;
}
/// <devdoc>
/// Helper to associate a process handle with this component.
/// </devdoc>
/// <internalonly/>
private void SetProcessHandle(SafeProcessHandle processHandle)
{
_processHandle = processHandle;
_haveProcessHandle = true;
if (_watchForExit)
{
EnsureWatchingForExit();
}
}
/// <devdoc>
/// Helper to associate a process id with this component.
/// </devdoc>
/// <internalonly/>
private void SetProcessId(int processId)
{
_processId = processId;
_haveProcessId = true;
ConfigureAfterProcessIdSet();
}
/// <summary>Additional optional configuration hook after a process ID is set.</summary>
partial void ConfigureAfterProcessIdSet();
/// <devdoc>
/// <para>
/// Starts a process specified by the <see cref='System.Diagnostics.Process.StartInfo'/> property of this <see cref='System.Diagnostics.Process'/>
/// component and associates it with the
/// <see cref='System.Diagnostics.Process'/> . If a process resource is reused
/// rather than started, the reused process is associated with this <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public bool Start()
{
Close();
ProcessStartInfo startInfo = StartInfo;
if (startInfo.FileName.Length == 0)
{
throw new InvalidOperationException(SR.FileNameMissing);
}
if (startInfo.StandardInputEncoding != null && !startInfo.RedirectStandardInput)
{
throw new InvalidOperationException(SR.StandardInputEncodingNotAllowed);
}
if (startInfo.StandardOutputEncoding != null && !startInfo.RedirectStandardOutput)
{
throw new InvalidOperationException(SR.StandardOutputEncodingNotAllowed);
}
if (startInfo.StandardErrorEncoding != null && !startInfo.RedirectStandardError)
{
throw new InvalidOperationException(SR.StandardErrorEncodingNotAllowed);
}
if (!string.IsNullOrEmpty(startInfo.Arguments) && startInfo.ArgumentList.Count > 0)
{
throw new InvalidOperationException(SR.ArgumentAndArgumentListInitialized);
}
//Cannot start a new process and store its handle if the object has been disposed, since finalization has been suppressed.
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return StartCore(startInfo);
}
/// <devdoc>
/// <para>
/// Starts a process resource by specifying the name of a
/// document or application file. Associates the process resource with a new <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public static Process Start(string fileName)
{
return Start(new ProcessStartInfo(fileName));
}
/// <devdoc>
/// <para>
/// Starts a process resource by specifying the name of an
/// application and a set of command line arguments. Associates the process resource
/// with a new <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public static Process Start(string fileName, string arguments)
{
return Start(new ProcessStartInfo(fileName, arguments));
}
/// <devdoc>
/// <para>
/// Starts a process resource specified by the process start
/// information passed in, for example the file name of the process to start.
/// Associates the process resource with a new <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public static Process Start(ProcessStartInfo startInfo)
{
Process process = new Process();
if (startInfo == null)
throw new ArgumentNullException(nameof(startInfo));
process.StartInfo = startInfo;
return process.Start() ?
process :
null;
}
/// <devdoc>
/// Make sure we are not watching for process exit.
/// </devdoc>
/// <internalonly/>
private void StopWatchingForExit()
{
if (_watchingForExit)
{
RegisteredWaitHandle rwh = null;
WaitHandle wh = null;
lock (this)
{
if (_watchingForExit)
{
_watchingForExit = false;
wh = _waitHandle;
_waitHandle = null;
rwh = _registeredWaitHandle;
_registeredWaitHandle = null;
}
}
if (rwh != null)
{
rwh.Unregister(null);
}
if (wh != null)
{
wh.Dispose();
}
}
}
public override string ToString()
{
if (Associated)
{
string processName = ProcessName;
if (processName.Length != 0)
{
return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", base.ToString(), processName);
}
}
return base.ToString();
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to wait
/// indefinitely for the associated process to exit.
/// </para>
/// </devdoc>
public void WaitForExit()
{
WaitForExit(Timeout.Infinite);
}
/// <summary>
/// Instructs the Process component to wait the specified number of milliseconds for
/// the associated process to exit.
/// </summary>
public bool WaitForExit(int milliseconds)
{
bool exited = WaitForExitCore(milliseconds);
if (exited && _watchForExit)
{
RaiseOnExited();
}
return exited;
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to start
/// reading the StandardOutput stream asynchronously. The user can register a callback
/// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached
/// then the remaining information is returned. The user can add an event handler to OutputDataReceived.
/// </para>
/// </devdoc>
public void BeginOutputReadLine()
{
if (_outputStreamReadMode == StreamReadMode.Undefined)
{
_outputStreamReadMode = StreamReadMode.AsyncMode;
}
else if (_outputStreamReadMode != StreamReadMode.AsyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
if (_pendingOutputRead)
throw new InvalidOperationException(SR.PendingAsyncOperation);
_pendingOutputRead = true;
// We can't detect if there's a pending synchronous read, stream also doesn't.
if (_output == null)
{
if (_standardOutput == null)
{
throw new InvalidOperationException(SR.CantGetStandardOut);
}
Stream s = _standardOutput.BaseStream;
_output = new AsyncStreamReader(s, OutputReadNotifyUser, _standardOutput.CurrentEncoding);
}
_output.BeginReadLine();
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to start
/// reading the StandardError stream asynchronously. The user can register a callback
/// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached
/// then the remaining information is returned. The user can add an event handler to ErrorDataReceived.
/// </para>
/// </devdoc>
public void BeginErrorReadLine()
{
if (_errorStreamReadMode == StreamReadMode.Undefined)
{
_errorStreamReadMode = StreamReadMode.AsyncMode;
}
else if (_errorStreamReadMode != StreamReadMode.AsyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
if (_pendingErrorRead)
{
throw new InvalidOperationException(SR.PendingAsyncOperation);
}
_pendingErrorRead = true;
// We can't detect if there's a pending synchronous read, stream also doesn't.
if (_error == null)
{
if (_standardError == null)
{
throw new InvalidOperationException(SR.CantGetStandardError);
}
Stream s = _standardError.BaseStream;
_error = new AsyncStreamReader(s, ErrorReadNotifyUser, _standardError.CurrentEncoding);
}
_error.BeginReadLine();
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation
/// specified by BeginOutputReadLine().
/// </para>
/// </devdoc>
public void CancelOutputRead()
{
if (_output != null)
{
_output.CancelOperation();
}
else
{
throw new InvalidOperationException(SR.NoAsyncOperation);
}
_pendingOutputRead = false;
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation
/// specified by BeginErrorReadLine().
/// </para>
/// </devdoc>
public void CancelErrorRead()
{
if (_error != null)
{
_error.CancelOperation();
}
else
{
throw new InvalidOperationException(SR.NoAsyncOperation);
}
_pendingErrorRead = false;
}
internal void OutputReadNotifyUser(string data)
{
// To avoid race between remove handler and raising the event
DataReceivedEventHandler outputDataReceived = OutputDataReceived;
if (outputDataReceived != null)
{
DataReceivedEventArgs e = new DataReceivedEventArgs(data);
outputDataReceived(this, e); // Call back to user informing data is available
}
}
internal void ErrorReadNotifyUser(string data)
{
// To avoid race between remove handler and raising the event
DataReceivedEventHandler errorDataReceived = ErrorDataReceived;
if (errorDataReceived != null)
{
DataReceivedEventArgs e = new DataReceivedEventArgs(data);
errorDataReceived(this, e); // Call back to user informing data is available.
}
}
private static void AppendArguments(StringBuilder stringBuilder, Collection<string> argumentList)
{
if (argumentList.Count > 0)
{
foreach (string argument in argumentList)
{
PasteArguments.AppendArgument(stringBuilder, argument);
}
}
}
/// <summary>
/// This enum defines the operation mode for redirected process stream.
/// We don't support switching between synchronous mode and asynchronous mode.
/// </summary>
private enum StreamReadMode
{
Undefined,
SyncMode,
AsyncMode
}
/// <summary>A desired internal state.</summary>
private enum State
{
HaveId = 0x1,
IsLocal = 0x2,
HaveNonExitedId = HaveId | 0x4,
HaveProcessInfo = 0x8,
Exited = 0x10,
Associated = 0x20,
}
}
}
| |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System;
using System.Collections.Generic;
using Scientia.HtmlRenderer.Adapters;
using Scientia.HtmlRenderer.Core.Entities;
using Scientia.HtmlRenderer.Core.Parse;
using Scientia.HtmlRenderer.Core.Utils;
namespace Scientia.HtmlRenderer.Core
{
/// <summary>
/// Holds parsed stylesheet css blocks arranged by media and classes.<br/>
/// <seealso cref="CssBlock"/>
/// </summary>
/// <remarks>
/// To learn more about CSS blocks visit CSS spec: http://www.w3.org/TR/CSS21/syndata.html#block
/// </remarks>
public sealed class CssData
{
#region Fields and Consts
/// <summary>
/// used to return empty array
/// </summary>
private static readonly List<CssBlock> EmptyArray = new List<CssBlock>();
/// <summary>
/// dictionary of media type to dictionary of css class name to the cssBlocks collection with all the data.
/// </summary>
private readonly Dictionary<string, Dictionary<string, List<CssBlock>>> _MediaBlocks = new Dictionary<string, Dictionary<string, List<CssBlock>>>(StringComparer.InvariantCultureIgnoreCase);
#endregion
/// <summary>
/// Init.
/// </summary>
internal CssData()
{
this._MediaBlocks.Add("all", new Dictionary<string, List<CssBlock>>(StringComparer.InvariantCultureIgnoreCase));
}
/// <summary>
/// Parse the given stylesheet to <see cref="CssData"/> object.<br/>
/// If <paramref name="combineWithDefault"/> is true the parsed css blocks are added to the
/// default css data (as defined by W3), merged if class name already exists. If false only the data in the given stylesheet is returned.
/// </summary>
/// <seealso cref="http://www.w3.org/TR/CSS21/sample.html"/>
/// <param name="adapter">Platform adapter</param>
/// <param name="stylesheet">the stylesheet source to parse</param>
/// <param name="combineWithDefault">true - combine the parsed css data with default css data, false - return only the parsed css data</param>
/// <returns>the parsed css data</returns>
public static CssData Parse(RAdapter adapter, string stylesheet, bool combineWithDefault = true)
{
CssParser parser = new CssParser(adapter);
return parser.ParseStyleSheet(stylesheet, combineWithDefault);
}
/// <summary>
/// dictionary of media type to dictionary of css class name to the cssBlocks collection with all the data
/// </summary>
internal IDictionary<string, Dictionary<string, List<CssBlock>>> MediaBlocks
{
get { return this._MediaBlocks; }
}
/// <summary>
/// Check if there are css blocks for the given class selector.
/// </summary>
/// <param name="className">the class selector to check for css blocks by</param>
/// <param name="media">optional: the css media type (default - all)</param>
/// <returns>true - has css blocks for the class, false - otherwise</returns>
public bool ContainsCssBlock(string className, string media = "all")
{
Dictionary<string, List<CssBlock>> mid;
return this._MediaBlocks.TryGetValue(media, out mid) && mid.ContainsKey(className);
}
/// <summary>
/// Get collection of css blocks for the requested class selector.<br/>
/// the <paramref name="className"/> can be: class name, html element name, html element and
/// class name (elm.class), hash tag with element id (#id).<br/>
/// returned all the blocks that word on the requested class selector, it can contain simple
/// selector or hierarchy selector.
/// </summary>
/// <param name="className">the class selector to get css blocks by</param>
/// <param name="media">optional: the css media type (default - all)</param>
/// <returns>collection of css blocks, empty collection if no blocks exists (never null)</returns>
public IEnumerable<CssBlock> GetCssBlock(string className, string media = "all")
{
List<CssBlock> block = null;
Dictionary<string, List<CssBlock>> mid;
if (this._MediaBlocks.TryGetValue(media, out mid))
{
mid.TryGetValue(className, out block);
}
return block ?? EmptyArray;
}
/// <summary>
/// Add the given css block to the css data, merging to existing block if required.
/// </summary>
/// <remarks>
/// If there is no css blocks for the same class it will be added to data collection.<br/>
/// If there is already css blocks for the same class it will check for each existing block
/// if the hierarchical selectors match (or not exists). if do the two css blocks will be merged into
/// one where the new block properties overwrite existing if needed. if the new block doesn't mach any
/// existing it will be added either to the beginning of the list if it has no hierarchical selectors or at the end.<br/>
/// Css block without hierarchical selectors must be added to the beginning of the list so more specific block
/// can overwrite it when the style is applied.
/// </remarks>
/// <param name="media">the media type to add the CSS to</param>
/// <param name="cssBlock">the css block to add</param>
public void AddCssBlock(string media, CssBlock cssBlock)
{
Dictionary<string, List<CssBlock>> mid;
if (!this._MediaBlocks.TryGetValue(media, out mid))
{
mid = new Dictionary<string, List<CssBlock>>(StringComparer.InvariantCultureIgnoreCase);
this._MediaBlocks.Add(media, mid);
}
if (!mid.ContainsKey(cssBlock.Class))
{
var list = new List<CssBlock>();
list.Add(cssBlock);
mid[cssBlock.Class] = list;
}
else
{
bool merged = false;
var list = mid[cssBlock.Class];
foreach (var block in list)
{
if (block.EqualsSelector(cssBlock))
{
merged = true;
block.Merge(cssBlock);
break;
}
}
if (!merged)
{
// general block must be first
if (cssBlock.Selectors == null)
list.Insert(0, cssBlock);
else
list.Add(cssBlock);
}
}
}
/// <summary>
/// Combine this CSS data blocks with <paramref name="other"/> CSS blocks for each media.<br/>
/// Merge blocks if exists in both.
/// </summary>
/// <param name="other">the CSS data to combine with</param>
public void Combine(CssData other)
{
ArgChecker.AssertArgNotNull(other, "other");
// for each media block
foreach (var mediaBlock in other.MediaBlocks)
{
// for each css class in the media block
foreach (var bla in mediaBlock.Value)
{
// for each css block of the css class
foreach (var cssBlock in bla.Value)
{
// combine with this
this.AddCssBlock(mediaBlock.Key, cssBlock);
}
}
}
}
/// <summary>
/// Create deep copy of the css data with cloned css blocks.
/// </summary>
/// <returns>cloned object</returns>
public CssData Clone()
{
var clone = new CssData();
foreach (var mid in this._MediaBlocks)
{
var cloneMid = new Dictionary<string, List<CssBlock>>(StringComparer.InvariantCultureIgnoreCase);
foreach (var blocks in mid.Value)
{
var cloneList = new List<CssBlock>();
foreach (var cssBlock in blocks.Value)
{
cloneList.Add(cssBlock.Clone());
}
cloneMid[blocks.Key] = cloneList;
}
clone._MediaBlocks[mid.Key] = cloneMid;
}
return clone;
}
}
}
| |
// Authors: Robert Scheller, Melissa Lucash
using Landis.Utilities;
using Landis.Core;
using Landis.SpatialModeling;
using System.Collections.Generic;
using Landis.Library.LeafBiomassCohorts;
using System;
namespace Landis.Extension.Succession.NECN
{
/// <summary>
/// Calculations for an individual cohort's biomass.
/// </summary>
public class CohortBiomass
: Landis.Library.LeafBiomassCohorts.ICalculator
{
/// <summary>
/// The single instance of the biomass calculations that is used by
/// the plug-in.
/// </summary>
public static CohortBiomass Calculator;
// Ecoregion where the cohort's site is located
private IEcoregion ecoregion;
private double defoliation;
private double defoliatedLeafBiomass;
//---------------------------------------------------------------------
public CohortBiomass()
{
}
//---------------------------------------------------------------------
/// <summary>
/// Computes the change in a cohort's biomass due to Annual Net Primary
/// Productivity (ANPP), age-related mortality (M_AGE), and development-
/// related mortality (M_BIO).
/// </summary>
public float[] ComputeChange(ICohort cohort, ActiveSite site)
{
ecoregion = PlugIn.ModelCore.Ecoregion[site];
// First call to the Calibrate Log:
if (PlugIn.ModelCore.CurrentTime > 0 && OtherData.CalibrateMode)
{
CalibrateLog.year = PlugIn.ModelCore.CurrentTime;
CalibrateLog.month = Main.Month + 1;
CalibrateLog.climateRegionIndex = ecoregion.Index;
CalibrateLog.speciesName = cohort.Species.Name;
CalibrateLog.cohortAge = cohort.Age;
CalibrateLog.cohortWoodB = cohort.WoodBiomass;
CalibrateLog.cohortLeafB = cohort.LeafBiomass;
}
double siteBiomass = Main.ComputeLivingBiomass(SiteVars.Cohorts[site]);
if(siteBiomass < 0)
throw new ApplicationException("Error: Site biomass < 0");
// ****** Mortality *******
// Age-related mortality includes woody and standing leaf biomass.
double[] mortalityAge = ComputeAgeMortality(cohort, site);
// ****** Growth *******
double[] actualANPP = ComputeActualANPP(cohort, site, siteBiomass, mortalityAge);
// Growth-related mortality
double[] mortalityGrowth = ComputeGrowthMortality(cohort, site, siteBiomass, actualANPP);
double[] totalMortality = new double[2]{Math.Min(cohort.WoodBiomass, mortalityAge[0] + mortalityGrowth[0]), Math.Min(cohort.LeafBiomass, mortalityAge[1] + mortalityGrowth[1])};
double nonDisturbanceLeafFall = totalMortality[1];
double scorch = 0.0;
defoliatedLeafBiomass = 0.0;
if (Main.Month == 6) //July = 6
{
if (SiteVars.FireSeverity != null && SiteVars.FireSeverity[site] > 0)
scorch = FireEffects.CrownScorching(cohort, SiteVars.FireSeverity[site]);
if (scorch > 0.0) // NEED TO DOUBLE CHECK WHAT CROWN SCORCHING RETURNS
totalMortality[1] = Math.Min(cohort.LeafBiomass, scorch + totalMortality[1]);
// Defoliation (index) ranges from 1.0 (total) to none (0.0).
if (PlugIn.ModelCore.CurrentTime > 0) //Skip this during initialization
{
//defoliation = Landis.Library.LeafBiomassCohorts.CohortDefoliation.Compute(cohort, site, (int)siteBiomass);
int cohortBiomass = (int)(cohort.LeafBiomass + cohort.WoodBiomass);
defoliation = Landis.Library.Biomass.CohortDefoliation.Compute(site, cohort.Species, cohortBiomass, (int)siteBiomass);
}
if (defoliation > 1.0)
defoliation = 1.0;
if (defoliation > 0.0)
{
defoliatedLeafBiomass = (cohort.LeafBiomass) * defoliation;
if (totalMortality[1] + defoliatedLeafBiomass - cohort.LeafBiomass > 0.001)
defoliatedLeafBiomass = cohort.LeafBiomass - totalMortality[1];
//PlugIn.ModelCore.UI.WriteLine("Defoliation.Month={0:0.0}, LeafBiomass={1:0.00}, DefoliatedLeafBiomass={2:0.00}, TotalLeafMort={2:0.00}", Main.Month, cohort.LeafBiomass, defoliatedLeafBiomass , mortalityAge[1]);
ForestFloor.AddFrassLitter(defoliatedLeafBiomass, cohort.Species, site);
}
}
else
{
defoliation = 0.0;
defoliatedLeafBiomass = 0.0;
}
if (totalMortality[0] <= 0.0 || cohort.WoodBiomass <= 0.0)
totalMortality[0] = 0.0;
if (totalMortality[1] <= 0.0 || cohort.LeafBiomass <= 0.0)
totalMortality[1] = 0.0;
if ((totalMortality[0]) > cohort.WoodBiomass)
{
PlugIn.ModelCore.UI.WriteLine("Warning: WOOD Mortality exceeds cohort wood biomass. M={0:0.0}, B={1:0.0}", (totalMortality[0]), cohort.WoodBiomass);
PlugIn.ModelCore.UI.WriteLine("Warning: If M>B, then list mortality. Mage={0:0.0}, Mgrow={1:0.0},", mortalityAge[0], mortalityGrowth[0]);
throw new ApplicationException("Error: WOOD Mortality exceeds cohort biomass");
}
if ((totalMortality[1] + defoliatedLeafBiomass - cohort.LeafBiomass) > 0.01)
{
PlugIn.ModelCore.UI.WriteLine("Warning: LEAF Mortality exceeds cohort biomass. Mortality={0:0.000}, Leafbiomass={1:0.000}", (totalMortality[1] + defoliatedLeafBiomass), cohort.LeafBiomass);
PlugIn.ModelCore.UI.WriteLine("Warning: If M>B, then list mortality. Mage={0:0.00}, Mgrow={1:0.00}, Mdefo={2:0.000},", mortalityAge[1], mortalityGrowth[1], defoliatedLeafBiomass);
throw new ApplicationException("Error: LEAF Mortality exceeds cohort biomass");
}
float deltaWood = (float)(actualANPP[0] - totalMortality[0]);
float deltaLeaf = (float)(actualANPP[1] - totalMortality[1] - defoliatedLeafBiomass);
float[] deltas = new float[2] { deltaWood, deltaLeaf };
//if((totalMortality[1] + defoliatedLeafBiomass) > cohort.LeafBiomass)
// PlugIn.ModelCore.UI.WriteLine("Warning: Leaf Mortality exceeds cohort leaf biomass. M={0:0.0}, B={1:0.0}, DefoLeafBiomass={2:0.0}, defoliationIndex={3:0.0}", totalMortality[1], cohort.LeafBiomass, defoliatedLeafBiomass, defoliation);
UpdateDeadBiomass(cohort, site, totalMortality);
CalculateNPPcarbon(site, cohort, actualANPP);
AvailableN.AdjustAvailableN(cohort, site, actualANPP);
if (OtherData.CalibrateMode && PlugIn.ModelCore.CurrentTime > 0)
{
CalibrateLog.deltaLeaf = deltaLeaf;
CalibrateLog.deltaWood = deltaWood;
CalibrateLog.WriteLogFile();
}
return deltas;
}
//---------------------------------------------------------------------
private double[] ComputeActualANPP(ICohort cohort,
ActiveSite site,
double siteBiomass,
double[] mortalityAge)
{
double leafFractionNPP = FunctionalType.Table[SpeciesData.FuncType[cohort.Species]].FractionANPPtoLeaf;
//double maxBiomass = SpeciesData.Max_Biomass[cohort.Species];
double sitelai = SiteVars.LAI[site];
double maxNPP = SpeciesData.Max_ANPP[cohort.Species];
double limitT = calculateTemp_Limit(site, cohort.Species);
double limitH20 = calculateWater_Limit(site, ecoregion, cohort.Species);
double limitLAI = calculateLAI_Limit(cohort, site);
// RMS 03/2016: Testing alternative more similar to how Biomass Succession operates: REMOVE FOR NEXT RELEASE
//double limitCapacity = 1.0 - Math.Min(1.0, Math.Exp(siteBiomass / maxBiomass * 5.0) / Math.Exp(5.0));
double competition_limit = calculate_LAI_Competition(cohort, site);
double potentialNPP = maxNPP * limitLAI * limitH20 * limitT * competition_limit;
double limitN = calculateN_Limit(site, cohort, potentialNPP, leafFractionNPP);
potentialNPP *= limitN;
//if (Double.IsNaN(limitT) || Double.IsNaN(limitH20) || Double.IsNaN(limitLAI) || Double.IsNaN(limitCapacity) || Double.IsNaN(limitN))
//{
// PlugIn.ModelCore.UI.WriteLine(" A limit = NaN! Will set to zero.");
// PlugIn.ModelCore.UI.WriteLine(" Yr={0},Mo={1}. GROWTH LIMITS: LAI={2:0.00}, H20={3:0.00}, N={4:0.00}, T={5:0.00}, Capacity={6:0.0}", PlugIn.ModelCore.CurrentTime, month + 1, limitLAI, limitH20, limitN, limitT, limitCapacity);
// PlugIn.ModelCore.UI.WriteLine(" Yr={0},Mo={1}. Other Information: MaxB={2}, Bsite={3}, Bcohort={4:0.0}, SoilT={5:0.0}.", PlugIn.ModelCore.CurrentTime, month + 1, maxBiomass, (int)siteBiomass, (cohort.WoodBiomass + cohort.LeafBiomass), SiteVars.SoilTemperature[site]);
//}
// Age mortality is discounted from ANPP to prevent the over-
// estimation of growth. ANPP cannot be negative.
double actualANPP = Math.Max(0.0, potentialNPP - mortalityAge[0] - mortalityAge[1]);
// Growth can be reduced by another extension via this method.
// To date, no extension has been written to utilize this hook.
double growthReduction = CohortGrowthReduction.Compute(cohort, site);
if (growthReduction > 0.0)
{
actualANPP *= (1.0 - growthReduction);
}
double leafNPP = actualANPP * leafFractionNPP;
double woodNPP = actualANPP * (1.0 - leafFractionNPP);
if (Double.IsNaN(leafNPP) || Double.IsNaN(woodNPP))
{
PlugIn.ModelCore.UI.WriteLine(" EITHER WOOD or LEAF NPP = NaN! Will set to zero.");
PlugIn.ModelCore.UI.WriteLine(" Yr={0},Mo={1}. Other Information: MaxB={2}, Bsite={3}, Bcohort={4:0.0}, SoilT={5:0.0}.", PlugIn.ModelCore.CurrentTime, Main.Month + 1, SpeciesData.Max_Biomass[cohort.Species], (int)siteBiomass, (cohort.WoodBiomass + cohort.LeafBiomass), SiteVars.SoilTemperature[site]);
PlugIn.ModelCore.UI.WriteLine(" Yr={0},Mo={1}. WoodNPP={2:0.00}, LeafNPP={3:0.00}.", PlugIn.ModelCore.CurrentTime, Main.Month + 1, woodNPP, leafNPP);
if (Double.IsNaN(leafNPP))
leafNPP = 0.0;
if (Double.IsNaN(woodNPP))
woodNPP = 0.0;
}
if (PlugIn.ModelCore.CurrentTime > 0 && OtherData.CalibrateMode)
{
CalibrateLog.limitLAI = limitLAI;
CalibrateLog.limitH20 = limitH20;
CalibrateLog.limitT = limitT;
CalibrateLog.limitN = limitN;
CalibrateLog.limitLAIcompetition = competition_limit; // Chihiro, 2021.03.26: added
CalibrateLog.maxNPP = maxNPP;
CalibrateLog.maxB = SpeciesData.Max_Biomass[cohort.Species];
CalibrateLog.siteB = siteBiomass;
CalibrateLog.cohortB = (cohort.WoodBiomass + cohort.LeafBiomass);
CalibrateLog.soilTemp = SiteVars.SoilTemperature[site];
CalibrateLog.actualWoodNPP = woodNPP;
CalibrateLog.actualLeafNPP = leafNPP;
}
return new double[2]{woodNPP, leafNPP};
}
//---------------------------------------------------------------------
/// <summary>
/// Computes M_AGE_ij: the mortality caused by the aging of the cohort.
/// See equation 6 in Scheller and Mladenoff, 2004.
/// </summary>
private double[] ComputeAgeMortality(ICohort cohort, ActiveSite site)
{
double monthAdjust = 1.0 / 12.0;
double totalBiomass = (double) (cohort.WoodBiomass + cohort.LeafBiomass);
double max_age = (double) cohort.Species.Longevity;
double d = FunctionalType.Table[SpeciesData.FuncType[cohort.Species]].LongevityMortalityShape;
double M_AGE_wood = cohort.WoodBiomass * monthAdjust *
Math.Exp((double) cohort.Age / max_age * d) / Math.Exp(d);
double M_AGE_leaf = cohort.LeafBiomass * monthAdjust *
Math.Exp((double) cohort.Age / max_age * d) / Math.Exp(d);
M_AGE_wood = Math.Min(M_AGE_wood, cohort.WoodBiomass);
M_AGE_leaf = Math.Min(M_AGE_leaf, cohort.LeafBiomass);
double[] M_AGE = new double[2]{M_AGE_wood, M_AGE_leaf};
SiteVars.WoodMortality[site] += (M_AGE_wood);
if(M_AGE_wood < 0.0 || M_AGE_leaf < 0.0)
{
PlugIn.ModelCore.UI.WriteLine("Mwood={0}, Mleaf={1}.", M_AGE_wood, M_AGE_leaf);
throw new ApplicationException("Error: Woody or Leaf Age Mortality is < 0");
}
if (PlugIn.ModelCore.CurrentTime > 0 && OtherData.CalibrateMode)
{
CalibrateLog.mortalityAGEleaf = M_AGE_leaf;
CalibrateLog.mortalityAGEwood = M_AGE_wood;
}
return M_AGE;
}
//---------------------------------------------------------------------
/// <summary>
/// Monthly mortality as a function of standing leaf and wood biomass.
/// </summary>
private double[] ComputeGrowthMortality(ICohort cohort, ActiveSite site, double siteBiomass, double[] AGNPP)
{
double maxBiomass = SpeciesData.Max_Biomass[cohort.Species];
double NPPwood = (double)AGNPP[0];
double M_wood_fixed = cohort.WoodBiomass * FunctionalType.Table[SpeciesData.FuncType[cohort.Species]].MonthlyWoodMortality;
double M_leaf = 0.0;
double relativeBiomass = siteBiomass / maxBiomass;
double M_constant = 5.0; //This constant controls the rate of change of mortality with NPP
//Functon which calculates an adjustment factor for mortality that ranges from 0 to 1 and exponentially increases with relative biomass.
double M_wood_NPP = Math.Max(0.0, (Math.Exp(M_constant * relativeBiomass) - 1.0) / (Math.Exp(M_constant) - 1.0));
M_wood_NPP = Math.Min(M_wood_NPP, 1.0);
//PlugIn.ModelCore.UI.WriteLine("relativeBiomass={0}, siteBiomass={1}.", relativeBiomass, siteBiomass);
//This function calculates mortality as a function of NPP
double M_wood = (NPPwood * M_wood_NPP) + M_wood_fixed;
//PlugIn.ModelCore.UI.WriteLine("Mwood={0}, M_wood_relative={1}, NPPwood={2}, Spp={3}, Age={4}.", M_wood, M_wood_NPP, NPPwood, cohort.Species.Name, cohort.Age);
// Leaves and Needles dropped.
if (SpeciesData.LeafLongevity[cohort.Species] > 1.0)
{
M_leaf = cohort.LeafBiomass / (double) SpeciesData.LeafLongevity[cohort.Species] / 12.0; //Needle deposit spread across the year.
}
else
{
if(Main.Month +1 == FunctionalType.Table[SpeciesData.FuncType[cohort.Species]].FoliageDropMonth)
{
M_leaf = cohort.LeafBiomass / 2.0; //spread across 2 months
}
if (Main.Month +2 > FunctionalType.Table[SpeciesData.FuncType[cohort.Species]].FoliageDropMonth)
{
M_leaf = cohort.LeafBiomass; //drop the remainder
}
}
double[] M_BIO = new double[2]{M_wood, M_leaf};
if(M_wood < 0.0 || M_leaf < 0.0)
{
PlugIn.ModelCore.UI.WriteLine("Mwood={0}, Mleaf={1}.", M_wood, M_leaf);
throw new ApplicationException("Error: Wood or Leaf Growth Mortality is < 0");
}
if (PlugIn.ModelCore.CurrentTime > 0 && OtherData.CalibrateMode)
{
CalibrateLog.mortalityBIOwood = M_wood;
CalibrateLog.mortalityBIOleaf = M_leaf;
}
SiteVars.WoodMortality[site] += (M_wood);
return M_BIO;
}
//---------------------------------------------------------------------
private void UpdateDeadBiomass(ICohort cohort, ActiveSite site, double[] totalMortality)
{
double mortality_wood = (double) totalMortality[0];
double mortality_nonwood = (double)totalMortality[1];
// Add mortality to dead biomass pools.
// Coarse root mortality is assumed proportional to aboveground woody mortality
// mass is assumed 25% of aboveground wood (White et al. 2000, Niklas & Enquist 2002)
if(mortality_wood > 0.0 && !SpeciesData.Grass[cohort.Species])
{
ForestFloor.AddWoodLitter(mortality_wood, cohort.Species, site);
Roots.AddCoarseRootLitter(mortality_wood, cohort, cohort.Species, site);
}
// Wood biomass of grass species is transfered to non wood litter. (W.Hotta 2021.12.16)
if (mortality_wood > 0.0 && SpeciesData.Grass[cohort.Species])
{
AvailableN.AddResorbedN(cohort, totalMortality[0], site); //ignoring input from scorching, which is rare, but not resorbed.
ForestFloor.AddResorbedFoliageLitter(mortality_wood, cohort.Species, site);
Roots.AddFineRootLitter(mortality_wood, cohort, cohort.Species, site);
}
if (mortality_nonwood > 0.0)
{
AvailableN.AddResorbedN(cohort, totalMortality[1], site); //ignoring input from scorching, which is rare, but not resorbed.
ForestFloor.AddResorbedFoliageLitter(mortality_nonwood, cohort.Species, site);
Roots.AddFineRootLitter(mortality_nonwood, cohort, cohort.Species, site);
}
return;
}
//---------------------------------------------------------------------
/// <summary>
/// Computes the initial biomass for a cohort at a site.
/// </summary>
public static float[] InitialBiomass(ISpecies species, ISiteCohorts siteCohorts,
ActiveSite site)
{
IEcoregion ecoregion = PlugIn.ModelCore.Ecoregion[site];
double leafFrac = FunctionalType.Table[SpeciesData.FuncType[species]].FractionANPPtoLeaf;
double B_ACT = SiteVars.ActualSiteBiomass(site);
double B_MAX = SpeciesData.Max_Biomass[species];
// Initial biomass exponentially declines in response to
// competition.
double initialBiomass = 0.002 * B_MAX * Math.Exp(-1.6 * B_ACT / B_MAX);
initialBiomass = Math.Max(initialBiomass, 5.0);
double initialLeafB = initialBiomass * leafFrac;
double initialWoodB = initialBiomass - initialLeafB;
double[] initialB = new double[2] { initialWoodB, initialLeafB };
float[] initialWoodLeafBiomass = new float[2] { (float)initialB[0], (float)initialB[1] };
return initialWoodLeafBiomass;
}
//---------------------------------------------------------------------
/// <summary>
/// Summarize NPP
/// </summary>
private static void CalculateNPPcarbon(ActiveSite site, ICohort cohort, double[] AGNPP)
{
double NPPwood = (double) AGNPP[0] * 0.47;
double NPPleaf = (double) AGNPP[1] * 0.47;
double NPPcoarseRoot = Roots.CalculateCoarseRoot(cohort, NPPwood);
double NPPfineRoot = Roots.CalculateFineRoot(cohort, NPPleaf);
if (Double.IsNaN(NPPwood) || Double.IsNaN(NPPleaf) || Double.IsNaN(NPPcoarseRoot) || Double.IsNaN(NPPfineRoot))
{
PlugIn.ModelCore.UI.WriteLine(" EITHER WOOD or LEAF NPP or COARSE ROOT or FINE ROOT = NaN! Will set to zero.");
PlugIn.ModelCore.UI.WriteLine(" Yr={0},Mo={1}. WoodNPP={0}, LeafNPP={1}, CRootNPP={2}, FRootNPP={3}.", NPPwood, NPPleaf, NPPcoarseRoot, NPPfineRoot);
if (Double.IsNaN(NPPleaf))
NPPleaf = 0.0;
if (Double.IsNaN(NPPwood))
NPPwood = 0.0;
if (Double.IsNaN(NPPcoarseRoot))
NPPcoarseRoot = 0.0;
if (Double.IsNaN(NPPfineRoot))
NPPfineRoot = 0.0;
}
SiteVars.AGNPPcarbon[site] += NPPwood + NPPleaf;
SiteVars.BGNPPcarbon[site] += NPPcoarseRoot + NPPfineRoot;
SiteVars.MonthlyAGNPPcarbon[site][Main.Month] += NPPwood + NPPleaf;
SiteVars.MonthlyBGNPPcarbon[site][Main.Month] += NPPcoarseRoot + NPPfineRoot;
SiteVars.MonthlySoilResp[site][Main.Month] += (NPPcoarseRoot + NPPfineRoot) * 0.53/0.47;
}
//--------------------------------------------------------------------------
//N limit is actual demand divided by maximum uptake.
private double calculateN_Limit(ActiveSite site, ICohort cohort, double NPP, double leafFractionNPP)
{
//Get Cohort Mineral and Resorbed N allocation.
double mineralNallocation = AvailableN.GetMineralNallocation(cohort);
double resorbedNallocation = AvailableN.GetResorbedNallocation(cohort, site);
double LeafNPP = (NPP * leafFractionNPP);
double WoodNPP = NPP * (1.0 - leafFractionNPP);
double limitN = 0.0;
if (SpeciesData.NFixer[cohort.Species])
limitN = 1.0; // No limit for N-fixing shrubs
else
{
// Divide allocation N by N demand here:
//PlugIn.ModelCore.UI.WriteLine(" WoodNPP={0:0.00}, LeafNPP={1:0.00}, FineRootNPP={2:0.00}, CoarseRootNPP={3:0.00}.", WoodNPP, LeafNPP);
double Ndemand = (AvailableN.CalculateCohortNDemand(cohort.Species, site, cohort, new double[] { WoodNPP, LeafNPP}));
if (Ndemand > 0.0)
{
limitN = Math.Min(1.0, (mineralNallocation + resorbedNallocation) / Ndemand);
//PlugIn.ModelCore.UI.WriteLine("mineralN={0}, resorbedN={1}, Ndemand={2}", mineralNallocation, resorbedNallocation, Ndemand);
}
else
limitN = 1.0; // No demand means that it is a new or very small cohort. Will allow it to grow anyways.
}
if (PlugIn.ModelCore.CurrentTime > 0 && OtherData.CalibrateMode)
{
CalibrateLog.mineralNalloc = mineralNallocation;
CalibrateLog.resorbedNalloc = resorbedNallocation;
}
return Math.Max(limitN, 0.0);
}
//--------------------------------------------------------------------------
// Originally from lacalc.f of CENTURY model
private static double calculateLAI_Limit(ICohort cohort, ActiveSite site)
{
//...Calculate true LAI using leaf biomass and a biomass-to-LAI
// conversion parameter which is the slope of a regression
// line derived from LAI vs Foliar Mass for Slash Pine.
//...Calculate theoretical LAI as a function of large wood mass.
// There is no strong consensus on the true nature of the relationship
// between LAI and stemwood mass. Many sutdies have cited as "general"
// an increase of LAI up to a maximum, then a decrease to a plateau value
// (e.g. Switzer et al. 1968, Gholz and Fisher 1982). However, this
// response is not general, and seems to mostly be a feature of young
// pine plantations. Northern hardwoods have shown a monotonic increase
// to a plateau (e.g. Switzer et al. 1968). Pacific Northwest conifers
// have shown a steady increase in LAI with no plateau evident (e.g.
// Gholz 1982). In this version, we use a simple saturation fucntion in
// which LAI increases linearly against large wood mass initially, then
// approaches a plateau value. The plateau value can be set very large to
// give a response of steadily increasing LAI with stemwood.
// References:
// 1) Switzer, G.L., L.E. Nelson and W.H. Smith 1968.
// The mineral cycle in forest stands. 'Forest
// Fertilization: Theory and Practice'. pp 1-9
// Tenn. Valley Auth., Muscle Shoals, AL.
//
// 2) Gholz, H.L., and F.R. Fisher 1982. Organic matter
// production and distribution in slash pine (Pinus
// elliotii) plantations. Ecology 63(6): 1827-1839.
//
// 3) Gholz, H.L. 1982. Environmental limits on aboveground
// net primary production and biomass in vegetation zones of
// the Pacific Northwest. Ecology 63:469-481.
//...Local variables
double leafC = (double) cohort.LeafBiomass * 0.47;
double woodC = (double) cohort.WoodBiomass * 0.47;
double lai = 0.0;
double lai_to_growth = SpeciesData.GrowthLAI[cohort.Species] * -1.0;
double btolai = FunctionalType.Table[SpeciesData.FuncType[cohort.Species]].BiomassToLAI;
double klai = FunctionalType.Table[SpeciesData.FuncType[cohort.Species]].KLAI;
double maxlai = FunctionalType.Table[SpeciesData.FuncType[cohort.Species]].MaxLAI;
double minlai = FunctionalType.Table[SpeciesData.FuncType[cohort.Species]].MinLAI;
double monthly_cumulative_LAI = SiteVars.MonthlyLAI[site][Main.Month];
// adjust for leaf on/off
double seasonal_adjustment = 1.0;
if (SpeciesData.LeafLongevity[cohort.Species] <= 1.0)
{
seasonal_adjustment = (Math.Max(0.0, 1.0 - Math.Exp(btolai * leafC)));
}
// The cohort LAI given wood Carbon
double base_lai = maxlai * woodC/(klai + woodC);
//...Choose the LAI reducer on production.
lai = base_lai * seasonal_adjustment;
// This will allow us to set MAXLAI to zero such that LAI is completely dependent upon
// foliar carbon, which may be necessary for simulating defoliation events.
if(base_lai <= 0.0) lai = seasonal_adjustment;
// The minimum LAI to calculate effect is 0.1.
if (lai < minlai) lai = minlai;
double LAI_Growth_limit = Math.Max(0.0, 1.0 - Math.Exp(lai_to_growth * lai));
//This allows LAI to go to zero for deciduous trees.
if (SpeciesData.LeafLongevity[cohort.Species] <= 1.0 &&
(Main.Month > FunctionalType.Table[SpeciesData.FuncType[cohort.Species]].FoliageDropMonth || Main.Month < 3))
{
lai = 0.0;
LAI_Growth_limit = 0.0;
}
if (Main.Month == 6)
SiteVars.LAI[site] += lai; //Tracking LAI.
SiteVars.MonthlyLAI[site][Main.Month] += lai;
// Chihiro 2021.02.23
// Tracking Tree species LAI above grasses
if (!SpeciesData.Grass[cohort.Species])
SiteVars.MonthlyLAI_Trees[site][Main.Month] += lai;
else
SiteVars.MonthlyLAI_Grasses[site][Main.Month] += lai; // Chihiro, 2021.03.30: tentative
if (PlugIn.ModelCore.CurrentTime > 0 && OtherData.CalibrateMode)
{
CalibrateLog.actual_LAI = lai;
if (!SpeciesData.Grass[cohort.Species])
CalibrateLog.actual_LAI_tree = lai;
else
CalibrateLog.actual_LAI_tree = 0;
CalibrateLog.base_lai = base_lai;
CalibrateLog.seasonal_adjustment = seasonal_adjustment;
CalibrateLog.siteLAI = SiteVars.MonthlyLAI[site][Main.Month]; // Chihiro, 2021.03.26: added
}
return LAI_Growth_limit;
}
private static double calculate_LAI_Competition(ICohort cohort, ActiveSite site)
{
double k = -0.14;
// This is the value given for all temperature ecosystems.
// The model is relatively insensitive to this parameter ZR 06/01/2021
// Chihiro 2020.01.22
// Competition between cohorts considering understory and overstory interactions
// If the biomass of tree cohort is larger than total grass biomass on the site,
// monthly_cummulative_LAI should ignore grass LAI.
//
// Added GrassThresholdMultiplier (W.Hotta 2020.07.07)
// grassThresholdMultiplier: User defined parameter to adjust relationships between AGB and Hight of the cohort
// default = 1.0
//
// if (the cohort is tree species) and (biomass_of_tree_cohort > total_grass_biomass_on_the_site * threshold_multiplier):
// monthly_cummulative_LAI = Monthly_LAI_of_tree_species
// else:
// monthly_cummulative_LAI = Monthly_LAI_of_tree_& grass_species
//
double monthly_cumulative_LAI = 0.0;
double grassThresholdMultiplier = PlugIn.Parameters.GrassThresholdMultiplier;
// PlugIn.ModelCore.UI.WriteLine("TreeLAI={0},TreeLAI={0}", SiteVars.MonthlyLAITree[site][Main.Month], SiteVars.MonthlyLAI[site][Main.Month]); // added (W.Hotta 2020.07.07)
// PlugIn.ModelCore.UI.WriteLine("Spp={0},Time={1},Mo={2},cohortBiomass={3},grassBiomass={4},LAI={5}", cohort.Species.Name, PlugIn.ModelCore.CurrentTime, Main.Month + 1, cohort.Biomass, Main.ComputeGrassBiomass(site), monthly_cumulative_LAI); // added (W.Hotta 2020.07.07)
if (!SpeciesData.Grass[cohort.Species] &&
cohort.Biomass > ComputeGrassBiomass(site) * grassThresholdMultiplier)
{
monthly_cumulative_LAI = SiteVars.MonthlyLAI_Trees[site][Main.Month];
// PlugIn.ModelCore.UI.WriteLine("Higher than Sasa"); // added (W.Hotta 2020.07.07)
}
else
{
// monthly_cumulative_LAI = SiteVars.MonthlyLAI[site][Main.Month];
monthly_cumulative_LAI = SiteVars.MonthlyLAI_Trees[site][Main.Month] + SiteVars.MonthlyLAI_GrassesLastMonth[site]; // Chihiro, 2021.03.30: tentative. trees + grass layer
}
double competition_limit = Math.Max(0.0, Math.Exp(k * monthly_cumulative_LAI));
return competition_limit;
}
//---------------------------------------------------------------------------
//... Originally from CENTURY
//...This funtion returns a value for potential plant production
// due to water content. Basically you have an equation of a
// line with a moveable y-intercept depending on the soil type.
// pprpts(1): The minimum ratio of available water to pet which
// would completely limit production assuming wc=0.
// pprpts(2): The effect of wc on the intercept, allows the
// user to increase the value of the intercept and
// thereby increase the slope of the line.
// pprpts(3): The lowest ratio of available water to pet at which
// there is no restriction on production.
private static double calculateWater_Limit(ActiveSite site, IEcoregion ecoregion, ISpecies species)
{
// Ratio_AvailWaterToPET used to be pptprd and WaterLimit used to be pprdwc
double Ratio_AvailWaterToPET = 0.0;
double waterContent = SiteVars.SoilFieldCapacity[site] - SiteVars.SoilWiltingPoint[site];
double tmin = ClimateRegionData.AnnualWeather[ecoregion].MonthlyMinTemp[Main.Month];
double H2Oinputs = ClimateRegionData.AnnualWeather[ecoregion].MonthlyPrecip[Main.Month]; //rain + irract;
double pet = ClimateRegionData.AnnualWeather[ecoregion].MonthlyPET[Main.Month];
if (pet >= 0.01)
{
Ratio_AvailWaterToPET = (SiteVars.AvailableWater[site] / pet); //Modified by ML so that we weren't double-counting precip as in above equation
}
else Ratio_AvailWaterToPET = 0.01;
//...The equation for the y-intercept (intcpt) is A+B*WC. A and B
// determine the effect of soil texture on plant production based
// on moisture.
//PPRPTS naming convention is imported from orginal Century model. Now replaced with 'MoistureCurve' to be more intuitive
//...New way (with updated naming convention):
double moisturecurve1 = 0.0; // OtherData.MoistureCurve1;
double moisturecurve2 = FunctionalType.Table[SpeciesData.FuncType[species]].MoistureCurve2;
double moisturecurve3 = FunctionalType.Table[SpeciesData.FuncType[species]].MoistureCurve3;
double intcpt = moisturecurve1 + (moisturecurve2 * waterContent);
double slope = 1.0 / (moisturecurve3 - intcpt);
double WaterLimit = 1.0 + slope * (Ratio_AvailWaterToPET - moisturecurve3);
if (WaterLimit > 1.0) WaterLimit = 1.0;
if (WaterLimit < 0.01) WaterLimit = 0.01;
//PlugIn.ModelCore.UI.WriteLine("Intercept={0}, Slope={1}, WaterLimit={2}.", intcpt, slope, WaterLimit);
if (PlugIn.ModelCore.CurrentTime > 0 && OtherData.CalibrateMode)
{
CalibrateLog.availableWater = SiteVars.AvailableWater[site];
//Outputs.CalibrateLog.Write("{0:0.00},", SiteVars.AvailableWater[site]);
}
return WaterLimit;
}
//-----------
private double calculateTemp_Limit(ActiveSite site, ISpecies species)
{
//Originally from gpdf.f of CENTURY model
//It calculates the limitation of soil temperature on aboveground forest potential production.
//...This routine is functionally equivalent to the routine of the
// same name, described in the publication:
// Some Graphs and their Functional Forms
// Technical Report No. 153
// William Parton and George Innis (1972)
// Natural Resource Ecology Lab.
// Colorado State University
// Fort collins, Colorado 80523
double A1 = SiteVars.SoilTemperature[site];
double A2 = FunctionalType.Table[SpeciesData.FuncType[species]].TempCurve1;
double A3 = FunctionalType.Table[SpeciesData.FuncType[species]].TempCurve2;
double A4 = FunctionalType.Table[SpeciesData.FuncType[species]].TempCurve3;
double A5 = FunctionalType.Table[SpeciesData.FuncType[species]].TempCurve4;
double frac = (A3-A1) / (A3-A2);
double U1 = 0.0;
if (frac > 0.0)
U1 = Math.Exp(A4 / A5 * (1.0 - Math.Pow(frac, A5))) * Math.Pow(frac, A4);
//PlugIn.ModelCore.UI.WriteLine(" TEMPERATURE Limits: Month={0}, Soil Temp={1:0.00}, Temp Limit={2:0.00}. [PPDF1={3:0.0},PPDF2={4:0.0},PPDF3={5:0.0},PPDF4={6:0.0}]", month+1, A1, U1,A2,A3,A4,A5);
return U1;
}
//---------------------------------------------------------------------
// Chihiro 2020.01.22
public static double ComputeGrassBiomass(ActiveSite site)
{
double grassTotal = 0;
if (SiteVars.Cohorts[site] != null)
foreach (ISpeciesCohorts speciesCohorts in SiteVars.Cohorts[site])
foreach (ICohort cohort in speciesCohorts)
if (SpeciesData.Grass[cohort.Species])
grassTotal += cohort.WoodBiomass;
return grassTotal;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Threading;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
namespace System.Reflection
{
internal unsafe sealed class RtFieldInfo : RuntimeFieldInfo, IRuntimeFieldInfo
{
#region Private Data Members
// agressive caching
private IntPtr m_fieldHandle;
private FieldAttributes m_fieldAttributes;
// lazy caching
private string m_name;
private RuntimeType m_fieldType;
private INVOCATION_FLAGS m_invocationFlags;
internal INVOCATION_FLAGS InvocationFlags
{
get
{
if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
{
Type declaringType = DeclaringType;
bool fIsReflectionOnlyType = (declaringType is ReflectionOnlyType);
INVOCATION_FLAGS invocationFlags = 0;
// first take care of all the NO_INVOKE cases
if (
(declaringType != null && declaringType.ContainsGenericParameters) ||
(declaringType == null && Module.Assembly.ReflectionOnly) ||
(fIsReflectionOnlyType)
)
{
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE;
}
// If the invocationFlags are still 0, then
// this should be an usable field, determine the other flags
if (invocationFlags == 0)
{
if ((m_fieldAttributes & FieldAttributes.InitOnly) != (FieldAttributes)0)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD;
if ((m_fieldAttributes & FieldAttributes.HasFieldRVA) != (FieldAttributes)0)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD;
// find out if the field type is one of the following: Primitive, Enum or Pointer
Type fieldType = FieldType;
if (fieldType.IsPointer || fieldType.IsEnum || fieldType.IsPrimitive)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_FIELD_SPECIAL_CAST;
}
// must be last to avoid threading problems
m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;
}
return m_invocationFlags;
}
}
#endregion
private RuntimeAssembly GetRuntimeAssembly() { return m_declaringType.GetRuntimeAssembly(); }
#region Constructor
internal RtFieldInfo(
RuntimeFieldHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags)
: base(reflectedTypeCache, declaringType, bindingFlags)
{
m_fieldHandle = handle.Value;
m_fieldAttributes = RuntimeFieldHandle.GetAttributes(handle);
}
#endregion
#region Private Members
RuntimeFieldHandleInternal IRuntimeFieldInfo.Value
{
get
{
return new RuntimeFieldHandleInternal(m_fieldHandle);
}
}
#endregion
#region Internal Members
internal void CheckConsistency(Object target)
{
// only test instance fields
if ((m_fieldAttributes & FieldAttributes.Static) != FieldAttributes.Static)
{
if (!m_declaringType.IsInstanceOfType(target))
{
if (target == null)
{
throw new TargetException(SR.RFLCT_Targ_StatFldReqTarg);
}
else
{
throw new ArgumentException(
String.Format(CultureInfo.CurrentUICulture, SR.Arg_FieldDeclTarget,
Name, m_declaringType, target.GetType()));
}
}
}
}
internal override bool CacheEquals(object o)
{
RtFieldInfo m = o as RtFieldInfo;
if ((object)m == null)
return false;
return m.m_fieldHandle == m_fieldHandle;
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal void InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture, ref StackCrawlMark stackMark)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
RuntimeType declaringType = DeclaringType as RuntimeType;
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
{
if (declaringType != null && declaringType.ContainsGenericParameters)
throw new InvalidOperationException(SR.Arg_UnboundGenField);
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
throw new InvalidOperationException(SR.Arg_ReflectionOnlyField);
throw new FieldAccessException();
}
CheckConsistency(obj);
RuntimeType fieldType = (RuntimeType)FieldType;
value = fieldType.CheckValue(value, binder, culture, invokeAttr);
bool domainInitialized = false;
if (declaringType == null)
{
RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized);
}
else
{
domainInitialized = declaringType.DomainInitialized;
RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized);
declaringType.DomainInitialized = domainInitialized;
}
}
// UnsafeSetValue doesn't perform any consistency or visibility check.
// It is the caller's responsibility to ensure the operation is safe.
// When the caller needs to perform visibility checks they should call
// InternalSetValue() instead. When the caller needs to perform
// consistency checks they should call CheckConsistency() before
// calling this method.
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal void UnsafeSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
{
RuntimeType declaringType = DeclaringType as RuntimeType;
RuntimeType fieldType = (RuntimeType)FieldType;
value = fieldType.CheckValue(value, binder, culture, invokeAttr);
bool domainInitialized = false;
if (declaringType == null)
{
RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized);
}
else
{
domainInitialized = declaringType.DomainInitialized;
RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized);
declaringType.DomainInitialized = domainInitialized;
}
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal Object InternalGetValue(Object obj, ref StackCrawlMark stackMark)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
RuntimeType declaringType = DeclaringType as RuntimeType;
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
{
if (declaringType != null && DeclaringType.ContainsGenericParameters)
throw new InvalidOperationException(SR.Arg_UnboundGenField);
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
throw new InvalidOperationException(SR.Arg_ReflectionOnlyField);
throw new FieldAccessException();
}
CheckConsistency(obj);
return UnsafeGetValue(obj);
}
// UnsafeGetValue doesn't perform any consistency or visibility check.
// It is the caller's responsibility to ensure the operation is safe.
// When the caller needs to perform visibility checks they should call
// InternalGetValue() instead. When the caller needs to perform
// consistency checks they should call CheckConsistency() before
// calling this method.
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal Object UnsafeGetValue(Object obj)
{
RuntimeType declaringType = DeclaringType as RuntimeType;
RuntimeType fieldType = (RuntimeType)FieldType;
bool domainInitialized = false;
if (declaringType == null)
{
return RuntimeFieldHandle.GetValue(this, obj, fieldType, null, ref domainInitialized);
}
else
{
domainInitialized = declaringType.DomainInitialized;
object retVal = RuntimeFieldHandle.GetValue(this, obj, fieldType, declaringType, ref domainInitialized);
declaringType.DomainInitialized = domainInitialized;
return retVal;
}
}
#endregion
#region MemberInfo Overrides
public override String Name
{
get
{
if (m_name == null)
m_name = RuntimeFieldHandle.GetName(this);
return m_name;
}
}
internal String FullName
{
get
{
return String.Format("{0}.{1}", DeclaringType.FullName, Name);
}
}
public override int MetadataToken
{
get { return RuntimeFieldHandle.GetToken(this); }
}
internal override RuntimeModule GetRuntimeModule()
{
return RuntimeTypeHandle.GetModule(RuntimeFieldHandle.GetApproxDeclaringType(this));
}
#endregion
#region FieldInfo Overrides
public override Object GetValue(Object obj)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return InternalGetValue(obj, ref stackMark);
}
public override object GetRawConstantValue() { throw new InvalidOperationException(); }
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override Object GetValueDirect(TypedReference obj)
{
if (obj.IsNull)
throw new ArgumentException(SR.Arg_TypedReference_Null);
unsafe
{
// Passing TypedReference by reference is easier to make correct in native code
return RuntimeFieldHandle.GetValueDirect(this, (RuntimeType)FieldType, &obj, (RuntimeType)DeclaringType);
}
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
InternalSetValue(obj, value, invokeAttr, binder, culture, ref stackMark);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValueDirect(TypedReference obj, Object value)
{
if (obj.IsNull)
throw new ArgumentException(SR.Arg_TypedReference_Null);
unsafe
{
// Passing TypedReference by reference is easier to make correct in native code
RuntimeFieldHandle.SetValueDirect(this, (RuntimeType)FieldType, &obj, value, (RuntimeType)DeclaringType);
}
}
public override RuntimeFieldHandle FieldHandle
{
get
{
Type declaringType = DeclaringType;
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
throw new InvalidOperationException(SR.InvalidOperation_NotAllowedInReflectionOnly);
return new RuntimeFieldHandle(this);
}
}
internal IntPtr GetFieldHandle()
{
return m_fieldHandle;
}
public override FieldAttributes Attributes
{
get
{
return m_fieldAttributes;
}
}
public override Type FieldType
{
get
{
if (m_fieldType == null)
m_fieldType = new Signature(this, m_declaringType).FieldType;
return m_fieldType;
}
}
public override Type[] GetRequiredCustomModifiers()
{
return new Signature(this, m_declaringType).GetCustomModifiers(1, true);
}
public override Type[] GetOptionalCustomModifiers()
{
return new Signature(this, m_declaringType).GetCustomModifiers(1, false);
}
#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 MySql.Data.MySqlClient;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Data;
namespace OpenSim.Data.MySQL
{
public class MySQLEstateStore : IEstateDataStore
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_connectionString;
private FieldInfo[] m_Fields;
private Dictionary<string, FieldInfo> m_FieldMap =
new Dictionary<string, FieldInfo>();
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public MySQLEstateStore()
{
}
public MySQLEstateStore(string connectionString)
{
Initialise(connectionString);
}
public void Initialise(string connectionString)
{
m_connectionString = connectionString;
try
{
m_log.Info("[REGION DB]: MySql - connecting: " + Util.GetDisplayConnectionString(m_connectionString));
}
catch (Exception e)
{
m_log.Debug("Exception: password not found in connection string\n" + e.ToString());
}
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
Migration m = new Migration(dbcon, Assembly, "EstateStore");
m.Update();
dbcon.Close();
Type t = typeof(EstateSettings);
m_Fields = t.GetFields(BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
foreach (FieldInfo f in m_Fields)
{
if (f.Name.Substring(0, 2) == "m_")
m_FieldMap[f.Name.Substring(2)] = f;
}
}
}
private string[] FieldList
{
get { return new List<string>(m_FieldMap.Keys).ToArray(); }
}
public EstateSettings LoadEstateSettings(UUID regionID, bool create)
{
string sql = "select estate_settings." + String.Join(",estate_settings.", FieldList) +
" from estate_map left join estate_settings on estate_map.EstateID = estate_settings.EstateID where estate_settings.EstateID is not null and RegionID = ?RegionID";
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("?RegionID", regionID.ToString());
EstateSettings e = DoLoad(cmd, regionID, create);
if (!create && e.EstateID == 0) // Not found
return null;
return e;
}
}
public EstateSettings CreateNewEstate()
{
EstateSettings es = new EstateSettings();
es.OnSave += StoreEstateSettings;
DoCreate(es);
LoadBanList(es);
es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers");
es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users");
es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups");
return es;
}
private EstateSettings DoLoad(MySqlCommand cmd, UUID regionID, bool create)
{
EstateSettings es = new EstateSettings();
es.OnSave += StoreEstateSettings;
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
cmd.Connection = dbcon;
bool found = false;
using (IDataReader r = cmd.ExecuteReader())
{
if (r.Read())
{
found = true;
foreach (string name in FieldList)
{
if (m_FieldMap[name].FieldType == typeof(bool))
{
m_FieldMap[name].SetValue(es, Convert.ToInt32(r[name]) != 0);
}
else if (m_FieldMap[name].FieldType == typeof(UUID))
{
m_FieldMap[name].SetValue(es, DBGuid.FromDB(r[name]));
}
else
{
m_FieldMap[name].SetValue(es, r[name]);
}
}
}
}
dbcon.Close();
cmd.Connection = null;
if (!found && create)
{
DoCreate(es);
LinkRegion(regionID, (int)es.EstateID);
}
}
LoadBanList(es);
es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers");
es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users");
es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups");
return es;
}
private void DoCreate(EstateSettings es)
{
// Migration case
List<string> names = new List<string>(FieldList);
names.Remove("EstateID");
string sql = "insert into estate_settings (" + String.Join(",", names.ToArray()) + ") values ( ?" + String.Join(", ?", names.ToArray()) + ")";
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd2 = dbcon.CreateCommand())
{
cmd2.CommandText = sql;
cmd2.Parameters.Clear();
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
if ((bool)m_FieldMap[name].GetValue(es))
cmd2.Parameters.AddWithValue("?" + name, "1");
else
cmd2.Parameters.AddWithValue("?" + name, "0");
}
else
{
cmd2.Parameters.AddWithValue("?" + name, m_FieldMap[name].GetValue(es).ToString());
}
}
cmd2.ExecuteNonQuery();
cmd2.CommandText = "select LAST_INSERT_ID() as id";
cmd2.Parameters.Clear();
using (IDataReader r = cmd2.ExecuteReader())
{
r.Read();
es.EstateID = Convert.ToUInt32(r["id"]);
}
es.Save();
}
dbcon.Close();
}
}
public void StoreEstateSettings(EstateSettings es)
{
string sql = "replace into estate_settings (" + String.Join(",", FieldList) + ") values ( ?" + String.Join(", ?", FieldList) + ")";
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = dbcon.CreateCommand())
{
cmd.CommandText = sql;
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
if ((bool)m_FieldMap[name].GetValue(es))
cmd.Parameters.AddWithValue("?" + name, "1");
else
cmd.Parameters.AddWithValue("?" + name, "0");
}
else
{
cmd.Parameters.AddWithValue("?" + name, m_FieldMap[name].GetValue(es).ToString());
}
}
cmd.ExecuteNonQuery();
}
dbcon.Close();
}
SaveBanList(es);
SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers);
SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess);
SaveUUIDList(es.EstateID, "estate_groups", es.EstateGroups);
}
private void LoadBanList(EstateSettings es)
{
es.ClearBans();
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = dbcon.CreateCommand())
{
cmd.CommandText = "select bannedUUID from estateban where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", es.EstateID);
using (IDataReader r = cmd.ExecuteReader())
{
while (r.Read())
{
EstateBan eb = new EstateBan();
UUID uuid = new UUID();
UUID.TryParse(r["bannedUUID"].ToString(), out uuid);
eb.BannedUserID = uuid;
eb.BannedHostAddress = "0.0.0.0";
eb.BannedHostIPMask = "0.0.0.0";
es.AddBan(eb);
}
}
}
dbcon.Close();
}
}
private void SaveBanList(EstateSettings es)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = dbcon.CreateCommand())
{
cmd.CommandText = "delete from estateban where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) values ( ?EstateID, ?bannedUUID, '', '', '' )";
foreach (EstateBan b in es.EstateBans)
{
cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString());
cmd.Parameters.AddWithValue("?bannedUUID", b.BannedUserID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
dbcon.Close();
}
}
void SaveUUIDList(uint EstateID, string table, UUID[] data)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = dbcon.CreateCommand())
{
cmd.CommandText = "delete from " + table + " where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into " + table + " (EstateID, uuid) values ( ?EstateID, ?uuid )";
foreach (UUID uuid in data)
{
cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString());
cmd.Parameters.AddWithValue("?uuid", uuid.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
dbcon.Close();
}
}
UUID[] LoadUUIDList(uint EstateID, string table)
{
List<UUID> uuids = new List<UUID>();
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = dbcon.CreateCommand())
{
cmd.CommandText = "select uuid from " + table + " where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", EstateID);
using (IDataReader r = cmd.ExecuteReader())
{
while (r.Read())
{
// EstateBan eb = new EstateBan();
uuids.Add(DBGuid.FromDB(r["uuid"]));
}
}
}
dbcon.Close();
}
return uuids.ToArray();
}
public EstateSettings LoadEstateSettings(int estateID)
{
using (MySqlCommand cmd = new MySqlCommand())
{
string sql = "select estate_settings." + String.Join(",estate_settings.", FieldList) + " from estate_settings where EstateID = ?EstateID";
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("?EstateID", estateID);
EstateSettings e = DoLoad(cmd, UUID.Zero, false);
if (e.EstateID != estateID)
return null;
return e;
}
}
public List<EstateSettings> LoadEstateSettingsAll()
{
List<EstateSettings> allEstateSettings = new List<EstateSettings>();
List<int> allEstateIds = GetEstatesAll();
foreach (int estateId in allEstateIds)
allEstateSettings.Add(LoadEstateSettings(estateId));
return allEstateSettings;
}
public List<int> GetEstatesAll()
{
List<int> result = new List<int>();
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = dbcon.CreateCommand())
{
cmd.CommandText = "select estateID from estate_settings";
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(Convert.ToInt32(reader["EstateID"]));
}
reader.Close();
}
}
dbcon.Close();
}
return result;
}
public List<int> GetEstates(string search)
{
List<int> result = new List<int>();
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = dbcon.CreateCommand())
{
cmd.CommandText = "select estateID from estate_settings where EstateName = ?EstateName";
cmd.Parameters.AddWithValue("?EstateName", search);
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(Convert.ToInt32(reader["EstateID"]));
}
reader.Close();
}
}
dbcon.Close();
}
return result;
}
public List<int> GetEstatesByOwner(UUID ownerID)
{
List<int> result = new List<int>();
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = dbcon.CreateCommand())
{
cmd.CommandText = "select estateID from estate_settings where EstateOwner = ?EstateOwner";
cmd.Parameters.AddWithValue("?EstateOwner", ownerID);
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(Convert.ToInt32(reader["EstateID"]));
}
reader.Close();
}
}
dbcon.Close();
}
return result;
}
public bool LinkRegion(UUID regionID, int estateID)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
MySqlTransaction transaction = dbcon.BeginTransaction();
try
{
// Delete any existing association of this region with an estate.
using (MySqlCommand cmd = dbcon.CreateCommand())
{
cmd.Transaction = transaction;
cmd.CommandText = "delete from estate_map where RegionID = ?RegionID";
cmd.Parameters.AddWithValue("?RegionID", regionID);
cmd.ExecuteNonQuery();
}
using (MySqlCommand cmd = dbcon.CreateCommand())
{
cmd.Transaction = transaction;
cmd.CommandText = "insert into estate_map values (?RegionID, ?EstateID)";
cmd.Parameters.AddWithValue("?RegionID", regionID);
cmd.Parameters.AddWithValue("?EstateID", estateID);
int ret = cmd.ExecuteNonQuery();
if (ret != 0)
transaction.Commit();
else
transaction.Rollback();
dbcon.Close();
return (ret != 0);
}
}
catch (MySqlException ex)
{
m_log.Error("[REGION DB]: LinkRegion failed: " + ex.Message);
transaction.Rollback();
}
dbcon.Close();
}
return false;
}
public List<UUID> GetRegions(int estateID)
{
List<UUID> result = new List<UUID>();
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
try
{
using (MySqlCommand cmd = dbcon.CreateCommand())
{
cmd.CommandText = "select RegionID from estate_map where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", estateID.ToString());
using (IDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
result.Add(DBGuid.FromDB(reader["RegionID"]));
reader.Close();
}
}
}
catch (Exception e)
{
m_log.Error("[REGION DB]: Error reading estate map. " + e.ToString());
return result;
}
dbcon.Close();
}
return result;
}
public bool DeleteEstate(int estateID)
{
return false;
}
}
}
| |
using MatterHackers.Agg.Transform;
using MatterHackers.Agg.VertexSource;
using MatterHackers.VectorMath;
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# port by: Lars Brubaker
// larsbrubaker@gmail.com
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// classes spline_ctrl_impl, spline_ctrl
//
//----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace MatterHackers.Agg.UI
{
//------------------------------------------------------------------------
// Class that can be used to create an interactive control to set up
// gamma arrays.
//------------------------------------------------------------------------
public class spline_ctrl : SimpleVertexSourceWidget
{
private Color m_background_color;
private Color m_border_color;
private Color m_curve_color;
private Color m_inactive_pnt_color;
private Color m_active_pnt_color;
private int m_num_pnt;
private double[] m_xp = new double[32];
private double[] m_yp = new double[32];
private bspline m_spline = new bspline();
private double[] m_spline_values = new double[256];
private byte[] m_spline_values8 = new byte[256];
private double m_border_width;
private double m_border_extra;
private double m_curve_width;
private double m_point_size;
private double m_xs1;
private double m_ys1;
private double m_xs2;
private double m_ys2;
private VertexSource.VertexStorage m_curve_pnt;
private Stroke m_curve_poly;
private VertexSource.Ellipse m_ellipse;
private int m_idx;
private int m_vertex;
private double[] m_vx = new double[32];
private double[] m_vy = new double[32];
private int m_active_pnt;
private int m_move_pnt;
private double m_pdx;
private double m_pdy;
private Transform.Affine m_mtx = Affine.NewIdentity();
public spline_ctrl(Vector2 location, Vector2 size, int num_pnt)
: base(location, false)
{
LocalBounds = new RectangleDouble(0, 0, size.X, size.Y);
m_curve_pnt = new VertexStorage();
m_curve_poly = new Stroke(m_curve_pnt);
m_ellipse = new Ellipse();
m_background_color = new Color(1.0, 1.0, 0.9);
m_border_color = new Color(0.0, 0.0, 0.0);
m_curve_color = new Color(0.0, 0.0, 0.0);
m_inactive_pnt_color = new Color(0.0, 0.0, 0.0);
m_active_pnt_color = new Color(1.0, 0.0, 0.0);
m_num_pnt = (num_pnt);
m_border_width = (1.0);
m_border_extra = (0.0);
m_curve_width = (1.0);
m_point_size = (3.0);
m_curve_poly = new Stroke(m_curve_pnt);
m_idx = (0);
m_vertex = (0);
m_active_pnt = (-1);
m_move_pnt = (-1);
m_pdx = (0.0);
m_pdy = (0.0);
if (m_num_pnt < 4) m_num_pnt = 4;
if (m_num_pnt > 32) m_num_pnt = 32;
for (int i = 0; i < m_num_pnt; i++)
{
m_xp[i] = (double)(i) / (double)(m_num_pnt - 1);
m_yp[i] = 0.5;
}
calc_spline_box();
update_spline();
{
m_spline.init((int)m_num_pnt, m_xp, m_yp);
for (int i = 0; i < 256; i++)
{
m_spline_values[i] = m_spline.get((double)(i) / 255.0);
if (m_spline_values[i] < 0.0) m_spline_values[i] = 0.0;
if (m_spline_values[i] > 1.0) m_spline_values[i] = 1.0;
m_spline_values8[i] = (byte)(m_spline_values[i] * 255.0);
}
}
}
// Set other parameters
public void border_width(double t)
{
border_width(t, 0);
}
public void border_width(double t, double extra)
{
m_border_width = t;
m_border_extra = extra;
calc_spline_box();
LocalBounds = new RectangleDouble(-m_border_extra, -m_border_extra, Width + m_border_extra, Height + m_border_extra);
}
public void curve_width(double t)
{
m_curve_width = t;
}
public void point_size(double s)
{
m_point_size = s;
}
public override void OnMouseDown(MouseEventArgs mouseEvent)
{
double x = mouseEvent.X;
double y = mouseEvent.Y;
int i;
for (i = 0; i < m_num_pnt; i++)
{
double xp = calc_xp(i);
double yp = calc_yp(i);
if (agg_math.calc_distance(x, y, xp, yp) <= m_point_size + 1)
{
m_pdx = xp - x;
m_pdy = yp - y;
m_active_pnt = m_move_pnt = (int)(i);
}
}
base.OnMouseDown(mouseEvent);
}
public override void OnMouseUp(MouseEventArgs mouseEvent)
{
if (m_move_pnt >= 0)
{
m_move_pnt = -1;
}
base.OnMouseUp(mouseEvent);
}
public override void OnMouseMove(MouseEventArgs mouseEvent)
{
double x = mouseEvent.X;
double y = mouseEvent.Y;
if (m_move_pnt >= 0)
{
double xp = x + m_pdx;
double yp = y + m_pdy;
set_xp((int)m_move_pnt, (xp - m_xs1) / (m_xs2 - m_xs1));
set_yp((int)m_move_pnt, (yp - m_ys1) / (m_ys2 - m_ys1));
update_spline();
Invalidate();
}
base.OnMouseMove(mouseEvent);
}
public override void OnKeyDown(KeyEventArgs keyEvent)
{
// this must be called first to ensure we get the correct Handled state
base.OnKeyDown(keyEvent);
if (!keyEvent.Handled)
{
double kx = 0.0;
double ky = 0.0;
bool ret = false;
if (m_active_pnt >= 0)
{
kx = m_xp[m_active_pnt];
ky = m_yp[m_active_pnt];
if (keyEvent.KeyCode == Keys.Left) { kx -= 0.001; ret = true; }
if (keyEvent.KeyCode == Keys.Right) { kx += 0.001; ret = true; }
if (keyEvent.KeyCode == Keys.Down) { ky -= 0.001; ret = true; }
if (keyEvent.KeyCode == Keys.Up) { ky += 0.001; ret = true; }
}
if (ret)
{
set_xp((int)m_active_pnt, kx);
set_yp((int)m_active_pnt, ky);
update_spline();
keyEvent.Handled = true;
Invalidate();
}
}
}
public void active_point(int i)
{
m_active_pnt = i;
}
public double[] spline()
{
return m_spline_values;
}
public byte[] spline8()
{
return m_spline_values8;
}
public double value(double x)
{
x = m_spline.get(x);
if (x < 0.0) x = 0.0;
if (x > 1.0) x = 1.0;
return x;
}
public void value(int idx, double y)
{
if (idx < m_num_pnt)
{
set_yp(idx, y);
}
}
public void point(int idx, double x, double y)
{
if (idx < m_num_pnt)
{
set_xp(idx, x);
set_yp(idx, y);
}
}
public void x(int idx, double x)
{
m_xp[idx] = x;
}
public void y(int idx, double y)
{
m_yp[idx] = y;
}
public double x(int idx)
{
return m_xp[idx];
}
public double y(int idx)
{
return m_yp[idx];
}
public void update_spline()
{
m_spline.init((int)m_num_pnt, m_xp, m_yp);
for (int i = 0; i < 256; i++)
{
m_spline_values[i] = m_spline.get((double)(i) / 255.0);
if (m_spline_values[i] < 0.0) m_spline_values[i] = 0.0;
if (m_spline_values[i] > 1.0) m_spline_values[i] = 1.0;
m_spline_values8[i] = (byte)(m_spline_values[i] * 255.0);
}
}
public override void OnDraw(Graphics2D graphics2D)
{
int index = 0;
rewind(index);
graphics2D.Render(this, m_background_color);
rewind(++index);
graphics2D.Render(this, m_border_color);
rewind(++index);
graphics2D.Render(this, m_curve_color);
rewind(++index);
graphics2D.Render(this, m_inactive_pnt_color);
rewind(++index);
graphics2D.Render(this, m_active_pnt_color);
base.OnDraw(graphics2D);
}
// Vertex source interface
public override int num_paths()
{
return 5;
}
public override IEnumerable<VertexData> Vertices()
{
throw new NotImplementedException();
}
public override void rewind(int idx)
{
m_idx = idx;
switch (idx)
{
default:
case 0: // Background
m_vertex = 0;
m_vx[0] = -m_border_extra;
m_vy[0] = -m_border_extra;
m_vx[1] = Width + m_border_extra;
m_vy[1] = -m_border_extra;
m_vx[2] = Width + m_border_extra;
m_vy[2] = Height + m_border_extra;
m_vx[3] = -m_border_extra;
m_vy[3] = Height + m_border_extra;
break;
case 1: // Border
m_vertex = 0;
m_vx[0] = 0;
m_vy[0] = 0;
m_vx[1] = Width - m_border_extra * 2;
m_vy[1] = 0;
m_vx[2] = Width - m_border_extra * 2;
m_vy[2] = Height - m_border_extra * 2;
m_vx[3] = 0;
m_vy[3] = Height - m_border_extra * 2;
m_vx[4] = +m_border_width;
m_vy[4] = +m_border_width;
m_vx[5] = +m_border_width;
m_vy[5] = Height - m_border_width - m_border_extra * 2;
m_vx[6] = Width - m_border_width - m_border_extra * 2;
m_vy[6] = Height - m_border_width - m_border_extra * 2;
m_vx[7] = Width - m_border_width - m_border_extra * 2;
m_vy[7] = +m_border_width;
break;
case 2: // Curve
calc_curve();
m_curve_poly.Width = m_curve_width;
m_curve_poly.rewind(0);
break;
case 3: // Inactive points
m_curve_pnt.remove_all();
for (int i = 0; i < m_num_pnt; i++)
{
if (i != m_active_pnt)
{
m_ellipse.init(calc_xp(i), calc_yp(i),
m_point_size, m_point_size, 32);
m_curve_pnt.concat_path(m_ellipse);
}
}
m_curve_poly.rewind(0);
break;
case 4: // Active point
m_curve_pnt.remove_all();
if (m_active_pnt >= 0)
{
m_ellipse.init(calc_xp(m_active_pnt), calc_yp(m_active_pnt),
m_point_size, m_point_size, 32);
m_curve_pnt.concat_path(m_ellipse);
}
m_curve_poly.rewind(0);
break;
}
}
public override ShapePath.FlagsAndCommand vertex(out double x, out double y)
{
x = 0;
y = 0;
ShapePath.FlagsAndCommand cmd = ShapePath.FlagsAndCommand.LineTo;
switch (m_idx)
{
case 0:
if (m_vertex == 0) cmd = ShapePath.FlagsAndCommand.MoveTo;
if (m_vertex >= 4) cmd = ShapePath.FlagsAndCommand.Stop;
x = m_vx[m_vertex];
y = m_vy[m_vertex];
m_vertex++;
break;
case 1:
if (m_vertex == 0 || m_vertex == 4) cmd = ShapePath.FlagsAndCommand.MoveTo;
if (m_vertex >= 8) cmd = ShapePath.FlagsAndCommand.Stop;
x = m_vx[m_vertex];
y = m_vy[m_vertex];
m_vertex++;
break;
case 2:
cmd = m_curve_poly.vertex(out x, out y);
break;
case 3:
case 4:
cmd = m_curve_pnt.vertex(out x, out y);
break;
default:
cmd = ShapePath.FlagsAndCommand.Stop;
break;
}
if (!ShapePath.is_stop(cmd))
{
//OriginRelativeParentTransform.transform(ref x, ref y);
}
return cmd;
}
private void calc_spline_box()
{
m_xs1 = LocalBounds.Left + m_border_width;
m_ys1 = LocalBounds.Bottom + m_border_width;
m_xs2 = LocalBounds.Right - m_border_width;
m_ys2 = LocalBounds.Top - m_border_width;
}
private void calc_curve()
{
int i;
m_curve_pnt.remove_all();
m_curve_pnt.MoveTo(m_xs1, m_ys1 + (m_ys2 - m_ys1) * m_spline_values[0]);
for (i = 1; i < 256; i++)
{
m_curve_pnt.LineTo(m_xs1 + (m_xs2 - m_xs1) * (double)(i) / 255.0,
m_ys1 + (m_ys2 - m_ys1) * m_spline_values[i]);
}
}
private double calc_xp(int idx)
{
return m_xs1 + (m_xs2 - m_xs1) * m_xp[idx];
}
private double calc_yp(int idx)
{
return m_ys1 + (m_ys2 - m_ys1) * m_yp[idx];
}
private void set_xp(int idx, double val)
{
if (val < 0.0) val = 0.0;
if (val > 1.0) val = 1.0;
if (idx == 0)
{
val = 0.0;
}
else if (idx == m_num_pnt - 1)
{
val = 1.0;
}
else
{
if (val < m_xp[idx - 1] + 0.001) val = m_xp[idx - 1] + 0.001;
if (val > m_xp[idx + 1] - 0.001) val = m_xp[idx + 1] - 0.001;
}
m_xp[idx] = val;
}
private void set_yp(int idx, double val)
{
if (val < 0.0) val = 0.0;
if (val > 1.0) val = 1.0;
m_yp[idx] = val;
}
// Set colors
public void background_color(Color c)
{
m_background_color = c;
}
public void border_color(Color c)
{
m_border_color = c;
}
public void curve_color(Color c)
{
m_curve_color = c;
}
public void inactive_pnt_color(Color c)
{
m_inactive_pnt_color = c;
}
public void active_pnt_color(Color c)
{
m_active_pnt_color = c;
}
public override IColorType color(int i)
{
switch (i)
{
case 0:
return m_background_color;
case 1:
return m_border_color;
case 2:
return m_curve_color;
case 3:
return m_inactive_pnt_color;
case 4:
return m_active_pnt_color;
default:
throw new System.IndexOutOfRangeException("You asked for a color out of range.");
}
}
}
}
| |
using System;
using AutoMapper.Configuration;
namespace AutoMapper
{
using ObjectMappingOperationOptions = MappingOperationOptions<object, object>;
public class Mapper : IRuntimeMapper
{
private const string InvalidOperationMessage = "Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.";
#region Static API
private static IConfigurationProvider _configuration;
private static IMapper _instance;
/// <summary>
/// Configuration provider for performing maps
/// </summary>
public static IConfigurationProvider Configuration
{
get => _configuration ?? throw new InvalidOperationException(InvalidOperationMessage);
private set => _configuration = value;
}
/// <summary>
/// Static mapper instance. You can also create a <see cref="Mapper"/> instance directly using the <see cref="Configuration"/> instance.
/// </summary>
public static IMapper Instance
{
get => _instance ?? throw new InvalidOperationException(InvalidOperationMessage);
private set => _instance = value;
}
/// <summary>
/// Initialize static configuration instance
/// </summary>
/// <param name="config">Configuration action</param>
public static void Initialize(Action<IMapperConfigurationExpression> config)
{
Configuration = new MapperConfiguration(config);
Instance = new Mapper(Configuration);
}
/// <summary>
/// Initialize static configuration instance
/// </summary>
/// <param name="config">Configuration action</param>
public static void Initialize(MapperConfigurationExpression config)
{
Configuration = new MapperConfiguration(config);
Instance = new Mapper(Configuration);
}
/// <summary>
/// Execute a mapping from the source object to a new destination object.
/// The source type is inferred from the source object.
/// </summary>
/// <typeparam name="TDestination">Destination type to create</typeparam>
/// <param name="source">Source object to map from</param>
/// <returns>Mapped destination object</returns>
public static TDestination Map<TDestination>(object source) => Instance.Map<TDestination>(source);
/// <summary>
/// Execute a mapping from the source object to a new destination object with supplied mapping options.
/// </summary>
/// <typeparam name="TDestination">Destination type to create</typeparam>
/// <param name="source">Source object to map from</param>
/// <param name="opts">Mapping options</param>
/// <returns>Mapped destination object</returns>
public static TDestination Map<TDestination>(object source, Action<IMappingOperationOptions> opts)
=> Instance.Map<TDestination>(source, opts);
/// <summary>
/// Execute a mapping from the source object to a new destination object.
/// </summary>
/// <typeparam name="TSource">Source type to use, regardless of the runtime type</typeparam>
/// <typeparam name="TDestination">Destination type to create</typeparam>
/// <param name="source">Source object to map from</param>
/// <returns>Mapped destination object</returns>
public static TDestination Map<TSource, TDestination>(TSource source)
=> Instance.Map<TSource, TDestination>(source);
/// <summary>
/// Execute a mapping from the source object to a new destination object with supplied mapping options.
/// </summary>
/// <typeparam name="TSource">Source type to use</typeparam>
/// <typeparam name="TDestination">Destination type to create</typeparam>
/// <param name="source">Source object to map from</param>
/// <param name="opts">Mapping options</param>
/// <returns>Mapped destination object</returns>
public static TDestination Map<TSource, TDestination>(TSource source, Action<IMappingOperationOptions<TSource, TDestination>> opts)
=> Instance.Map(source, opts);
/// <summary>
/// Execute a mapping from the source object to the existing destination object.
/// </summary>
/// <typeparam name="TSource">Source type to use</typeparam>
/// <typeparam name="TDestination">Dsetination type</typeparam>
/// <param name="source">Source object to map from</param>
/// <param name="destination">Destination object to map into</param>
/// <returns>The mapped destination object, same instance as the <paramref name="destination"/> object</returns>
public static TDestination Map<TSource, TDestination>(TSource source, TDestination destination)
=> Instance.Map(source, destination);
/// <summary>
/// Execute a mapping from the source object to the existing destination object with supplied mapping options.
/// </summary>
/// <typeparam name="TSource">Source type to use</typeparam>
/// <typeparam name="TDestination">Destination type</typeparam>
/// <param name="source">Source object to map from</param>
/// <param name="destination">Destination object to map into</param>
/// <param name="opts">Mapping options</param>
/// <returns>The mapped destination object, same instance as the <paramref name="destination"/> object</returns>
public static TDestination Map<TSource, TDestination>(TSource source, TDestination destination, Action<IMappingOperationOptions<TSource, TDestination>> opts)
=> Instance.Map(source, destination, opts);
/// <summary>
/// Execute a mapping from the source object to a new destination object with explicit <see cref="System.Type"/> objects
/// </summary>
/// <param name="source">Source object to map from</param>
/// <param name="sourceType">Source type to use</param>
/// <param name="destinationType">Destination type to create</param>
/// <returns>Mapped destination object</returns>
public static object Map(object source, Type sourceType, Type destinationType)
=> Instance.Map(source, sourceType, destinationType);
/// <summary>
/// Execute a mapping from the source object to a new destination object with explicit <see cref="System.Type"/> objects and supplied mapping options.
/// </summary>
/// <param name="source">Source object to map from</param>
/// <param name="sourceType">Source type to use</param>
/// <param name="destinationType">Destination type to create</param>
/// <param name="opts">Mapping options</param>
/// <returns>Mapped destination object</returns>
public static object Map(object source, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts)
=> Instance.Map(source, sourceType, destinationType, opts);
/// <summary>
/// Execute a mapping from the source object to existing destination object with explicit <see cref="System.Type"/> objects
/// </summary>
/// <param name="source">Source object to map from</param>
/// <param name="destination">Destination object to map into</param>
/// <param name="sourceType">Source type to use</param>
/// <param name="destinationType">Destination type to use</param>
/// <returns>Mapped destination object, same instance as the <paramref name="destination"/> object</returns>
public static object Map(object source, object destination, Type sourceType, Type destinationType)
=> Instance.Map(source, destination, sourceType, destinationType);
/// <summary>
/// Execute a mapping from the source object to existing destination object with supplied mapping options and explicit <see cref="System.Type"/> objects
/// </summary>
/// <param name="source">Source object to map from</param>
/// <param name="destination">Destination object to map into</param>
/// <param name="sourceType">Source type to use</param>
/// <param name="destinationType">Destination type to use</param>
/// <param name="opts">Mapping options</param>
/// <returns>Mapped destination object, same instance as the <paramref name="destination"/> object</returns>
public static object Map(object source, object destination, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts)
=> Instance.Map(source, destination, sourceType, destinationType, opts);
/// <summary>
/// Dry run all configured type maps and throw <see cref="AutoMapperConfigurationException"/> for each problem
/// </summary>
public static void AssertConfigurationIsValid() => Configuration.AssertConfigurationIsValid();
#endregion
private readonly IConfigurationProvider _configurationProvider;
private readonly Func<Type, object> _serviceCtor;
public Mapper(IConfigurationProvider configurationProvider)
: this(configurationProvider, configurationProvider.ServiceCtor)
{
}
public Mapper(IConfigurationProvider configurationProvider, Func<Type, object> serviceCtor)
{
_configurationProvider = configurationProvider;
_serviceCtor = serviceCtor;
DefaultContext = new ResolutionContext(new ObjectMappingOperationOptions(serviceCtor), this);
}
public ResolutionContext DefaultContext { get; }
Func<Type, object> IMapper.ServiceCtor => _serviceCtor;
IConfigurationProvider IMapper.ConfigurationProvider => _configurationProvider;
TDestination IMapper.Map<TDestination>(object source)
{
if (source == null)
return default(TDestination);
var types = new TypePair(source.GetType(), typeof(TDestination));
var func = _configurationProvider.GetUntypedMapperFunc(new MapRequest(types, types));
return (TDestination) func(source, null, DefaultContext);
}
TDestination IMapper.Map<TDestination>(object source, Action<IMappingOperationOptions> opts)
{
var mappedObject = default(TDestination);
if (source == null) return mappedObject;
var sourceType = source.GetType();
var destinationType = typeof(TDestination);
mappedObject = (TDestination)((IMapper)this).Map(source, sourceType, destinationType, opts);
return mappedObject;
}
TDestination IMapper.Map<TSource, TDestination>(TSource source)
{
var types = TypePair.Create(source, typeof(TSource), typeof (TDestination));
var func = _configurationProvider.GetMapperFunc<TSource, TDestination>(types);
var destination = default(TDestination);
return func(source, destination, DefaultContext);
}
TDestination IMapper.Map<TSource, TDestination>(TSource source, Action<IMappingOperationOptions<TSource, TDestination>> opts)
{
var types = TypePair.Create(source, typeof(TSource), typeof(TDestination));
var func = _configurationProvider.GetMapperFunc<TSource, TDestination>(types);
var destination = default(TDestination);
var typedOptions = new MappingOperationOptions<TSource, TDestination>(_serviceCtor);
opts(typedOptions);
typedOptions.BeforeMapAction(source, destination);
var context = new ResolutionContext(typedOptions, this);
destination = func(source, destination, context);
typedOptions.AfterMapAction(source, destination);
return destination;
}
TDestination IMapper.Map<TSource, TDestination>(TSource source, TDestination destination)
{
var types = TypePair.Create(source, destination, typeof(TSource), typeof(TDestination));
var func = _configurationProvider.GetMapperFunc<TSource, TDestination>(types);
return func(source, destination, DefaultContext);
}
TDestination IMapper.Map<TSource, TDestination>(TSource source, TDestination destination, Action<IMappingOperationOptions<TSource, TDestination>> opts)
{
var types = TypePair.Create(source, destination, typeof(TSource), typeof(TDestination));
var func = _configurationProvider.GetMapperFunc<TSource, TDestination>(types);
var typedOptions = new MappingOperationOptions<TSource, TDestination>(_serviceCtor);
opts(typedOptions);
typedOptions.BeforeMapAction(source, destination);
var context = new ResolutionContext(typedOptions, this);
destination = func(source, destination, context);
typedOptions.AfterMapAction(source, destination);
return destination;
}
object IMapper.Map(object source, Type sourceType, Type destinationType)
{
var types = TypePair.Create(source, sourceType, destinationType);
var func = _configurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(sourceType, destinationType), types));
return func(source, null, DefaultContext);
}
object IMapper.Map(object source, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts)
{
var types = TypePair.Create(source, sourceType, destinationType);
var func = _configurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(sourceType, destinationType), types));
var options = new ObjectMappingOperationOptions(_serviceCtor);
opts(options);
options.BeforeMapAction(source, null);
var context = new ResolutionContext(options, this);
var destination = func(source, null, context);
options.AfterMapAction(source, destination);
return destination;
}
object IMapper.Map(object source, object destination, Type sourceType, Type destinationType)
{
var types = TypePair.Create(source, destination, sourceType, destinationType);
var func = _configurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(sourceType, destinationType), types));
return func(source, destination, DefaultContext);
}
object IMapper.Map(object source, object destination, Type sourceType, Type destinationType,
Action<IMappingOperationOptions> opts)
{
var types = TypePair.Create(source, destination, sourceType, destinationType);
var func = _configurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(sourceType, destinationType), types));
var options = new ObjectMappingOperationOptions(_serviceCtor);
opts(options);
options.BeforeMapAction(source, destination);
var context = new ResolutionContext(options, this);
destination = func(source, destination, context);
options.AfterMapAction(source, destination);
return destination;
}
object IRuntimeMapper.Map(object source, object destination, Type sourceType, Type destinationType, ResolutionContext context)
{
var types = TypePair.Create(source, destination, sourceType, destinationType);
var func = _configurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(sourceType, destinationType), types));
return func(source, destination, context);
}
TDestination IRuntimeMapper.Map<TSource, TDestination>(TSource source, TDestination destination, ResolutionContext context)
{
var types = TypePair.Create(source, destination, typeof(TSource), typeof(TDestination));
var func = _configurationProvider.GetMapperFunc<TSource, TDestination>(types);
return func(source, destination, context);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Analytics
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.DataLake;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// Creates an Azure Data Lake Analytics job client.
/// </summary>
public partial class DataLakeAnalyticsJobManagementClient : ServiceClient<DataLakeAnalyticsJobManagementClient>, IDataLakeAnalyticsJobManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
internal string BaseUri {get; set;}
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Client Api Version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets the DNS suffix used as the base for all Azure Data Lake Analytics Job
/// service requests.
/// </summary>
public string AdlaJobDnsSuffix { get; set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IJobOperations.
/// </summary>
public virtual IJobOperations Job { get; private set; }
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsJobManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected DataLakeAnalyticsJobManagementClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsJobManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected DataLakeAnalyticsJobManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsJobManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DataLakeAnalyticsJobManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsJobManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DataLakeAnalyticsJobManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
Job = new JobOperations(this);
BaseUri = "https://{accountName}.{adlaJobDnsSuffix}";
ApiVersion = "2016-11-01";
AdlaJobDnsSuffix = "azuredatalakeanalytics.net";
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<JobProperties>("type"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<JobProperties>("type"));
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Xml;
using System.IO;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
namespace NUnitLite
{
/// <summary>
/// NUnit2XmlOutputWriter is able to create an XML file representing
/// the result of a test run in NUnit 2.x format.
/// </summary>
public class NUnit2XmlOutputWriter : OutputWriter
{
private XmlWriter xmlWriter;
/// <summary>
/// Write info about a test
/// </summary>
/// <param name="test">The test</param>
/// <param name="writer">A TextWriter</param>
public override void WriteTestFile(ITest test, TextWriter writer)
{
throw new NotImplementedException("Explore test output is not supported by the NUnit2 format.");
}
/// <summary>
/// Writes the result of a test run to a specified TextWriter.
/// </summary>
/// <param name="result">The test result for the run</param>
/// <param name="writer">The TextWriter to which the xml will be written</param>
/// <param name="runSettings"></param>
/// <param name="filter"></param>
public override void WriteResultFile(ITestResult result, TextWriter writer, IDictionary<string, object> runSettings, TestFilter filter)
{
var settings = new XmlWriterSettings { Indent = true };
using (var xmlWriter = XmlWriter.Create(writer, settings))
{
WriteXmlOutput(result, xmlWriter);
}
}
private void WriteXmlOutput(ITestResult result, XmlWriter xmlWriter)
{
this.xmlWriter = xmlWriter;
InitializeXmlFile(result);
WriteResultElement(result);
TerminateXmlFile();
}
private void InitializeXmlFile(ITestResult result)
{
ResultSummary summary = new ResultSummary(result);
xmlWriter.WriteStartDocument(false);
xmlWriter.WriteComment("This file represents the results of running a test suite");
xmlWriter.WriteStartElement("test-results");
xmlWriter.WriteAttributeString("name", result.FullName);
xmlWriter.WriteAttributeString("total", summary.TestCount.ToString());
xmlWriter.WriteAttributeString("errors", summary.ErrorCount.ToString());
xmlWriter.WriteAttributeString("failures", summary.FailureCount.ToString());
xmlWriter.WriteAttributeString("not-run", summary.NotRunCount.ToString());
xmlWriter.WriteAttributeString("inconclusive", summary.InconclusiveCount.ToString());
xmlWriter.WriteAttributeString("ignored", summary.IgnoreCount.ToString());
xmlWriter.WriteAttributeString("skipped", summary.SkipCount.ToString());
xmlWriter.WriteAttributeString("invalid", summary.InvalidCount.ToString());
xmlWriter.WriteAttributeString("date", result.StartTime.ToString("yyyy-MM-dd"));
xmlWriter.WriteAttributeString("time", result.StartTime.ToString("HH:mm:ss"));
WriteEnvironment();
WriteCultureInfo();
}
private void WriteCultureInfo()
{
xmlWriter.WriteStartElement("culture-info");
xmlWriter.WriteAttributeString("current-culture",
CultureInfo.CurrentCulture.ToString());
xmlWriter.WriteAttributeString("current-uiculture",
CultureInfo.CurrentUICulture.ToString());
xmlWriter.WriteEndElement();
}
private void WriteEnvironment()
{
xmlWriter.WriteStartElement("environment");
var assemblyName = AssemblyHelper.GetAssemblyName(typeof(NUnit2XmlOutputWriter).GetTypeInfo().Assembly);
xmlWriter.WriteAttributeString("nunit-version",
assemblyName.Version.ToString());
xmlWriter.WriteAttributeString("clr-version",
Environment.Version.ToString());
#if NETSTANDARD2_0
xmlWriter.WriteAttributeString("os-version",
System.Runtime.InteropServices.RuntimeInformation.OSDescription);
#else
xmlWriter.WriteAttributeString("os-version",
OSPlatform.CurrentPlatform.ToString());
#endif
xmlWriter.WriteAttributeString("platform",
Environment.OSVersion.Platform.ToString());
xmlWriter.WriteAttributeString("cwd",
Directory.GetCurrentDirectory());
xmlWriter.WriteAttributeString("machine-name",
Environment.MachineName);
xmlWriter.WriteAttributeString("user",
Environment.UserName);
xmlWriter.WriteAttributeString("user-domain",
Environment.UserDomainName);
xmlWriter.WriteEndElement();
}
private void WriteResultElement(ITestResult result)
{
StartTestElement(result);
WriteCategories(result);
WriteProperties(result);
switch (result.ResultState.Status)
{
case TestStatus.Skipped:
if (result.Message != null)
WriteReasonElement(result.Message);
break;
case TestStatus.Failed:
WriteFailureElement(result.Message, result.StackTrace);
break;
}
if (result.Test is TestSuite)
WriteChildResults(result);
xmlWriter.WriteEndElement(); // test element
}
private void TerminateXmlFile()
{
xmlWriter.WriteEndElement(); // test-results
xmlWriter.WriteEndDocument();
xmlWriter.Flush();
((IDisposable)xmlWriter).Dispose();
}
#region Element Creation Helpers
private void StartTestElement(ITestResult result)
{
ITest test = result.Test;
TestSuite suite = test as TestSuite;
if (suite != null)
{
xmlWriter.WriteStartElement("test-suite");
xmlWriter.WriteAttributeString("type", suite.TestType == "ParameterizedMethod" ? "ParameterizedTest" : suite.TestType);
xmlWriter.WriteAttributeString("name", suite.TestType == "Assembly" || suite.TestType == "Project"
? result.Test.FullName
: result.Test.Name);
}
else
{
xmlWriter.WriteStartElement("test-case");
xmlWriter.WriteAttributeString("name", result.Name);
}
if (test.Properties.ContainsKey(PropertyNames.Description))
{
string description = (string)test.Properties.Get(PropertyNames.Description);
xmlWriter.WriteAttributeString("description", description);
}
TestStatus status = result.ResultState.Status;
string translatedResult = TranslateResult(result.ResultState);
if (status != TestStatus.Skipped)
{
xmlWriter.WriteAttributeString("executed", "True");
xmlWriter.WriteAttributeString("result", translatedResult);
xmlWriter.WriteAttributeString("success", status == TestStatus.Passed ? "True" : "False");
xmlWriter.WriteAttributeString("time", result.Duration.ToString("0.000", NumberFormatInfo.InvariantInfo));
xmlWriter.WriteAttributeString("asserts", result.AssertCount.ToString());
}
else
{
xmlWriter.WriteAttributeString("executed", "False");
xmlWriter.WriteAttributeString("result", translatedResult);
}
}
private string TranslateResult(ResultState resultState)
{
switch (resultState.Status)
{
default:
case TestStatus.Passed:
return "Success";
case TestStatus.Inconclusive:
return "Inconclusive";
case TestStatus.Failed:
switch (resultState.Label)
{
case "Error":
case "Cancelled":
return resultState.Label;
default:
return "Failure";
}
case TestStatus.Skipped:
switch (resultState.Label)
{
case "Ignored":
return "Ignored";
case "Invalid":
return "NotRunnable";
default:
return "Skipped";
}
}
}
private void WriteCategories(ITestResult result)
{
IPropertyBag properties = result.Test.Properties;
if (properties.ContainsKey(PropertyNames.Category))
{
xmlWriter.WriteStartElement("categories");
foreach (string category in properties[PropertyNames.Category])
{
xmlWriter.WriteStartElement("category");
xmlWriter.WriteAttributeString("name", category);
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
}
private void WriteProperties(ITestResult result)
{
IPropertyBag properties = result.Test.Properties;
int nprops = 0;
foreach (string key in properties.Keys)
{
if (key != PropertyNames.Category)
{
if (nprops++ == 0)
xmlWriter.WriteStartElement("properties");
foreach (object prop in properties[key])
{
xmlWriter.WriteStartElement("property");
xmlWriter.WriteAttributeString("name", key);
xmlWriter.WriteAttributeString("value", prop.ToString());
xmlWriter.WriteEndElement();
}
}
}
if (nprops > 0)
xmlWriter.WriteEndElement();
}
private void WriteReasonElement(string message)
{
xmlWriter.WriteStartElement("reason");
xmlWriter.WriteStartElement("message");
WriteCData(message);
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
}
private void WriteFailureElement(string message, string stackTrace)
{
xmlWriter.WriteStartElement("failure");
xmlWriter.WriteStartElement("message");
WriteCData(message);
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("stack-trace");
if (stackTrace != null)
WriteCData(stackTrace);
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
}
private void WriteChildResults(ITestResult result)
{
xmlWriter.WriteStartElement("results");
foreach (ITestResult childResult in result.Children)
WriteResultElement(childResult);
xmlWriter.WriteEndElement();
}
#endregion
#region Output Helpers
///// <summary>
///// Makes string safe for xml parsing, replacing control chars with '?'
///// </summary>
///// <param name="encodedString">string to make safe</param>
///// <returns>xml safe string</returns>
//private static string CharacterSafeString(string encodedString)
//{
// /*The default code page for the system will be used.
// Since all code pages use the same lower 128 bytes, this should be sufficient
// for finding unprintable control characters that make the xslt processor error.
// We use characters encoded by the default code page to avoid mistaking bytes as
// individual characters on non-latin code pages.*/
// char[] encodedChars = System.Text.Encoding.Default.GetChars(System.Text.Encoding.Default.GetBytes(encodedString));
// System.Collections.ArrayList pos = new System.Collections.ArrayList();
// for (int x = 0; x < encodedChars.Length; x++)
// {
// char currentChar = encodedChars[x];
// //unprintable characters are below 0x20 in Unicode tables
// //some control characters are acceptable. (carriage return 0x0D, line feed 0x0A, horizontal tab 0x09)
// if (currentChar < 32 && (currentChar != 9 && currentChar != 10 && currentChar != 13))
// {
// //save the array index for later replacement.
// pos.Add(x);
// }
// }
// foreach (int index in pos)
// {
// encodedChars[index] = '?';//replace unprintable control characters with ?(3F)
// }
// return System.Text.Encoding.Default.GetString(System.Text.Encoding.Default.GetBytes(encodedChars));
//}
private void WriteCData(string text)
{
int start = 0;
while (true)
{
int illegal = text.IndexOf("]]>", start, StringComparison.Ordinal);
if (illegal < 0)
break;
xmlWriter.WriteCData(text.Substring(start, illegal - start + 2));
start = illegal + 2;
if (start >= text.Length)
return;
}
if (start > 0)
xmlWriter.WriteCData(text.Substring(start));
else
xmlWriter.WriteCData(text);
}
#endregion
}
}
| |
/*
* Exchange Web Services Managed API
*
* 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.
*/
namespace Microsoft.Exchange.WebServices.Autodiscover
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Xml;
using Microsoft.Exchange.WebServices.Data;
/// <summary>
/// Represents a GetDomainSettings request.
/// </summary>
internal class GetDomainSettingsRequest : AutodiscoverRequest
{
/// <summary>
/// Action Uri of Autodiscover.GetDomainSettings method.
/// </summary>
private const string GetDomainSettingsActionUri = EwsUtilities.AutodiscoverSoapNamespace + "/Autodiscover/GetDomainSettings";
private List<string> domains;
private List<DomainSettingName> settings;
private ExchangeVersion? requestedVersion;
/// <summary>
/// Initializes a new instance of the <see cref="GetDomainSettingsRequest"/> class.
/// </summary>
/// <param name="service">Autodiscover service associated with this request.</param>
/// <param name="url">URL of Autodiscover service.</param>
internal GetDomainSettingsRequest(AutodiscoverService service, Uri url)
: base(service, url)
{
}
/// <summary>
/// Validates the request.
/// </summary>
internal override void Validate()
{
base.Validate();
EwsUtilities.ValidateParam(this.Domains, "domains");
EwsUtilities.ValidateParam(this.Settings, "settings");
if (this.Settings.Count == 0)
{
throw new ServiceValidationException(Strings.InvalidAutodiscoverSettingsCount);
}
if (domains.Count == 0)
{
throw new ServiceValidationException(Strings.InvalidAutodiscoverDomainsCount);
}
foreach (string domain in this.domains)
{
if (string.IsNullOrEmpty(domain))
{
throw new ServiceValidationException(Strings.InvalidAutodiscoverDomain);
}
}
}
/// <summary>
/// Executes this instance.
/// </summary>
/// <returns></returns>
internal GetDomainSettingsResponseCollection Execute()
{
GetDomainSettingsResponseCollection responses = (GetDomainSettingsResponseCollection)this.InternalExecute();
if (responses.ErrorCode == AutodiscoverErrorCode.NoError)
{
this.PostProcessResponses(responses);
}
return responses;
}
/// <summary>
/// Post-process responses to GetDomainSettings.
/// </summary>
/// <param name="responses">The GetDomainSettings responses.</param>
private void PostProcessResponses(GetDomainSettingsResponseCollection responses)
{
// Note:The response collection may not include all of the requested domains if the request has been throttled.
for (int index = 0; index < responses.Count; index++)
{
responses[index].Domain = this.Domains[index];
}
}
/// <summary>
/// Gets the name of the request XML element.
/// </summary>
/// <returns>Request XML element name.</returns>
internal override string GetRequestXmlElementName()
{
return XmlElementNames.GetDomainSettingsRequestMessage;
}
/// <summary>
/// Gets the name of the response XML element.
/// </summary>
/// <returns>Response XML element name.</returns>
internal override string GetResponseXmlElementName()
{
return XmlElementNames.GetDomainSettingsResponseMessage;
}
/// <summary>
/// Gets the WS-Addressing action name.
/// </summary>
/// <returns>WS-Addressing action name.</returns>
internal override string GetWsAddressingActionName()
{
return GetDomainSettingsActionUri;
}
/// <summary>
/// Creates the service response.
/// </summary>
/// <returns>AutodiscoverResponse</returns>
internal override AutodiscoverResponse CreateServiceResponse()
{
return new GetDomainSettingsResponseCollection();
}
/// <summary>
/// Writes the attributes to XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteAttributesToXml(EwsServiceXmlWriter writer)
{
writer.WriteAttributeValue(
"xmlns",
EwsUtilities.AutodiscoverSoapNamespacePrefix,
EwsUtilities.AutodiscoverSoapNamespace);
}
/// <summary>
/// Writes request to XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteElementsToXml(EwsServiceXmlWriter writer)
{
writer.WriteStartElement(XmlNamespace.Autodiscover, XmlElementNames.Request);
writer.WriteStartElement(XmlNamespace.Autodiscover, XmlElementNames.Domains);
foreach (string domain in this.Domains)
{
if (!string.IsNullOrEmpty(domain))
{
writer.WriteElementValue(
XmlNamespace.Autodiscover,
XmlElementNames.Domain,
domain);
}
}
writer.WriteEndElement(); // Domains
writer.WriteStartElement(XmlNamespace.Autodiscover, XmlElementNames.RequestedSettings);
foreach (DomainSettingName setting in settings)
{
writer.WriteElementValue(
XmlNamespace.Autodiscover,
XmlElementNames.Setting,
setting);
}
writer.WriteEndElement(); // RequestedSettings
if (this.requestedVersion.HasValue)
{
writer.WriteElementValue(XmlNamespace.Autodiscover, XmlElementNames.RequestedVersion, this.requestedVersion.Value);
}
writer.WriteEndElement(); // Request
}
/// <summary>
/// Gets or sets the domains.
/// </summary>
internal List<string> Domains
{
get { return domains; }
set { domains = value; }
}
/// <summary>
/// Gets or sets the settings.
/// </summary>
internal List<DomainSettingName> Settings
{
get { return settings; }
set { settings = value; }
}
/// <summary>
/// Gets or sets the RequestedVersion.
/// </summary>
internal ExchangeVersion? RequestedVersion
{
get { return requestedVersion; }
set { requestedVersion = value; }
}
}
}
| |
/*
* Copyright (C) Sony Computer Entertainment America LLC.
* All Rights Reserved.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Net;
using System.Xml;
using Sce.Atf;
using Sce.Atf.Applications;
using Sce.Atf.Controls.PropertyEditing;
using Sce.Sled.Shared;
using Sce.Sled.Shared.Plugin;
using Sce.Sled.Shared.Services;
namespace Sce.Sled.Net.Tcp
{
[Export(typeof(IInitializable))]
[Export(typeof(ISledNetworkPlugin))]
[Export(typeof(SledNetPluginTcp))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class SledNetPluginTcp : IInitializable, ISledNetworkPlugin
{
[ImportingConstructor]
public SledNetPluginTcp(ISettingsService settingsService)
{
// From AssemblyInfo.cs in this .dll
PluginGuid = new Guid("7cdb0b45-9c29-4412-8bcd-1413b058611c");
// Persist settings
settingsService.RegisterSettings(
this,
new BoundPropertyDescriptor(
this,
() => PersistedSettings,
"TCP Settings",
"Network",
"TCP Settings"));
// Add some user settings to edit > preferences
settingsService.RegisterUserSettings(
"Network",
new BoundPropertyDescriptor(
this,
() => DefaultPortUserSetting,
"TCP Default Port",
null,
"Default TCP port"));
}
#region IInitializable Interface
void IInitializable.Initialize()
{
// Keep this here
}
#endregion
#region ISledNetworkPlugin Interface
public void Connect(ISledTarget target)
{
var tcpTarget = target as SledTcpTarget;
if (tcpTarget == null)
throw new InvalidOperationException("target is not a TcpTarget");
m_socket = new TargetTcpSocket(1000);
m_socket.Connected += SocketConnected;
m_socket.Disconnected += SocketDisconnected;
m_socket.DataReady += SocketDataReady;
m_socket.UnHandledException += SocketUnHandledException;
try
{
m_socket.Connect(tcpTarget);
}
catch (Exception ex)
{
if (UnHandledExceptionEvent != null)
UnHandledExceptionEvent(this, ex);
}
}
public bool IsConnected
{
get
{
return m_socket != null && m_socket.IsConnected;
}
}
public void Disconnect()
{
try
{
m_socket.Disconnect();
}
catch (Exception ex)
{
if (UnHandledExceptionEvent != null)
UnHandledExceptionEvent(this, ex);
}
finally
{
if (m_socket != null)
{
m_socket.Connected -= SocketConnected;
m_socket.Disconnected -= SocketDisconnected;
m_socket.DataReady -= SocketDataReady;
m_socket.UnHandledException -= SocketUnHandledException;
m_socket = null;
}
}
}
public int Send(byte[] buffer)
{
return Send(buffer, buffer.Length);
}
public int Send(byte[] buffer, int length)
{
var iLen = length;
try
{
m_socket.Send(buffer, length);
}
catch (Exception ex)
{
if (UnHandledExceptionEvent != null)
UnHandledExceptionEvent(this, ex);
iLen = -1;
}
return iLen;
}
public void Dispose()
{
if (IsConnected)
Disconnect();
}
public event ConnectionHandler ConnectedEvent;
public event ConnectionHandler DisconnectedEvent;
public event DataReadyHandler DataReadyEvent;
public event UnHandledExceptionHandler UnHandledExceptionEvent;
public string Name
{
get { return PluginName; }
}
public string Protocol
{
get { return PluginProtocol; }
}
public SledNetworkPluginTargetFormSettings CreateSettingsControl(ISledTarget target)
{
return new SledTcpSettingsControl(target);
}
public ISledTarget CreateAndSetup(string name, IPEndPoint endPoint, params object[] settings)
{
var target = new SledTcpTarget(name, endPoint, this, false);
return target;
}
public ISledTarget[] ImportedTargets
{
get
{
var lstTargets =
new List<ISledTarget>
{
new SledTcpTarget(
"localhost",
new IPEndPoint(IPAddress.Loopback, DefaultPort),
this,
true)
};
return lstTargets.ToArray();
}
}
public Guid PluginGuid { get; private set; }
#endregion
#region ISledNetworkPluginPersistedSettings
public bool Save(ISledTarget target, XmlElement elem)
{
if (elem == null)
return false;
var tcpTarget = target as SledTcpTarget;
if (tcpTarget == null)
return false;
elem.SetAttribute("name", tcpTarget.Name);
elem.SetAttribute("ipaddress", tcpTarget.EndPoint.Address.ToString());
elem.SetAttribute("port", tcpTarget.EndPoint.Port.ToString());
return true;
}
public bool Load(out ISledTarget target, XmlElement elem)
{
target = null;
if (elem == null)
return false;
var bSuccessful = false;
try
{
var name = elem.GetAttribute("name");
if (string.IsNullOrEmpty(name))
return false;
var ipaddress = elem.GetAttribute("ipaddress");
if (string.IsNullOrEmpty(ipaddress))
return false;
IPAddress ipAddr;
if (!IPAddress.TryParse(ipaddress, out ipAddr))
return false;
int port;
if (!int.TryParse(elem.GetAttribute("port"), out port))
return false;
target = CreateAndSetup(name, new IPEndPoint(ipAddr, port), null);
bSuccessful = target != null;
}
catch (Exception ex)
{
SledOutDevice.OutLineDebug(SledMessageType.Error, "{0}: Exception loading settings: {1}", this, ex.Message);
target = null;
}
return bSuccessful;
}
#endregion
#region Persisted Settings
public string PersistedSettings
{
get
{
// Generate Xml string to contain the Mru project list
var xmlDoc = new XmlDocument();
xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes"));
var root = xmlDoc.CreateElement(PersistedSettingsElement);
xmlDoc.AppendChild(root);
try
{
var elem = xmlDoc.CreateElement(PersistedSettingsTcpElement);
elem.SetAttribute(PersistedSettingsTcpAttribute, DefaultPort.ToString());
root.AppendChild(elem);
if (xmlDoc.DocumentElement == null)
xmlDoc.RemoveAll();
else if (xmlDoc.DocumentElement.ChildNodes.Count == 0)
xmlDoc.RemoveAll();
}
catch (Exception ex)
{
xmlDoc.RemoveAll();
const string szSetting = PersistedSettingsElement;
SledOutDevice.OutLine(SledMessageType.Info, "Exception saving {0} settings: {1}", szSetting, ex.Message);
}
return xmlDoc.InnerXml.Trim();
}
set
{
try
{
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(value);
if (xmlDoc.DocumentElement == null)
return;
var nodes = xmlDoc.DocumentElement.SelectNodes(PersistedSettingsTcpElement);
if ((nodes == null) || (nodes.Count == 0))
return;
foreach (XmlElement elem in nodes)
{
if (!elem.HasAttribute(PersistedSettingsTcpAttribute))
continue;
var szPort = elem.GetAttribute(PersistedSettingsTcpAttribute);
int iPort;
if (int.TryParse(szPort, out iPort))
DefaultPort = iPort;
}
}
catch (Exception ex)
{
const string szSetting = PersistedSettingsElement;
SledOutDevice.OutLine(SledMessageType.Info, "Exception loading {0} settings: {1}", szSetting, ex.Message);
}
}
}
public int DefaultPortUserSetting
{
get { return DefaultPort; }
set { DefaultPort = value; }
}
public static int DefaultPort
{
get { return s_defaultPort; }
set { s_defaultPort = value; }
}
private const string PersistedSettingsElement = "NetworkSettings";
private const string PersistedSettingsTcpElement = "tcp";
private const string PersistedSettingsTcpAttribute = "default_port";
private static int s_defaultPort = 11111;
#endregion
#region Socket Events
private void SocketConnected(object sender, ISledTarget target)
{
if (ConnectedEvent != null)
ConnectedEvent(this, target);
}
private void SocketDisconnected(object sender, ISledTarget target)
{
if (DisconnectedEvent != null)
DisconnectedEvent(this, target);
}
private void SocketDataReady(object sender, byte[] buffer)
{
if (DataReadyEvent != null)
DataReadyEvent(this, buffer);
}
private void SocketUnHandledException(object sender, Exception ex)
{
if (UnHandledExceptionEvent != null)
UnHandledExceptionEvent(this, ex);
}
#endregion
private TargetTcpSocket m_socket;
private const string PluginName = "SLED Tcp Network Plugin";
private const string PluginProtocol = "TCP";
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using System.Threading.Tests;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Threading.Threads.Tests
{
public class DummyClass
{
public static string HostRunnerTest = RemoteExecutor.HostRunner;
}
public static partial class ThreadTests
{
private const int UnexpectedTimeoutMilliseconds = ThreadTestHelpers.UnexpectedTimeoutMilliseconds;
private const int ExpectedTimeoutMilliseconds = ThreadTestHelpers.ExpectedTimeoutMilliseconds;
[Fact]
public static void ConstructorTest()
{
const int SmallStackSizeBytes = 64 << 10; // 64 KB, currently accepted in all supported platforms, and is the PAL minimum
const int LargeStackSizeBytes = 16 << 20; // 16 MB
int pageSizeBytes = Environment.SystemPageSize;
// Leave some buffer for other data structures that will take some of the allocated stack space
int stackSizeBufferBytes = pageSizeBytes * 16;
Action<Thread> startThreadAndJoin =
t =>
{
t.IsBackground = true;
t.Start();
Assert.True(t.Join(UnexpectedTimeoutMilliseconds));
};
Action<int> verifyStackSize =
stackSizeBytes =>
{
// Try to stack-allocate an array to verify that close to the expected amount of stack space is actually
// available
int bufferSizeBytes = Math.Max(SmallStackSizeBytes / 4, stackSizeBytes - stackSizeBufferBytes);
unsafe
{
byte* buffer = stackalloc byte[bufferSizeBytes];
for (int i = 0; i < bufferSizeBytes; i += pageSizeBytes)
{
Volatile.Write(ref buffer[i], 0xff);
}
Volatile.Write(ref buffer[bufferSizeBytes - 1], 0xff);
}
};
startThreadAndJoin(new Thread(() => verifyStackSize(0)));
startThreadAndJoin(new Thread(() => verifyStackSize(0), 0));
startThreadAndJoin(new Thread(() => verifyStackSize(SmallStackSizeBytes), SmallStackSizeBytes));
startThreadAndJoin(new Thread(() => verifyStackSize(LargeStackSizeBytes), LargeStackSizeBytes));
startThreadAndJoin(new Thread(state => verifyStackSize(0)));
startThreadAndJoin(new Thread(state => verifyStackSize(0), 0));
startThreadAndJoin(new Thread(state => verifyStackSize(SmallStackSizeBytes), SmallStackSizeBytes));
startThreadAndJoin(new Thread(state => verifyStackSize(LargeStackSizeBytes), LargeStackSizeBytes));
Assert.Throws<ArgumentNullException>(() => new Thread((ThreadStart)null));
Assert.Throws<ArgumentNullException>(() => new Thread((ThreadStart)null, 0));
Assert.Throws<ArgumentNullException>(() => new Thread((ParameterizedThreadStart)null));
Assert.Throws<ArgumentNullException>(() => new Thread((ParameterizedThreadStart)null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => new Thread(() => { }, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new Thread(state => { }, -1));
}
public static IEnumerable<object[]> ApartmentStateTest_MemberData()
{
yield return
new object[]
{
#pragma warning disable 618 // Obsolete members
new Func<Thread, ApartmentState>(t => t.ApartmentState),
#pragma warning restore 618 // Obsolete members
new Func<Thread, ApartmentState, int>(
(t, value) =>
{
try
{
#pragma warning disable 618 // Obsolete members
t.ApartmentState = value;
#pragma warning restore 618 // Obsolete members
return 0;
}
catch (ArgumentOutOfRangeException)
{
return 1;
}
catch (PlatformNotSupportedException)
{
return 3;
}
}),
0
};
yield return
new object[]
{
new Func<Thread, ApartmentState>(t => t.GetApartmentState()),
new Func<Thread, ApartmentState, int>(
(t, value) =>
{
try
{
t.SetApartmentState(value);
return 0;
}
catch (ArgumentOutOfRangeException)
{
return 1;
}
catch (InvalidOperationException)
{
return 2;
}
catch (PlatformNotSupportedException)
{
return 3;
}
}),
1
};
yield return
new object[]
{
new Func<Thread, ApartmentState>(t => t.GetApartmentState()),
new Func<Thread, ApartmentState, int>(
(t, value) =>
{
try
{
return t.TrySetApartmentState(value) ? 0 : 2;
}
catch (ArgumentOutOfRangeException)
{
return 1;
}
catch (PlatformNotSupportedException)
{
return 3;
}
}),
2
};
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))]
[InlineData("STAMain.exe", "GetApartmentStateTest")]
[InlineData("STAMain.exe", "SetApartmentStateTest")]
[InlineData("STAMain.exe", "WaitAllNotSupportedOnSta_Test0")]
[InlineData("STAMain.exe", "WaitAllNotSupportedOnSta_Test1")]
[InlineData("MTAMain.exe", "GetApartmentStateTest")]
[InlineData("MTAMain.exe", "SetApartmentStateTest")]
[InlineData("DefaultApartmentStateMain.exe", "GetApartmentStateTest")]
[InlineData("DefaultApartmentStateMain.exe", "SetApartmentStateTest")]
public static void ApartmentState_AttributePresent(string appName, string testName)
{
var psi = new ProcessStartInfo();
psi.FileName = DummyClass.HostRunnerTest;
psi.Arguments = $"{appName} {testName}";
using (Process p = Process.Start(psi))
{
p.WaitForExit();
Assert.Equal(PlatformDetection.IsWindows ? 0 : 2, p.ExitCode);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public static void ApartmentState_NoAttributePresent_DefaultState_Windows()
{
RemoteExecutor.Invoke(() =>
{
Assert.Equal(ApartmentState.MTA, Thread.CurrentThread.GetApartmentState());
Assert.Throws<InvalidOperationException>(() => Thread.CurrentThread.SetApartmentState(ApartmentState.STA));
Thread.CurrentThread.SetApartmentState(ApartmentState.MTA);
}).Dispose();
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public static void ApartmentState_NoAttributePresent_DefaultState_Unix()
{
RemoteExecutor.Invoke(() =>
{
Assert.Equal(ApartmentState.Unknown, Thread.CurrentThread.GetApartmentState());
Assert.Throws<PlatformNotSupportedException>(() => Thread.CurrentThread.SetApartmentState(ApartmentState.MTA));
}).Dispose();
}
// Thread is always initialized as MTA irrespective of the attribute present.
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsWindowsNanoServer))]
public static void ApartmentState_NoAttributePresent_DefaultState_Nano()
{
RemoteExecutor.Invoke(() =>
{
Assert.Throws<InvalidOperationException>(() => Thread.CurrentThread.SetApartmentState(ApartmentState.STA));
Assert.Equal(ApartmentState.MTA, Thread.CurrentThread.GetApartmentState());
}).Dispose();
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public static void ApartmentState_NoAttributePresent_STA_Unix()
{
RemoteExecutor.Invoke(() =>
{
Assert.Throws<PlatformNotSupportedException>(() => Thread.CurrentThread.SetApartmentState(ApartmentState.STA));
}).Dispose();
}
[Theory]
[MemberData(nameof(ApartmentStateTest_MemberData))]
[PlatformSpecific(TestPlatforms.Windows)] // Expected behavior differs on Unix and Windows
public static void GetSetApartmentStateTest_ChangeAfterThreadStarted_Windows(
Func<Thread, ApartmentState> getApartmentState,
Func<Thread, ApartmentState, int> setApartmentState,
int setType /* 0 = ApartmentState setter, 1 = SetApartmentState, 2 = TrySetApartmentState */)
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
var t = Thread.CurrentThread;
Assert.Equal(1, setApartmentState(t, ApartmentState.STA - 1));
Assert.Equal(1, setApartmentState(t, ApartmentState.Unknown + 1));
Assert.Equal(ApartmentState.MTA, getApartmentState(t));
Assert.Equal(0, setApartmentState(t, ApartmentState.MTA));
Assert.Equal(ApartmentState.MTA, getApartmentState(t));
Assert.Equal(setType == 0 ? 0 : 2, setApartmentState(t, ApartmentState.STA)); // cannot be changed after thread is started
Assert.Equal(ApartmentState.MTA, getApartmentState(t));
});
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))]
[MemberData(nameof(ApartmentStateTest_MemberData))]
[PlatformSpecific(TestPlatforms.Windows)] // Expected behavior differs on Unix and Windows
public static void ApartmentStateTest_ChangeBeforeThreadStarted_Windows(
Func<Thread, ApartmentState> getApartmentState,
Func<Thread, ApartmentState, int> setApartmentState,
int setType /* 0 = ApartmentState setter, 1 = SetApartmentState, 2 = TrySetApartmentState */)
{
ApartmentState apartmentStateInThread = ApartmentState.Unknown;
Thread t = null;
t = new Thread(() => apartmentStateInThread = getApartmentState(t));
t.IsBackground = true;
Assert.Equal(0, setApartmentState(t, ApartmentState.STA));
Assert.Equal(ApartmentState.STA, getApartmentState(t));
Assert.Equal(setType == 0 ? 0 : 2, setApartmentState(t, ApartmentState.MTA)); // cannot be changed more than once
Assert.Equal(ApartmentState.STA, getApartmentState(t));
t.Start();
Assert.True(t.Join(UnexpectedTimeoutMilliseconds));
Assert.Equal(ApartmentState.STA, apartmentStateInThread);
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWindowsNanoServer))]
[MemberData(nameof(ApartmentStateTest_MemberData))]
public static void ApartmentStateTest_ChangeBeforeThreadStarted_Windows_Nano_Server(
Func<Thread, ApartmentState> getApartmentState,
Func<Thread, ApartmentState, int> setApartmentState,
int setType /* 0 = ApartmentState setter, 1 = SetApartmentState, 2 = TrySetApartmentState */)
{
ApartmentState apartmentStateInThread = ApartmentState.Unknown;
Thread t = null;
t = new Thread(() => apartmentStateInThread = getApartmentState(t));
t.IsBackground = true;
Assert.Equal(0, setApartmentState(t, ApartmentState.STA));
Assert.Equal(ApartmentState.STA, getApartmentState(t));
Assert.Equal(setType == 0 ? 0 : 2, setApartmentState(t, ApartmentState.MTA)); // cannot be changed more than once
Assert.Equal(ApartmentState.STA, getApartmentState(t));
Assert.Throws<ThreadStartException>(() => t.Start()); // Windows Nano Server does not support starting threads in the STA.
}
[Theory]
[MemberData(nameof(ApartmentStateTest_MemberData))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior differs on Unix and Windows
public static void ApartmentStateTest_Unix(
Func<Thread, ApartmentState> getApartmentState,
Func<Thread, ApartmentState, int> setApartmentState,
int setType /* 0 = ApartmentState setter, 1 = SetApartmentState, 2 = TrySetApartmentState */)
{
var t = new Thread(() => { });
Assert.Equal(ApartmentState.Unknown, getApartmentState(t));
Assert.Equal(0, setApartmentState(t, ApartmentState.Unknown));
int expectedFailure;
switch (setType)
{
case 0:
expectedFailure = 0; // ApartmentState setter - no exception, but value does not change
break;
case 1:
expectedFailure = 3; // SetApartmentState - InvalidOperationException
break;
default:
expectedFailure = 2; // TrySetApartmentState - returns false
break;
}
Assert.Equal(expectedFailure, setApartmentState(t, ApartmentState.STA));
Assert.Equal(expectedFailure, setApartmentState(t, ApartmentState.MTA));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Mono)]
public static void CurrentCultureTest_DifferentThread()
{
CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
CultureInfo uiCulture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
ExceptionDispatchInfo exceptionFromThread = null;
var t = new Thread(() => {
try
{
Assert.Same(culture, Thread.CurrentThread.CurrentCulture);
Assert.Same(uiCulture, Thread.CurrentThread.CurrentUICulture);
}
catch (Exception e)
{
exceptionFromThread = ExceptionDispatchInfo.Capture(e);
}
});
// We allow setting thread culture of unstarted threads to ease .NET Framework migration. It is pattern used
// in real world .NET Framework apps.
t.CurrentCulture = culture;
t.CurrentUICulture = uiCulture;
// Cannot access culture properties on a thread object from a different thread
Assert.Throws<InvalidOperationException>(() => t.CurrentCulture);
Assert.Throws<InvalidOperationException>(() => t.CurrentUICulture);
t.Start();
// Cannot access culture properties on a thread object from a different thread once the thread is started
// .NET Framework allowed this, but it did not work reliably. .NET Core throws instead.
Assert.Throws<InvalidOperationException>(() => { t.CurrentCulture = culture; });
Assert.Throws<InvalidOperationException>(() => { t.CurrentUICulture = uiCulture; });
Assert.Throws<InvalidOperationException>(() => t.CurrentCulture);
Assert.Throws<InvalidOperationException>(() => t.CurrentUICulture);
t.Join();
exceptionFromThread?.Throw();
}
[Fact]
public static void CurrentCultureTest()
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
var t = Thread.CurrentThread;
var originalCulture = CultureInfo.CurrentCulture;
var originalUICulture = CultureInfo.CurrentUICulture;
var otherCulture = CultureInfo.InvariantCulture;
// Culture properties return the same value as those on CultureInfo
Assert.Equal(originalCulture, t.CurrentCulture);
Assert.Equal(originalUICulture, t.CurrentUICulture);
try
{
// Changing culture properties on CultureInfo causes the values of properties on the current thread to change
CultureInfo.CurrentCulture = otherCulture;
CultureInfo.CurrentUICulture = otherCulture;
Assert.Equal(otherCulture, t.CurrentCulture);
Assert.Equal(otherCulture, t.CurrentUICulture);
// Changing culture properties on the current thread causes new values to be returned, and causes the values of
// properties on CultureInfo to change
t.CurrentCulture = originalCulture;
t.CurrentUICulture = originalUICulture;
Assert.Equal(originalCulture, t.CurrentCulture);
Assert.Equal(originalUICulture, t.CurrentUICulture);
Assert.Equal(originalCulture, CultureInfo.CurrentCulture);
Assert.Equal(originalUICulture, CultureInfo.CurrentUICulture);
}
finally
{
CultureInfo.CurrentCulture = originalCulture;
CultureInfo.CurrentUICulture = originalUICulture;
}
Assert.Throws<ArgumentNullException>(() => t.CurrentCulture = null);
Assert.Throws<ArgumentNullException>(() => t.CurrentUICulture = null);
});
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Mono)]
public static void CurrentPrincipalTest_SkipOnDesktopFramework()
{
ThreadTestHelpers.RunTestInBackgroundThread(() => Assert.Null(Thread.CurrentPrincipal));
}
[Fact]
public static void CurrentPrincipalTest()
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
var originalPrincipal = Thread.CurrentPrincipal;
var otherPrincipal =
new GenericPrincipal(new GenericIdentity(string.Empty, string.Empty), new string[] { string.Empty });
Thread.CurrentPrincipal = otherPrincipal;
Assert.Equal(otherPrincipal, Thread.CurrentPrincipal);
Thread.CurrentPrincipal = originalPrincipal;
Assert.Equal(originalPrincipal, Thread.CurrentPrincipal);
});
}
[Fact]
public static void CurrentPrincipalContextFlowTest()
{
ThreadTestHelpers.RunTestInBackgroundThread(async () =>
{
Thread.CurrentPrincipal = new ClaimsPrincipal();
await Task.Run(async() => {
Assert.IsType<ClaimsPrincipal>(Thread.CurrentPrincipal);
await Task.Run(async() =>
{
Assert.IsType<ClaimsPrincipal>(Thread.CurrentPrincipal);
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("name"), new string[0]);
await Task.Run(() =>
{
Assert.IsType<GenericPrincipal>(Thread.CurrentPrincipal);
});
Assert.IsType<GenericPrincipal>(Thread.CurrentPrincipal);
});
Assert.IsType<ClaimsPrincipal>(Thread.CurrentPrincipal);
});
Assert.IsType<ClaimsPrincipal>(Thread.CurrentPrincipal);
});
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Mono)]
public static void CurrentPrincipalContextFlowTest_NotFlow()
{
ThreadTestHelpers.RunTestInBackgroundThread(async () =>
{
Thread.CurrentPrincipal = new ClaimsPrincipal();
Task task;
using(ExecutionContext.SuppressFlow())
{
Assert.True(ExecutionContext.IsFlowSuppressed());
task = Task.Run(() =>
{
Assert.Null(Thread.CurrentPrincipal);
Assert.False(ExecutionContext.IsFlowSuppressed());
});
}
Assert.False(ExecutionContext.IsFlowSuppressed());
await task;
});
}
[Fact]
public static void CurrentPrincipal_SetNull()
{
// We run test on remote process because we need to set same principal policy
// On netfx default principal policy is PrincipalPolicy.UnauthenticatedPrincipal
RemoteExecutor.Invoke(() =>
{
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.NoPrincipal);
Assert.Null(Thread.CurrentPrincipal);
Thread.CurrentPrincipal = null;
Assert.Null(Thread.CurrentPrincipal);
Thread.CurrentPrincipal = new ClaimsPrincipal();
Assert.IsType<ClaimsPrincipal>(Thread.CurrentPrincipal);
Thread.CurrentPrincipal = null;
Assert.Null(Thread.CurrentPrincipal);
Thread.CurrentPrincipal = new ClaimsPrincipal();
Assert.IsType<ClaimsPrincipal>(Thread.CurrentPrincipal);
}).Dispose();
}
[Fact]
public static void CurrentThreadTest()
{
Thread otherThread = null;
var t = new Thread(() => otherThread = Thread.CurrentThread);
t.IsBackground = true;
t.Start();
Assert.True(t.Join(UnexpectedTimeoutMilliseconds));
Assert.Equal(t, otherThread);
var mainThread = Thread.CurrentThread;
Assert.NotNull(mainThread);
Assert.NotEqual(mainThread, otherThread);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Mono)]
public static void ExecutionContextTest()
{
ThreadTestHelpers.RunTestInBackgroundThread(
() => Assert.Equal(ExecutionContext.Capture(), Thread.CurrentThread.ExecutionContext));
}
[Fact]
public static void IsAliveTest()
{
var isAliveWhenRunning = false;
Thread t = null;
t = new Thread(() => isAliveWhenRunning = t.IsAlive);
t.IsBackground = true;
Assert.False(t.IsAlive);
t.Start();
Assert.True(t.Join(UnexpectedTimeoutMilliseconds));
Assert.True(isAliveWhenRunning);
Assert.False(t.IsAlive);
}
[Fact]
public static void IsBackgroundTest()
{
var t = new Thread(() => { });
Assert.False(t.IsBackground);
t.IsBackground = true;
Assert.True(t.IsBackground);
t.Start();
Assert.True(t.Join(UnexpectedTimeoutMilliseconds));
// Cannot use this property after the thread is dead
Assert.Throws<ThreadStateException>(() => t.IsBackground);
Assert.Throws<ThreadStateException>(() => t.IsBackground = false);
Assert.Throws<ThreadStateException>(() => t.IsBackground = true);
// Verify that the test process can shut down gracefully with a hung background thread
t = new Thread(() => Thread.Sleep(Timeout.Infinite));
t.IsBackground = true;
t.Start();
}
[Fact]
public static void IsThreadPoolThreadTest()
{
var isThreadPoolThread = false;
Thread t = null;
t = new Thread(() => { isThreadPoolThread = t.IsThreadPoolThread; });
t.IsBackground = true;
Assert.False(t.IsThreadPoolThread);
t.Start();
Assert.True(t.Join(UnexpectedTimeoutMilliseconds));
Assert.False(isThreadPoolThread);
var e = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(
state =>
{
isThreadPoolThread = Thread.CurrentThread.IsThreadPoolThread;
e.Set();
});
e.CheckedWait();
Assert.True(isThreadPoolThread);
}
[Fact]
public static void ManagedThreadIdTest()
{
var e = new ManualResetEvent(false);
Action waitForThread;
var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, e.CheckedWait);
t.IsBackground = true;
t.Start();
Assert.NotEqual(Thread.CurrentThread.ManagedThreadId, t.ManagedThreadId);
e.Set();
waitForThread();
}
[Fact]
public static void NameTest()
{
string name = Guid.NewGuid().ToString("N");
Action waitForThread;
var t =
ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
{
var ct = Thread.CurrentThread;
Assert.Equal(name, ct.Name);
Assert.Throws<InvalidOperationException>(() => ct.Name = null);
Assert.Throws<InvalidOperationException>(() => ct.Name = name + "b");
Assert.Equal(name, ct.Name);
});
t.IsBackground = true;
Assert.Null(t.Name);
t.Name = null;
t.Name = null;
Assert.Null(t.Name);
t.Name = name;
Assert.Equal(name, t.Name);
Assert.Throws<InvalidOperationException>(() => t.Name = null);
Assert.Throws<InvalidOperationException>(() => t.Name = name + "b");
Assert.Equal(name, t.Name);
t.Start();
waitForThread();
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
var ct = Thread.CurrentThread;
Assert.Null(ct.Name);
ct.Name = null;
ct.Name = null;
Assert.Null(ct.Name);
ct.Name = name;
Assert.Equal(name, ct.Name);
Assert.Throws<InvalidOperationException>(() => ct.Name = null);
Assert.Throws<InvalidOperationException>(() => ct.Name = name + "b");
Assert.Equal(name, ct.Name);
});
}
[Fact]
public static void PriorityTest()
{
var e = new ManualResetEvent(false);
Action waitForThread;
var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, e.CheckedWait);
t.IsBackground = true;
Assert.Equal(ThreadPriority.Normal, t.Priority);
t.Priority = ThreadPriority.AboveNormal;
Assert.Equal(ThreadPriority.AboveNormal, t.Priority);
t.Start();
Assert.Equal(ThreadPriority.AboveNormal, t.Priority);
t.Priority = ThreadPriority.Normal;
Assert.Equal(ThreadPriority.Normal, t.Priority);
e.Set();
waitForThread();
}
[Fact]
public static void ThreadStateTest()
{
var e0 = new ManualResetEvent(false);
var e1 = new AutoResetEvent(false);
Action waitForThread;
var t =
ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
{
e0.CheckedWait();
ThreadTestHelpers.WaitForConditionWithoutBlocking(() => e1.WaitOne(0));
});
Assert.Equal(ThreadState.Unstarted, t.ThreadState);
t.IsBackground = true;
Assert.Equal(ThreadState.Unstarted | ThreadState.Background, t.ThreadState);
t.Start();
ThreadTestHelpers.WaitForCondition(() => t.ThreadState == (ThreadState.WaitSleepJoin | ThreadState.Background));
e0.Set();
ThreadTestHelpers.WaitForCondition(() => t.ThreadState == (ThreadState.Running | ThreadState.Background));
e1.Set();
waitForThread();
Assert.Equal(ThreadState.Stopped, t.ThreadState);
t = ThreadTestHelpers.CreateGuardedThread(
out waitForThread,
() => ThreadTestHelpers.WaitForConditionWithoutBlocking(() => e1.WaitOne(0)));
t.Start();
ThreadTestHelpers.WaitForCondition(() => t.ThreadState == ThreadState.Running);
e1.Set();
waitForThread();
Assert.Equal(ThreadState.Stopped, t.ThreadState);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Mono)]
public static void AbortSuspendTest()
{
var e = new ManualResetEvent(false);
Action waitForThread;
var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, e.CheckedWait);
t.IsBackground = true;
Action verify = () =>
{
Assert.Throws<PlatformNotSupportedException>(() => t.Abort());
Assert.Throws<PlatformNotSupportedException>(() => t.Abort(t));
#pragma warning disable 618 // Obsolete members
Assert.Throws<PlatformNotSupportedException>(() => t.Suspend());
Assert.Throws<PlatformNotSupportedException>(() => t.Resume());
#pragma warning restore 618 // Obsolete members
};
verify();
t.Start();
verify();
e.Set();
waitForThread();
Assert.Throws<PlatformNotSupportedException>(() => Thread.ResetAbort());
}
private static void VerifyLocalDataSlot(LocalDataStoreSlot slot)
{
Assert.NotNull(slot);
var waitForThreadArray = new Action[2];
var threadArray = new Thread[2];
var barrier = new Barrier(threadArray.Length);
var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
Func<bool> barrierSignalAndWait =
() =>
{
try
{
Assert.True(barrier.SignalAndWait(UnexpectedTimeoutMilliseconds, cancellationToken));
}
catch (OperationCanceledException)
{
return false;
}
return true;
};
Action<int> threadMain =
threadIndex =>
{
try
{
Assert.Null(Thread.GetData(slot));
if (!barrierSignalAndWait())
{
return;
}
if (threadIndex == 0)
{
Thread.SetData(slot, threadIndex);
}
if (!barrierSignalAndWait())
{
return;
}
if (threadIndex == 0)
{
Assert.Equal(threadIndex, Thread.GetData(slot));
}
else
{
Assert.Null(Thread.GetData(slot));
}
if (!barrierSignalAndWait())
{
return;
}
if (threadIndex != 0)
{
Thread.SetData(slot, threadIndex);
}
if (!barrierSignalAndWait())
{
return;
}
Assert.Equal(threadIndex, Thread.GetData(slot));
if (!barrierSignalAndWait())
{
return;
}
}
catch (Exception ex)
{
cancellationTokenSource.Cancel();
throw new TargetInvocationException(ex);
}
};
for (int i = 0; i < threadArray.Length; ++i)
{
threadArray[i] = ThreadTestHelpers.CreateGuardedThread(out waitForThreadArray[i], () => threadMain(i));
threadArray[i].IsBackground = true;
threadArray[i].Start();
}
foreach (var waitForThread in waitForThreadArray)
{
waitForThread();
}
}
[Fact]
public static void LocalDataSlotTest()
{
var slot = Thread.AllocateDataSlot();
var slot2 = Thread.AllocateDataSlot();
Assert.NotEqual(slot, slot2);
VerifyLocalDataSlot(slot);
VerifyLocalDataSlot(slot2);
var slotName = "System.Threading.Threads.Tests.LocalDataSlotTest";
var slotName2 = slotName + ".2";
var invalidSlotName = slotName + ".Invalid";
try
{
// AllocateNamedDataSlot allocates
slot = Thread.AllocateNamedDataSlot(slotName);
AssertExtensions.Throws<ArgumentException>(null, () => Thread.AllocateNamedDataSlot(slotName));
slot2 = Thread.AllocateNamedDataSlot(slotName2);
Assert.NotEqual(slot, slot2);
VerifyLocalDataSlot(slot);
VerifyLocalDataSlot(slot2);
// Free the same slot twice, should be fine
Thread.FreeNamedDataSlot(slotName2);
Thread.FreeNamedDataSlot(slotName2);
}
catch (Exception ex)
{
Thread.FreeNamedDataSlot(slotName);
Thread.FreeNamedDataSlot(slotName2);
throw new TargetInvocationException(ex);
}
try
{
// GetNamedDataSlot gets or allocates
var tempSlot = Thread.GetNamedDataSlot(slotName);
Assert.Equal(slot, tempSlot);
tempSlot = Thread.GetNamedDataSlot(slotName2);
Assert.NotEqual(slot2, tempSlot);
slot2 = tempSlot;
Assert.NotEqual(slot, slot2);
VerifyLocalDataSlot(slot);
VerifyLocalDataSlot(slot2);
}
finally
{
Thread.FreeNamedDataSlot(slotName);
Thread.FreeNamedDataSlot(slotName2);
}
try
{
// A named slot can be used after the name is freed, since only the name is freed, not the slot
slot = Thread.AllocateNamedDataSlot(slotName);
Thread.FreeNamedDataSlot(slotName);
slot2 = Thread.AllocateNamedDataSlot(slotName); // same name
Thread.FreeNamedDataSlot(slotName);
Assert.NotEqual(slot, slot2);
VerifyLocalDataSlot(slot);
VerifyLocalDataSlot(slot2);
}
finally
{
Thread.FreeNamedDataSlot(slotName);
Thread.FreeNamedDataSlot(slotName2);
}
}
[Fact]
public static void InterruptTest()
{
// Interrupting a thread that is not blocked does not do anything, but once the thread starts blocking, it gets
// interrupted and does not auto-reset the signaled event
var threadReady = new AutoResetEvent(false);
var continueThread = new AutoResetEvent(false);
bool continueThreadBool = false;
Action waitForThread;
var t =
ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
{
threadReady.Set();
ThreadTestHelpers.WaitForConditionWithoutBlocking(() => Volatile.Read(ref continueThreadBool));
threadReady.Set();
Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait());
});
t.IsBackground = true;
t.Start();
threadReady.CheckedWait();
continueThread.Set();
t.Interrupt();
Assert.False(threadReady.WaitOne(ExpectedTimeoutMilliseconds));
Volatile.Write(ref continueThreadBool, true);
waitForThread();
Assert.True(continueThread.WaitOne(0));
// Interrupting a dead thread does nothing
t.Interrupt();
// Interrupting an unstarted thread causes the thread to be interrupted after it is started and starts blocking
t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait()));
t.IsBackground = true;
t.Interrupt();
t.Start();
waitForThread();
// A thread that is already blocked on a synchronization primitive unblocks immediately
continueThread.Reset();
t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait()));
t.IsBackground = true;
t.Start();
ThreadTestHelpers.WaitForCondition(() => (t.ThreadState & ThreadState.WaitSleepJoin) != 0);
t.Interrupt();
waitForThread();
}
[Fact]
public static void InterruptInFinallyBlockTest_SkipOnDesktopFramework()
{
// A wait in a finally block can be interrupted. The desktop framework applies the same rules as thread abort, and
// does not allow thread interrupt in a finally block. There is nothing special about thread interrupt that requires
// not allowing it in finally blocks, so this behavior has changed in .NET Core.
var continueThread = new AutoResetEvent(false);
Action waitForThread;
Thread t =
ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
{
try
{
}
finally
{
Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait());
}
});
t.IsBackground = true;
t.Start();
t.Interrupt();
waitForThread();
}
[Fact]
public static void JoinTest()
{
var threadReady = new ManualResetEvent(false);
var continueThread = new ManualResetEvent(false);
Action waitForThread;
var t =
ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
{
threadReady.Set();
continueThread.CheckedWait();
Thread.Sleep(ExpectedTimeoutMilliseconds);
});
t.IsBackground = true;
Assert.Throws<ArgumentOutOfRangeException>(() => t.Join(-2));
Assert.Throws<ArgumentOutOfRangeException>(() => t.Join(TimeSpan.FromMilliseconds(-2)));
Assert.Throws<ArgumentOutOfRangeException>(() => t.Join(TimeSpan.FromMilliseconds((double)int.MaxValue + 1)));
Assert.Throws<ThreadStateException>(() => t.Join());
Assert.Throws<ThreadStateException>(() => t.Join(UnexpectedTimeoutMilliseconds));
Assert.Throws<ThreadStateException>(() => t.Join(TimeSpan.FromMilliseconds(UnexpectedTimeoutMilliseconds)));
t.Start();
threadReady.CheckedWait();
Assert.False(t.Join(ExpectedTimeoutMilliseconds));
Assert.False(t.Join(TimeSpan.FromMilliseconds(ExpectedTimeoutMilliseconds)));
continueThread.Set();
waitForThread();
Assert.True(t.Join(0));
Assert.True(t.Join(TimeSpan.Zero));
}
[Fact]
public static void SleepTest()
{
Assert.Throws<ArgumentOutOfRangeException>(() => Thread.Sleep(-2));
Assert.Throws<ArgumentOutOfRangeException>(() => Thread.Sleep(TimeSpan.FromMilliseconds(-2)));
Assert.Throws<ArgumentOutOfRangeException>(() => Thread.Sleep(TimeSpan.FromMilliseconds((double)int.MaxValue + 1)));
Thread.Sleep(0);
var stopwatch = Stopwatch.StartNew();
Thread.Sleep(500);
stopwatch.Stop();
Assert.InRange((int)stopwatch.ElapsedMilliseconds, 100, int.MaxValue);
}
[Fact]
public static void StartTest()
{
var e = new AutoResetEvent(false);
Action waitForThread;
Thread t = null;
t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
{
e.CheckedWait();
Assert.Same(t, Thread.CurrentThread);
});
t.IsBackground = true;
Assert.Throws<InvalidOperationException>(() => t.Start(null));
Assert.Throws<InvalidOperationException>(() => t.Start(t));
t.Start();
Assert.Throws<ThreadStateException>(() => t.Start());
e.Set();
waitForThread();
Assert.Throws<ThreadStateException>(() => t.Start());
t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, parameter => e.CheckedWait());
t.IsBackground = true;
t.Start();
Assert.Throws<ThreadStateException>(() => t.Start());
Assert.Throws<ThreadStateException>(() => t.Start(null));
Assert.Throws<ThreadStateException>(() => t.Start(t));
e.Set();
waitForThread();
Assert.Throws<ThreadStateException>(() => t.Start());
Assert.Throws<ThreadStateException>(() => t.Start(null));
Assert.Throws<ThreadStateException>(() => t.Start(t));
t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, parameter =>
{
Assert.Null(parameter);
Assert.Same(t, Thread.CurrentThread);
});
t.IsBackground = true;
t.Start();
waitForThread();
t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, parameter =>
{
Assert.Null(parameter);
Assert.Same(t, Thread.CurrentThread);
});
t.IsBackground = true;
t.Start(null);
waitForThread();
t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, parameter =>
{
Assert.Same(t, parameter);
Assert.Same(t, Thread.CurrentThread);
});
t.IsBackground = true;
t.Start(t);
waitForThread();
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Mono)]
public static void MiscellaneousTest()
{
Thread.BeginCriticalRegion();
Thread.EndCriticalRegion();
Thread.BeginThreadAffinity();
Thread.EndThreadAffinity();
#pragma warning disable 618 // obsolete members
Assert.Throws<InvalidOperationException>(() => Thread.CurrentThread.GetCompressedStack());
Assert.Throws<InvalidOperationException>(() => Thread.CurrentThread.SetCompressedStack(CompressedStack.Capture()));
#pragma warning restore 618 // obsolete members
Thread.MemoryBarrier();
var ad = Thread.GetDomain();
Assert.NotNull(ad);
Assert.Equal(AppDomain.CurrentDomain, ad);
Assert.Equal(ad.Id, Thread.GetDomainID());
Thread.SpinWait(int.MinValue);
Thread.SpinWait(-1);
Thread.SpinWait(0);
Thread.SpinWait(1);
Thread.Yield();
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public static void WindowsPrincipalPolicyTest_Windows()
{
RemoteExecutor.Invoke(() =>
{
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
Assert.Equal(Environment.UserDomainName + @"\" + Environment.UserName, Thread.CurrentPrincipal.Identity.Name);
}).Dispose();
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public static void WindowsPrincipalPolicyTest_Unix()
{
RemoteExecutor.Invoke(() =>
{
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
Assert.Throws<PlatformNotSupportedException>(() => Thread.CurrentPrincipal);
}).Dispose();
}
[Fact]
public static void UnauthenticatedPrincipalTest()
{
RemoteExecutor.Invoke(() =>
{
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.UnauthenticatedPrincipal);
Assert.Equal(string.Empty, Thread.CurrentPrincipal.Identity.Name);
}).Dispose();
}
[Fact]
public static void DefaultPrincipalPolicyTest()
{
RemoteExecutor.Invoke(() =>
{
Assert.Null(Thread.CurrentPrincipal);
}).Dispose();
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.PythonTools.Infrastructure;
namespace Microsoft.PythonTools.Interpreter {
/// <summary>
/// Finds all the interpreters located under the current workspace folder,
/// as well as those referenced from the curent workspace folder settings.
/// </summary>
[InterpreterFactoryId(FactoryProviderName)]
[Export(typeof(IPythonInterpreterFactoryProvider))]
[Export(typeof(WorkspaceInterpreterFactoryProvider))]
[PartCreationPolicy(CreationPolicy.Shared)]
class WorkspaceInterpreterFactoryProvider : IPythonInterpreterFactoryProvider, IDisposable {
private readonly IPythonWorkspaceContextProvider _workspaceContextProvider;
private IPythonWorkspaceContext _workspace;
private readonly Dictionary<string, PythonInterpreterInformation> _factories = new Dictionary<string, PythonInterpreterInformation>();
internal const string FactoryProviderName = WorkspaceInterpreterFactoryConstants.FactoryProviderName;
private FileSystemWatcher _folderWatcher;
private Timer _folderWatcherTimer;
private bool _refreshPythonInterpreters;
private int _ignoreNotifications;
private bool _initialized;
private static readonly Version[] ExcludedVersions = new[] {
new Version(2, 5),
new Version(3, 0)
};
internal event EventHandler DiscoveryStarted;
[ImportingConstructor]
public WorkspaceInterpreterFactoryProvider(
[Import] IPythonWorkspaceContextProvider workspaceContextProvider
) {
_workspaceContextProvider = workspaceContextProvider;
_workspaceContextProvider.WorkspaceOpening += OnWorkspaceOpening;
_workspaceContextProvider.WorkspaceClosed += OnWorkspaceClosed;
}
protected void Dispose(bool disposing) {
if (disposing) {
_workspaceContextProvider.WorkspaceOpening -= OnWorkspaceOpening;
_workspaceContextProvider.WorkspaceClosed -= OnWorkspaceClosed;
if (_workspace != null) {
_workspace.InterpreterSettingChanged -= OnInterpreterSettingChanged;
}
_folderWatcher?.Dispose();
_folderWatcherTimer?.Dispose();
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
~WorkspaceInterpreterFactoryProvider() {
Dispose(false);
}
private void EnsureInitialized() {
lock (_factories) {
if (!_initialized) {
_initialized = true;
InitializeWorkspace(_workspaceContextProvider.Workspace);
DiscoverInterpreterFactories();
}
}
}
private void OnWorkspaceClosed(object sender, PythonWorkspaceContextEventArgs e) {
lock (_factories) {
_initialized = true;
InitializeWorkspace(null);
DiscoverInterpreterFactories();
}
}
private void OnWorkspaceOpening(object sender, PythonWorkspaceContextEventArgs e) {
lock (_factories) {
_initialized = true;
InitializeWorkspace(e.Workspace);
DiscoverInterpreterFactories();
}
}
private void InitializeWorkspace(IPythonWorkspaceContext workspace) {
lock (_factories) {
// Cleanup state associated with the previous workspace, if any
if (_workspace != null) {
_workspace.InterpreterSettingChanged -= OnInterpreterSettingChanged;
_workspace = null;
}
_folderWatcher?.Dispose();
_folderWatcher = null;
_folderWatcherTimer?.Dispose();
_folderWatcherTimer = null;
// Setup new workspace
_workspace = workspace;
if (_workspace != null) {
_workspace.InterpreterSettingChanged += OnInterpreterSettingChanged;
try {
_folderWatcher = new FileSystemWatcher(_workspace.Location, "*.*");
_folderWatcher.Created += OnFileCreatedDeletedRenamed;
_folderWatcher.Deleted += OnFileCreatedDeletedRenamed;
_folderWatcher.Renamed += OnFileCreatedDeletedRenamed;
_folderWatcher.EnableRaisingEvents = true;
_folderWatcher.IncludeSubdirectories = true;
} catch (ArgumentException) {
} catch (IOException) {
}
_folderWatcherTimer = new Timer(OnFileChangesTimerElapsed);
}
}
}
private void OnInterpreterSettingChanged(object sender, EventArgs e) {
DiscoverInterpreterFactories();
}
private void DiscoverInterpreterFactories() {
if (Volatile.Read(ref _ignoreNotifications) > 0) {
return;
}
ForceDiscoverInterpreterFactories();
}
private void ForceDiscoverInterpreterFactories() {
DiscoveryStarted?.Invoke(this, EventArgs.Empty);
// Discover the available interpreters...
bool anyChanged = false;
IPythonWorkspaceContext workspace = null;
lock (_factories) {
workspace = _workspace;
}
List<PythonInterpreterInformation> found;
try {
found = FindWorkspaceInterpreters(workspace)
.Where(i => !ExcludedVersions.Contains(i.Configuration.Version))
.ToList();
} catch (ObjectDisposedException) {
// We are aborting, so silently return with no results.
return;
}
var uniqueIds = new HashSet<string>(found.Select(i => i.Configuration.Id));
// Then update our cached state with the lock held.
lock (_factories) {
foreach (var info in found) {
PythonInterpreterInformation existingInfo;
if (!_factories.TryGetValue(info.Configuration.Id, out existingInfo) ||
info.Configuration != existingInfo.Configuration) {
_factories[info.Configuration.Id] = info;
anyChanged = true;
}
}
// Remove any factories we had before and no longer see...
foreach (var unregistered in _factories.Keys.Except(uniqueIds).ToArray()) {
_factories.Remove(unregistered);
anyChanged = true;
}
}
if (anyChanged) {
OnInterpreterFactoriesChanged();
}
}
private static IEnumerable<PythonInterpreterInformation> FindWorkspaceInterpreters(IPythonWorkspaceContext workspace) {
var found = new List<PythonInterpreterInformation>();
if (workspace != null) {
// First look in workspace subfolders
found.AddRange(FindInterpretersInSubFolders(workspace.Location).Where(p => p != null));
// Then look at the currently set interpreter path,
// because it may point to a folder outside of the workspace,
// or in a deep subfolder that we don't look into.
var interpreter = workspace.ReadInterpreterSetting();
if (PathUtils.IsValidPath(interpreter) && !Path.IsPathRooted(interpreter)) {
interpreter = workspace.MakeRooted(interpreter);
}
// Make sure it wasn't already discovered
if (File.Exists(interpreter) && !found.Any(p => PathUtils.IsSamePath(p.Configuration.InterpreterPath, interpreter))) {
var info = CreateEnvironmentInfo(interpreter);
if (info != null) {
found.Add(info);
}
}
}
return found;
}
private static IEnumerable<PythonInterpreterInformation> FindInterpretersInSubFolders(string workspaceFolder) {
foreach (var dir in PathUtils.EnumerateDirectories(workspaceFolder, recurse: false)) {
var file = PathUtils.FindFile(dir, "python.exe", depthLimit: 1);
if (!string.IsNullOrEmpty(file)) {
yield return CreateEnvironmentInfo(file);
}
}
}
private void OnFileCreatedDeletedRenamed(object sender, FileSystemEventArgs e) {
lock (_factories) {
try {
if (_refreshPythonInterpreters) {
_folderWatcherTimer?.Change(1000, Timeout.Infinite);
} else {
//Renamed
if (e.ChangeType == WatcherChangeTypes.Renamed && Directory.Exists(e.FullPath)) {
var renamedFileInformation = e as RenamedEventArgs;
if (_factories.Values.Any(a =>
PathUtils.IsSameDirectory(a.Configuration.GetPrefixPath(), renamedFileInformation.OldFullPath))
) {
_refreshPythonInterpreters = true;
_folderWatcherTimer?.Change(1000, Timeout.Infinite);
}
} else if ((e.ChangeType == WatcherChangeTypes.Created || e.ChangeType == WatcherChangeTypes.Deleted)
&& DetectPythonEnvironment(e)
) {
_refreshPythonInterpreters = true;
_folderWatcherTimer?.Change(1000, Timeout.Infinite);
}
}
} catch (ObjectDisposedException) {
}
}
}
private bool DetectPythonEnvironment(FileSystemEventArgs fileChangeEventArgs) {
if (string.Compare(Path.GetFileName(fileChangeEventArgs.FullPath), "python.exe", StringComparison.OrdinalIgnoreCase) != 0) {
return false;
}
int pythonExecutableDepth = fileChangeEventArgs.Name.Split(Path.DirectorySeparatorChar).Length;
return pythonExecutableDepth != 0 && pythonExecutableDepth <= 3;
}
private void OnFileChangesTimerElapsed(object state) {
try {
bool shouldDiscover;
lock (_factories) {
_folderWatcherTimer?.Change(Timeout.Infinite, Timeout.Infinite);
shouldDiscover = _refreshPythonInterpreters;
_refreshPythonInterpreters = false;
}
if (shouldDiscover) {
DiscoverInterpreterFactories();
}
} catch (ObjectDisposedException) {
}
}
private static PythonInterpreterInformation CreateEnvironmentInfo(string interpreterPath) {
if (!File.Exists(interpreterPath)) {
return null;
}
var prefixPath = PrefixFromSysPrefix(interpreterPath);
if (prefixPath == null) {
return null;
}
var arch = CPythonInterpreterFactoryProvider.ArchitectureFromExe(interpreterPath);
var version = CPythonInterpreterFactoryProvider.VersionFromSysVersionInfo(interpreterPath);
var name = Path.GetFileName(prefixPath);
var description = name;
var vendor = Strings.WorkspaceEnvironmentDescription;
var vendorUrl = string.Empty;
var supportUrl = string.Empty;
var windowsInterpreterPath = Path.Combine(Path.GetDirectoryName(interpreterPath), WorkspaceInterpreterFactoryConstants.WindowsExecutable);
if (!File.Exists(windowsInterpreterPath)) {
windowsInterpreterPath = string.Empty;
}
var config = new VisualStudioInterpreterConfiguration(
WorkspaceInterpreterFactoryConstants.GetInterpreterId(WorkspaceInterpreterFactoryConstants.EnvironmentCompanyName, name),
description,
prefixPath,
interpreterPath,
windowsInterpreterPath,
WorkspaceInterpreterFactoryConstants.PathEnvironmentVariableName,
arch,
version,
InterpreterUIMode.CannotBeDefault | InterpreterUIMode.CannotBeConfigured
);
config.SwitchToFullDescription();
var unique = new PythonInterpreterInformation(
config,
vendor,
vendorUrl,
supportUrl
);
return unique;
}
private static string PrefixFromSysPrefix(string interpreterPath) {
// Interpreter executable may be under scripts folder (ex: virtual envs)
// or directly in the prefix path folder (ex: installed env)
using (var output = ProcessOutput.RunHiddenAndCapture(
interpreterPath, "-c", "import sys; print(sys.prefix)"
)) {
output.Wait();
if (output.ExitCode == 0) {
var result = output.StandardOutputLines.FirstOrDefault() ?? "";
if (Directory.Exists(result)) {
return result;
}
}
}
return null;
}
#region IPythonInterpreterProvider Members
public IEnumerable<InterpreterConfiguration> GetInterpreterConfigurations() {
EnsureInitialized();
lock (_factories) {
return _factories.Values.Select(x => x.Configuration).ToArray();
}
}
public IPythonInterpreterFactory GetInterpreterFactory(string id) {
EnsureInitialized();
PythonInterpreterInformation info;
lock (_factories) {
_factories.TryGetValue(id, out info);
}
return info?.GetOrCreateFactory(CreateFactory);
}
private static IPythonInterpreterFactory CreateFactory(PythonInterpreterInformation info) {
return InterpreterFactoryCreator.CreateInterpreterFactory(
info.Configuration,
new InterpreterFactoryCreationOptions {
WatchFileSystem = true,
}
);
}
private EventHandler _interpFactoriesChanged;
public event EventHandler InterpreterFactoriesChanged {
add {
EnsureInitialized();
_interpFactoriesChanged += value;
}
remove {
_interpFactoriesChanged -= value;
}
}
private void OnInterpreterFactoriesChanged() {
_interpFactoriesChanged?.Invoke(this, EventArgs.Empty);
}
public object GetProperty(string id, string propName) {
PythonInterpreterInformation info;
switch (propName) {
case PythonRegistrySearch.CompanyPropertyKey:
lock (_factories) {
if (_factories.TryGetValue(id, out info)) {
return info.Vendor;
}
}
break;
case "PersistInteractive":
return true;
}
return null;
}
#endregion
private sealed class DiscoverOnDispose : IDisposable {
private readonly WorkspaceInterpreterFactoryProvider _provider;
private readonly bool _forceDiscovery;
public DiscoverOnDispose(WorkspaceInterpreterFactoryProvider provider, bool forceDiscovery) {
_provider = provider;
_forceDiscovery = forceDiscovery;
Interlocked.Increment(ref _provider._ignoreNotifications);
}
public void Dispose() {
Interlocked.Decrement(ref _provider._ignoreNotifications);
if (_forceDiscovery) {
_provider.ForceDiscoverInterpreterFactories();
} else {
_provider.DiscoverInterpreterFactories();
}
}
}
internal IDisposable SuppressDiscoverFactories(bool forceDiscoveryOnDispose) {
return new DiscoverOnDispose(this, forceDiscoveryOnDispose);
}
}
}
| |
// 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.Diagnostics;
using System.Reflection.Metadata;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Reflection.Internal
{
/// <summary>
/// Provides helpers to decode strings from unmanaged memory to System.String while avoiding
/// intermediate allocation.
///
/// This has three components:
///
/// (1) Light-up Encoding.GetString(byte*, int) via reflection and resurface it as extension
/// method.
///
/// This is a new API that will provide API convergence across all platforms for
/// this scenario. It is already on .NET 4.6+ and ASP.NET vNext, but not yet available
/// on every platform we support. See below for how we fall back.
///
/// (2) Deal with WinRT prefixes.
///
/// When reading managed winmds with projections enabled, the metadata reader needs to prepend
/// a WinRT prefix in some case . Doing this without allocation poses a problem
/// as we don't have the prefix and input in contiguous data that we can pass to the
/// Encoding.GetString. We handle this case using pooled managed scratch buffers where we copy
/// the prefix and input and decode using Encoding.GetString(byte[], int, int).
///
/// (3) Deal with platforms that don't yet have Encoding.GetString(byte*, int).
///
/// If we're running on a full framework earlier than 4.6, we will bind to the internal
/// String.CreateStringFromEncoding which is equivalent and Encoding.GetString is just a trivial
/// wrapper around it in .NET 4.6. This means that we always have the fast path on every
/// full framework version we support.
///
/// If we can't bind to it via reflection, then we emulate it using what is effectively (2) and
/// with an empty prefix.
///
/// For both (2) and (3), the pooled buffers have a fixed size deemed large enough for the
/// vast majority of metadata strings. In the rare worst case (byteCount > threshold and
/// (lightUpAttemptFailed || prefix != null), we give up and allocate a temporary array,
/// copy to it, decode, and throw it away.
/// </summary>
internal unsafe static class EncodingHelper
{
// Size of pooled buffers. Input larger than that is prefixed or given to us on a
// platform that doesn't have unsafe Encoding.GetString, will cause us to
// allocate and throw away a temporary buffer. The vast majority of metadata strings
// are quite small so we don't need to waste memory with large buffers.
public const int PooledBufferSize = 200;
// The pooled buffers for (2) and (3) above. Use AcquireBuffer(int) and ReleaseBuffer(byte[])
// instead of the pool directly to implement the size check.
private static readonly ObjectPool<byte[]> s_pool = new ObjectPool<byte[]>(() => new byte[PooledBufferSize]);
public static string DecodeUtf8(byte* bytes, int byteCount, byte[] prefix, MetadataStringDecoder utf8Decoder)
{
Debug.Assert(utf8Decoder != null);
if (prefix != null)
{
return DecodeUtf8Prefixed(bytes, byteCount, prefix, utf8Decoder);
}
if (byteCount == 0)
{
return String.Empty;
}
return utf8Decoder.GetString(bytes, byteCount);
}
private static string DecodeUtf8Prefixed(byte* bytes, int byteCount, byte[] prefix, MetadataStringDecoder utf8Decoder)
{
Debug.Assert(utf8Decoder != null);
int prefixedByteCount = byteCount + prefix.Length;
if (prefixedByteCount == 0)
{
return String.Empty;
}
byte[] buffer = AcquireBuffer(prefixedByteCount);
prefix.CopyTo(buffer, 0);
Marshal.Copy((IntPtr)bytes, buffer, prefix.Length, byteCount);
string result;
fixed (byte* prefixedBytes = buffer)
{
result = utf8Decoder.GetString(prefixedBytes, prefixedByteCount);
}
ReleaseBuffer(buffer);
return result;
}
private static byte[] AcquireBuffer(int byteCount)
{
if (byteCount > PooledBufferSize)
{
return new byte[byteCount];
}
return s_pool.Allocate();
}
private static void ReleaseBuffer(byte[] buffer)
{
if (buffer.Length == PooledBufferSize)
{
s_pool.Free(buffer);
}
}
// TODO: Remove everything in this region when we can retarget and use the real
// Encoding.GetString(byte*, int) without reflection.
#region Light-Up
internal delegate string Encoding_GetString(Encoding encoding, byte* bytes, int byteCount); // only internal for test hook
private delegate string String_CreateStringFromEncoding(byte* bytes, int byteCount, Encoding encoding);
private static Encoding_GetString s_getStringPlatform = LoadGetStringPlatform(); // only non-readonly for test hook
public static string GetString(this Encoding encoding, byte* bytes, int byteCount)
{
Debug.Assert(encoding != null);
if (s_getStringPlatform == null)
{
return GetStringPortable(encoding, bytes, byteCount);
}
return s_getStringPlatform(encoding, bytes, byteCount);
}
private static unsafe string GetStringPortable(Encoding encoding, byte* bytes, int byteCount)
{
// This implementation can leak publicly (by design) to MetadataStringDecoder.GetString.
// Therefore we implement the same validation.
Debug.Assert(encoding != null); // validated by MetadataStringDecoder constructor.
if (bytes == null)
{
throw new ArgumentNullException("bytes");
}
if (byteCount < 0)
{
throw new ArgumentOutOfRangeException("byteCount");
}
byte[] buffer = AcquireBuffer(byteCount);
Marshal.Copy((IntPtr)bytes, buffer, 0, byteCount);
string result = encoding.GetString(buffer, 0, byteCount);
ReleaseBuffer(buffer);
return result;
}
private static Encoding_GetString LoadGetStringPlatform()
{
// .NET Framework 4.6+ and recent versions of other .NET platforms.
//
// Try to bind to Encoding.GetString(byte*, int);
MethodInfo getStringInfo = LightUpHelper.GetMethod(typeof(Encoding), "GetString", typeof(byte*), typeof(int));
if (getStringInfo != null && getStringInfo.ReturnType == typeof(String))
{
try
{
return (Encoding_GetString)getStringInfo.CreateDelegate(typeof(Encoding_GetString), null);
}
catch (MemberAccessException)
{
}
catch (InvalidOperationException)
{
// thrown when accessing unapproved API in a Windows Store app
}
}
// .NET Framework < 4.6
//
// Try to bind to String.CreateStringFromEncoding(byte*, int, Encoding)
//
// Note that this one is internal and GetRuntimeMethod only searches public methods, which accounts for the different
// pattern from above.
//
// NOTE: Another seeming equivalent is new string(sbyte*, int, Encoding), but don't be fooled. First of all, we can't get
// a delegate to a constructor. Worst than that, even if we could, it is actually about 4x slower than both of these
// and even the portable version (only ~20% slower than these) crushes it.
//
// It spends an inordinate amount of time transitioning to managed code from the VM and then lands in String.CreateString
// (note no FromEncoding suffix), which defensively copies to a new byte array on every call -- defeating the entire purpose
// of this class!
//
// For this reason, desktop callers should not implement an interner that falls back to the unsafe string ctor but instead
// return null and let us find the best decoding approach for the current platform.
//
// Yet another approach is to use new string('\0', GetCharCount) and use unsafe GetChars to fill it.
// However, on .NET < 4.6, there isn't no-op fast path for zero-initialization case so we'd slow down.
// Plus, mutating a System.String is no better than the reflection here.
IEnumerable<MethodInfo> createStringInfos = typeof(String).GetTypeInfo().GetDeclaredMethods("CreateStringFromEncoding");
foreach (var methodInfo in createStringInfos)
{
var parameters = methodInfo.GetParameters();
if (parameters.Length == 3
&& parameters[0].ParameterType == typeof(byte*)
&& parameters[1].ParameterType == typeof(int)
&& parameters[2].ParameterType == typeof(Encoding)
&& methodInfo.ReturnType == typeof(String))
{
try
{
var createStringFromEncoding = (String_CreateStringFromEncoding)methodInfo.CreateDelegate(typeof(String_CreateStringFromEncoding), null);
return (encoding, bytes, byteCount) => GetStringUsingCreateStringFromEncoding(createStringFromEncoding, bytes, byteCount, encoding);
}
catch (MemberAccessException)
{
}
catch (InvalidOperationException)
{
// thrown when accessing unapproved API in a Windows Store app
}
}
}
// Other platforms: Give up and fall back to GetStringPortable above.
return null;
}
private static unsafe string GetStringUsingCreateStringFromEncoding(
String_CreateStringFromEncoding createStringFromEncoding,
byte* bytes,
int byteCount,
Encoding encoding)
{
// String.CreateStringFromEncoding is an internal method that does not validate
// arguments, but this implementation can leak publicly (by design) via
// MetadataStringDecoder.GetString. Therefore, we implement the same validation
// that Encoding.GetString would do if it were available directly.
Debug.Assert(encoding != null); // validated by MetadataStringDecoder constructor.
if (bytes == null)
{
throw new ArgumentNullException("bytes");
}
if (byteCount < 0)
{
throw new ArgumentOutOfRangeException("byteCount");
}
return createStringFromEncoding(bytes, byteCount, encoding);
}
// Test hook to force portable implementation and ensure light is functioning.
internal static bool TestOnly_LightUpEnabled
{
get { return s_getStringPlatform != null; }
set { s_getStringPlatform = value ? LoadGetStringPlatform() : null; }
}
#endregion
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System.Text;
using System.IO;
using System.Collections;
using log4net.Util;
using log4net.Repository;
namespace log4net.Util
{
/// <summary>
/// Abstract class that provides the formatting functionality that
/// derived classes need.
/// </summary>
/// <remarks>
/// <para>
/// Conversion specifiers in a conversion patterns are parsed to
/// individual PatternConverters. Each of which is responsible for
/// converting a logging event in a converter specific manner.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public abstract class PatternConverter
{
#region Protected Instance Constructors
/// <summary>
/// Protected constructor
/// </summary>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="PatternConverter" /> class.
/// </para>
/// </remarks>
protected PatternConverter()
{
}
#endregion Protected Instance Constructors
#region Public Instance Properties
/// <summary>
/// Get the next pattern converter in the chain
/// </summary>
/// <value>
/// the next pattern converter in the chain
/// </value>
/// <remarks>
/// <para>
/// Get the next pattern converter in the chain
/// </para>
/// </remarks>
public virtual PatternConverter Next
{
get { return m_next; }
}
/// <summary>
/// Gets or sets the formatting info for this converter
/// </summary>
/// <value>
/// The formatting info for this converter
/// </value>
/// <remarks>
/// <para>
/// Gets or sets the formatting info for this converter
/// </para>
/// </remarks>
public virtual FormattingInfo FormattingInfo
{
get { return new FormattingInfo(m_min, m_max, m_leftAlign); }
set
{
m_min = value.Min;
m_max = value.Max;
m_leftAlign = value.LeftAlign;
}
}
/// <summary>
/// Gets or sets the option value for this converter
/// </summary>
/// <summary>
/// The option for this converter
/// </summary>
/// <remarks>
/// <para>
/// Gets or sets the option value for this converter
/// </para>
/// </remarks>
public virtual string Option
{
get { return m_option; }
set { m_option = value; }
}
#endregion Public Instance Properties
#region Protected Abstract Methods
/// <summary>
/// Evaluate this pattern converter and write the output to a writer.
/// </summary>
/// <param name="writer"><see cref="TextWriter" /> that will receive the formatted result.</param>
/// <param name="state">The state object on which the pattern converter should be executed.</param>
/// <remarks>
/// <para>
/// Derived pattern converters must override this method in order to
/// convert conversion specifiers in the appropriate way.
/// </para>
/// </remarks>
abstract protected void Convert(TextWriter writer, object state);
#endregion Protected Abstract Methods
#region Public Instance Methods
/// <summary>
/// Set the next pattern converter in the chains
/// </summary>
/// <param name="patternConverter">the pattern converter that should follow this converter in the chain</param>
/// <returns>the next converter</returns>
/// <remarks>
/// <para>
/// The PatternConverter can merge with its neighbor during this method (or a sub class).
/// Therefore the return value may or may not be the value of the argument passed in.
/// </para>
/// </remarks>
public virtual PatternConverter SetNext(PatternConverter patternConverter)
{
m_next = patternConverter;
return m_next;
}
/// <summary>
/// Write the pattern converter to the writer with appropriate formatting
/// </summary>
/// <param name="writer"><see cref="TextWriter" /> that will receive the formatted result.</param>
/// <param name="state">The state object on which the pattern converter should be executed.</param>
/// <remarks>
/// <para>
/// This method calls <see cref="Convert"/> to allow the subclass to perform
/// appropriate conversion of the pattern converter. If formatting options have
/// been specified via the <see cref="FormattingInfo"/> then this method will
/// apply those formattings before writing the output.
/// </para>
/// </remarks>
virtual public void Format(TextWriter writer, object state)
{
if (m_min < 0 && m_max == int.MaxValue)
{
// Formatting options are not in use
Convert(writer, state);
}
else
{
string msg = null;
int len;
lock (m_formatWriter)
{
m_formatWriter.Reset(c_renderBufferMaxCapacity, c_renderBufferSize);
Convert(m_formatWriter, state);
StringBuilder buf = m_formatWriter.GetStringBuilder();
len = buf.Length;
if (len > m_max)
{
msg = buf.ToString(len - m_max, m_max);
len = m_max;
}
else
{
msg = buf.ToString();
}
}
if (len < m_min)
{
if (m_leftAlign)
{
writer.Write(msg);
SpacePad(writer, m_min - len);
}
else
{
SpacePad(writer, m_min - len);
writer.Write(msg);
}
}
else
{
writer.Write(msg);
}
}
}
private static readonly string[] SPACES = { " ", " ", " ", " ", // 1,2,4,8 spaces
" ", // 16 spaces
" " }; // 32 spaces
/// <summary>
/// Fast space padding method.
/// </summary>
/// <param name="writer"><see cref="TextWriter" /> to which the spaces will be appended.</param>
/// <param name="length">The number of spaces to be padded.</param>
/// <remarks>
/// <para>
/// Fast space padding method.
/// </para>
/// </remarks>
protected static void SpacePad(TextWriter writer, int length)
{
while(length >= 32)
{
writer.Write(SPACES[5]);
length -= 32;
}
for(int i = 4; i >= 0; i--)
{
if ((length & (1<<i)) != 0)
{
writer.Write(SPACES[i]);
}
}
}
#endregion Public Instance Methods
#region Private Instance Fields
private PatternConverter m_next;
private int m_min = -1;
private int m_max = int.MaxValue;
private bool m_leftAlign = false;
/// <summary>
/// The option string to the converter
/// </summary>
private string m_option = null;
private ReusableStringWriter m_formatWriter = new ReusableStringWriter(System.Globalization.CultureInfo.InvariantCulture);
#endregion Private Instance Fields
#region Constants
/// <summary>
/// Initial buffer size
/// </summary>
private const int c_renderBufferSize = 256;
/// <summary>
/// Maximum buffer size before it is recycled
/// </summary>
private const int c_renderBufferMaxCapacity = 1024;
#endregion
#region Static Methods
/// <summary>
/// Write an dictionary to a <see cref="TextWriter"/>
/// </summary>
/// <param name="writer">the writer to write to</param>
/// <param name="repository">a <see cref="ILoggerRepository"/> to use for object conversion</param>
/// <param name="value">the value to write to the writer</param>
/// <remarks>
/// <para>
/// Writes the <see cref="IDictionary"/> to a writer in the form:
/// </para>
/// <code>
/// {key1=value1, key2=value2, key3=value3}
/// </code>
/// <para>
/// If the <see cref="ILoggerRepository"/> specified
/// is not null then it is used to render the key and value to text, otherwise
/// the object's ToString method is called.
/// </para>
/// </remarks>
protected static void WriteDictionary(TextWriter writer, ILoggerRepository repository, IDictionary value)
{
WriteDictionary(writer, repository, value.GetEnumerator());
}
/// <summary>
/// Write an dictionary to a <see cref="TextWriter"/>
/// </summary>
/// <param name="writer">the writer to write to</param>
/// <param name="repository">a <see cref="ILoggerRepository"/> to use for object conversion</param>
/// <param name="value">the value to write to the writer</param>
/// <remarks>
/// <para>
/// Writes the <see cref="IDictionaryEnumerator"/> to a writer in the form:
/// </para>
/// <code>
/// {key1=value1, key2=value2, key3=value3}
/// </code>
/// <para>
/// If the <see cref="ILoggerRepository"/> specified
/// is not null then it is used to render the key and value to text, otherwise
/// the object's ToString method is called.
/// </para>
/// </remarks>
protected static void WriteDictionary(TextWriter writer, ILoggerRepository repository, IDictionaryEnumerator value)
{
writer.Write("{");
bool first = true;
// Write out all the dictionary key value pairs
while (value.MoveNext())
{
if (first)
{
first = false;
}
else
{
writer.Write(", ");
}
WriteObject(writer, repository, value.Key);
writer.Write("=");
WriteObject(writer, repository, value.Value);
}
writer.Write("}");
}
/// <summary>
/// Write an object to a <see cref="TextWriter"/>
/// </summary>
/// <param name="writer">the writer to write to</param>
/// <param name="repository">a <see cref="ILoggerRepository"/> to use for object conversion</param>
/// <param name="value">the value to write to the writer</param>
/// <remarks>
/// <para>
/// Writes the Object to a writer. If the <see cref="ILoggerRepository"/> specified
/// is not null then it is used to render the object to text, otherwise
/// the object's ToString method is called.
/// </para>
/// </remarks>
protected static void WriteObject(TextWriter writer, ILoggerRepository repository, object value)
{
if (repository != null)
{
repository.RendererMap.FindAndRender(value, writer);
}
else
{
// Don't have a repository to render with so just have to rely on ToString
if (value == null)
{
writer.Write( SystemInfo.NullText );
}
else
{
writer.Write( value.ToString() );
}
}
}
#endregion
private PropertiesDictionary properties;
/// <summary>
///
/// </summary>
public PropertiesDictionary Properties
{
get { return properties; }
set { properties = 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 Internal.Runtime.InteropServices.WindowsRuntime;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
namespace System
{
/// <summary>Provides extension methods in the System namespace for working with the Windows Runtime.<br />
/// Currently contains:<br />
/// <ul>
/// <li>Extension methods for conversion between <code>Windows.Foundation.IAsyncInfo</code> and deriving generic interfaces
/// and <code>System.Threading.Tasks.Task</code>.</li>
/// <li>Extension methods for conversion between <code>System.Threading.Tasks.Task</code>
/// and <code>Windows.Foundation.IAsyncInfo</code> and deriving generic interfaces.</li>
/// </ul></summary>
[CLSCompliant(false)]
public static class WindowsRuntimeSystemExtensions
{
#region Converters from Windows.Foundation.IAsyncInfo (and interfaces that derive from it) to System.Threading.Tasks.Task
#region Convenience Helpers
private static void ConcatenateCancelTokens(CancellationToken source, CancellationTokenSource sink, Task concatenationLifetime)
{
Debug.Assert(sink != null);
CancellationTokenRegistration ctReg = source.Register((state) => { ((CancellationTokenSource)state).Cancel(); },
sink);
concatenationLifetime.ContinueWith((_, state) => { ((CancellationTokenRegistration)state).Dispose(); },
ctReg, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
private static void ConcatenateProgress<TProgress>(IAsyncActionWithProgress<TProgress> source, IProgress<TProgress> sink)
{
// This is separated out into a separate method so that we only pay the costs of compiler-generated closure if progress is non-null.
source.Progress += new AsyncActionProgressHandler<TProgress>((_, info) => sink.Report(info));
}
private static void ConcatenateProgress<TResult, TProgress>(IAsyncOperationWithProgress<TResult, TProgress> source, IProgress<TProgress> sink)
{
// This is separated out into a separate method so that we only pay the costs of compiler-generated closure if progress is non-null.
source.Progress += new AsyncOperationProgressHandler<TResult, TProgress>((_, info) => sink.Report(info));
}
#endregion Convenience Helpers
#region Converters from IAsyncAction to Task
/// <summary>Gets an awaiter used to await this asynchronous operation.</summary>
/// <returns>An awaiter instance.</returns>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public static TaskAwaiter GetAwaiter(this IAsyncAction source)
{
return AsTask(source).GetAwaiter();
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task AsTask(this IAsyncAction source)
{
return AsTask(source, CancellationToken.None);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task AsTask(this IAsyncAction source, CancellationToken cancellationToken)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
var wrapper = source as TaskToAsyncActionAdapter;
if (wrapper != null && !wrapper.CompletedSynchronously)
{
Task innerTask = wrapper.Task;
Debug.Assert(innerTask != null);
Debug.Assert(innerTask.Status != TaskStatus.Created);
if (!innerTask.IsCompleted)
{
// The race here is benign: If the task completes here, the concatination is useless, but not damaging.
if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null)
ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask);
}
return innerTask;
}
// Fast path to return a completed Task if the operation has already completed:
switch (source.Status)
{
case AsyncStatus.Completed:
return Task.CompletedTask;
case AsyncStatus.Error:
return Task.FromException(ExceptionSupport.AttachRestrictedErrorInfo(source.ErrorCode));
case AsyncStatus.Canceled:
return Task.FromCanceled(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true));
}
// Benign race: source may complete here. Things still work, just not taking the fast path.
// Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task:
var bridge = new AsyncInfoToTaskBridge<VoidValueTypeParameter, VoidValueTypeParameter>(cancellationToken);
source.Completed = new AsyncActionCompletedHandler(bridge.CompleteFromAsyncAction);
bridge.RegisterForCancellation(source);
return bridge.Task;
}
#endregion Converters from IAsyncAction to Task
#region Converters from IAsyncOperation<TResult> to Task
/// <summary>Gets an awaiter used to await this asynchronous operation.</summary>
/// <returns>An awaiter instance.</returns>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public static TaskAwaiter<TResult> GetAwaiter<TResult>(this IAsyncOperation<TResult> source)
{
return AsTask(source).GetAwaiter();
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task<TResult> AsTask<TResult>(this IAsyncOperation<TResult> source)
{
return AsTask(source, CancellationToken.None);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task<TResult> AsTask<TResult>(this IAsyncOperation<TResult> source, CancellationToken cancellationToken)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
var wrapper = source as TaskToAsyncOperationAdapter<TResult>;
if (wrapper != null && !wrapper.CompletedSynchronously)
{
Task<TResult> innerTask = wrapper.Task as Task<TResult>;
Debug.Assert(innerTask != null);
Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment?
if (!innerTask.IsCompleted)
{
// The race here is benign: If the task completes here, the concatination is useless, but not damaging.
if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null)
ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask);
}
return innerTask;
}
// Fast path to return a completed Task if the operation has already completed
switch (source.Status)
{
case AsyncStatus.Completed:
return Task.FromResult(source.GetResults());
case AsyncStatus.Error:
return Task.FromException<TResult>(ExceptionSupport.AttachRestrictedErrorInfo(source.ErrorCode));
case AsyncStatus.Canceled:
return Task.FromCanceled<TResult>(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true));
}
// Benign race: source may complete here. Things still work, just not taking the fast path.
// Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task:
var bridge = new AsyncInfoToTaskBridge<TResult, VoidValueTypeParameter>(cancellationToken);
source.Completed = new AsyncOperationCompletedHandler<TResult>(bridge.CompleteFromAsyncOperation);
bridge.RegisterForCancellation(source);
return bridge.Task;
}
#endregion Converters from IAsyncOperation<TResult> to Task
#region Converters from IAsyncActionWithProgress<TProgress> to Task
/// <summary>Gets an awaiter used to await this asynchronous operation.</summary>
/// <returns>An awaiter instance.</returns>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public static TaskAwaiter GetAwaiter<TProgress>(this IAsyncActionWithProgress<TProgress> source)
{
return AsTask(source).GetAwaiter();
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source)
{
return AsTask(source, CancellationToken.None, null);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source, CancellationToken cancellationToken)
{
return AsTask(source, cancellationToken, null);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="progress">The progress object used to receive progress updates.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source, IProgress<TProgress> progress)
{
return AsTask(source, CancellationToken.None, progress);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
/// <param name="progress">The progress object used to receive progress updates.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source,
CancellationToken cancellationToken, IProgress<TProgress> progress)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
var wrapper = source as TaskToAsyncActionWithProgressAdapter<TProgress>;
if (wrapper != null && !wrapper.CompletedSynchronously)
{
Task innerTask = wrapper.Task;
Debug.Assert(innerTask != null);
Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment?
if (!innerTask.IsCompleted)
{
// The race here is benign: If the task completes here, the concatinations are useless, but not damaging.
if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null)
ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask);
if (progress != null)
ConcatenateProgress(source, progress);
}
return innerTask;
}
// Fast path to return a completed Task if the operation has already completed:
switch (source.Status)
{
case AsyncStatus.Completed:
return Task.CompletedTask;
case AsyncStatus.Error:
return Task.FromException(ExceptionSupport.AttachRestrictedErrorInfo(source.ErrorCode));
case AsyncStatus.Canceled:
return Task.FromCanceled(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true));
}
// Benign race: source may complete here. Things still work, just not taking the fast path.
// Forward progress reports:
if (progress != null)
ConcatenateProgress(source, progress);
// Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task:
var bridge = new AsyncInfoToTaskBridge<VoidValueTypeParameter, TProgress>(cancellationToken);
source.Completed = new AsyncActionWithProgressCompletedHandler<TProgress>(bridge.CompleteFromAsyncActionWithProgress);
bridge.RegisterForCancellation(source);
return bridge.Task;
}
#endregion Converters from IAsyncActionWithProgress<TProgress> to Task
#region Converters from IAsyncOperationWithProgress<TResult,TProgress> to Task
/// <summary>Gets an awaiter used to await this asynchronous operation.</summary>
/// <returns>An awaiter instance.</returns>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public static TaskAwaiter<TResult> GetAwaiter<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source)
{
return AsTask(source).GetAwaiter();
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <returns>The Task representing the started asynchronous operation.</returns>
public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source)
{
return AsTask(source, CancellationToken.None, null);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source,
CancellationToken cancellationToken)
{
return AsTask(source, cancellationToken, null);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="progress">The progress object used to receive progress updates.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source,
IProgress<TProgress> progress)
{
return AsTask(source, CancellationToken.None, progress);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
/// <param name="progress">The progress object used to receive progress updates.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source,
CancellationToken cancellationToken, IProgress<TProgress> progress)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
var wrapper = source as TaskToAsyncOperationWithProgressAdapter<TResult, TProgress>;
if (wrapper != null && !wrapper.CompletedSynchronously)
{
Task<TResult> innerTask = wrapper.Task as Task<TResult>;
Debug.Assert(innerTask != null);
Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment?
if (!innerTask.IsCompleted)
{
// The race here is benign: If the task completes here, the concatinations are useless, but not damaging.
if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null)
ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask);
if (progress != null)
ConcatenateProgress(source, progress);
}
return innerTask;
}
// Fast path to return a completed Task if the operation has already completed
switch (source.Status)
{
case AsyncStatus.Completed:
return Task.FromResult(source.GetResults());
case AsyncStatus.Error:
return Task.FromException<TResult>(ExceptionSupport.AttachRestrictedErrorInfo(source.ErrorCode));
case AsyncStatus.Canceled:
return Task.FromCanceled<TResult>(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true));
}
// Benign race: source may complete here. Things still work, just not taking the fast path.
// Forward progress reports:
if (progress != null)
ConcatenateProgress(source, progress);
// Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task:
var bridge = new AsyncInfoToTaskBridge<TResult, TProgress>(cancellationToken);
source.Completed = new AsyncOperationWithProgressCompletedHandler<TResult, TProgress>(bridge.CompleteFromAsyncOperationWithProgress);
bridge.RegisterForCancellation(source);
return bridge.Task;
}
#endregion Converters from IAsyncOperationWithProgress<TResult,TProgress> to Task
#endregion Converters from Windows.Foundation.IAsyncInfo (and interfaces that derive from it) to System.Threading.Tasks.Task
#region Converters from System.Threading.Tasks.Task to Windows.Foundation.IAsyncInfo (and interfaces that derive from it)
public static IAsyncAction AsAsyncAction(this Task source)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return new TaskToAsyncActionAdapter(source, underlyingCancelTokenSource: null);
}
public static IAsyncOperation<TResult> AsAsyncOperation<TResult>(this Task<TResult> source)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return new TaskToAsyncOperationAdapter<TResult>(source, underlyingCancelTokenSource: null);
}
#endregion Converters from System.Threading.Tasks.Task to Windows.Foundation.IAsyncInfo (and interfaces that derive from it)
private static void CommonlyUsedGenericInstantiations()
{
// This method is an aid for NGen to save common generic
// instantiations into the ngen image.
((IAsyncOperation<bool>)null).AsTask();
((IAsyncOperation<string>)null).AsTask();
((IAsyncOperation<object>)null).AsTask();
((IAsyncOperation<uint>)null).AsTask();
((IAsyncOperationWithProgress<uint, uint>)null).AsTask();
((IAsyncOperationWithProgress<ulong, ulong>)null).AsTask();
((IAsyncOperationWithProgress<string, ulong>)null).AsTask();
}
} // class WindowsRuntimeSystemExtensions
} // namespace
// WindowsRuntimeExtensions.cs
| |
/*
* 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 OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Interfaces;
using log4net;
namespace OpenSim.Region.ScriptEngine.XEngine
{
/// <summary>
/// Prepares events so they can be directly executed upon a script by EventQueueManager, then queues it.
/// </summary>
public class EventManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private XEngine myScriptEngine;
public EventManager(XEngine _ScriptEngine)
{
myScriptEngine = _ScriptEngine;
// m_log.Info("[XEngine] Hooking up to server events");
myScriptEngine.World.EventManager.OnAttach += attach;
myScriptEngine.World.EventManager.OnObjectGrab += touch_start;
myScriptEngine.World.EventManager.OnObjectGrabbing += touch;
myScriptEngine.World.EventManager.OnObjectDeGrab += touch_end;
myScriptEngine.World.EventManager.OnScriptChangedEvent += changed;
myScriptEngine.World.EventManager.OnScriptAtTargetEvent += at_target;
myScriptEngine.World.EventManager.OnScriptNotAtTargetEvent += not_at_target;
myScriptEngine.World.EventManager.OnScriptAtRotTargetEvent += at_rot_target;
myScriptEngine.World.EventManager.OnScriptNotAtRotTargetEvent += not_at_rot_target;
myScriptEngine.World.EventManager.OnScriptMovingStartEvent += moving_start;
myScriptEngine.World.EventManager.OnScriptMovingEndEvent += moving_end;
myScriptEngine.World.EventManager.OnScriptControlEvent += control;
myScriptEngine.World.EventManager.OnScriptColliderStart += collision_start;
myScriptEngine.World.EventManager.OnScriptColliding += collision;
myScriptEngine.World.EventManager.OnScriptCollidingEnd += collision_end;
myScriptEngine.World.EventManager.OnScriptLandColliderStart += land_collision_start;
myScriptEngine.World.EventManager.OnScriptLandColliding += land_collision;
myScriptEngine.World.EventManager.OnScriptLandColliderEnd += land_collision_end;
IMoneyModule money = myScriptEngine.World.RequestModuleInterface<IMoneyModule>();
if (money != null)
{
money.OnObjectPaid+=HandleObjectPaid;
}
}
/// <summary>
/// When an object gets paid by an avatar and generates the paid event,
/// this will pipe it to the script engine
/// </summary>
/// <param name="objectID">Object ID that got paid</param>
/// <param name="agentID">Agent Id that did the paying</param>
/// <param name="amount">Amount paid</param>
private void HandleObjectPaid(UUID objectID, UUID agentID,
int amount)
{
// Since this is an event from a shared module, all scenes will
// get it. But only one has the object in question. The others
// just ignore it.
//
SceneObjectPart part =
myScriptEngine.World.GetSceneObjectPart(objectID);
if (part == null)
return;
if ((part.ScriptEvents & scriptEvents.money) == 0)
part = part.ParentGroup.RootPart;
m_log.Debug("Paid: " + objectID + " from " + agentID + ", amount " + amount);
// part = part.ParentGroup.RootPart;
money(part.LocalId, agentID, amount);
}
/// <summary>
/// Handles piping the proper stuff to The script engine for touching
/// Including DetectedParams
/// </summary>
/// <param name="localID"></param>
/// <param name="originalID"></param>
/// <param name="offsetPos"></param>
/// <param name="remoteClient"></param>
/// <param name="surfaceArgs"></param>
public void touch_start(uint localID, uint originalID, Vector3 offsetPos,
IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs)
{
// Add to queue for all scripts in ObjectID object
DetectParams[] det = new DetectParams[1];
det[0] = new DetectParams();
det[0].Key = remoteClient.AgentId;
det[0].Populate(myScriptEngine.World);
if (originalID == 0)
{
SceneObjectPart part = myScriptEngine.World.GetSceneObjectPart(localID);
if (part == null)
return;
det[0].LinkNum = part.LinkNum;
}
else
{
SceneObjectPart originalPart = myScriptEngine.World.GetSceneObjectPart(originalID);
det[0].LinkNum = originalPart.LinkNum;
}
if (surfaceArgs != null)
{
det[0].SurfaceTouchArgs = surfaceArgs;
}
myScriptEngine.PostObjectEvent(localID, new EventParams(
"touch_start", new Object[] { new LSL_Types.LSLInteger(1) },
det));
}
public void touch(uint localID, uint originalID, Vector3 offsetPos,
IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs)
{
// Add to queue for all scripts in ObjectID object
DetectParams[] det = new DetectParams[1];
det[0] = new DetectParams();
det[0].Key = remoteClient.AgentId;
det[0].Populate(myScriptEngine.World);
det[0].OffsetPos = offsetPos;
if (originalID == 0)
{
SceneObjectPart part = myScriptEngine.World.GetSceneObjectPart(localID);
if (part == null)
return;
det[0].LinkNum = part.LinkNum;
}
else
{
SceneObjectPart originalPart = myScriptEngine.World.GetSceneObjectPart(originalID);
det[0].LinkNum = originalPart.LinkNum;
}
if (surfaceArgs != null)
{
det[0].SurfaceTouchArgs = surfaceArgs;
}
myScriptEngine.PostObjectEvent(localID, new EventParams(
"touch", new Object[] { new LSL_Types.LSLInteger(1) },
det));
}
public void touch_end(uint localID, uint originalID, IClientAPI remoteClient,
SurfaceTouchEventArgs surfaceArgs)
{
// Add to queue for all scripts in ObjectID object
DetectParams[] det = new DetectParams[1];
det[0] = new DetectParams();
det[0].Key = remoteClient.AgentId;
det[0].Populate(myScriptEngine.World);
if (originalID == 0)
{
SceneObjectPart part = myScriptEngine.World.GetSceneObjectPart(localID);
if (part == null)
return;
det[0].LinkNum = part.LinkNum;
}
else
{
SceneObjectPart originalPart = myScriptEngine.World.GetSceneObjectPart(originalID);
det[0].LinkNum = originalPart.LinkNum;
}
if (surfaceArgs != null)
{
det[0].SurfaceTouchArgs = surfaceArgs;
}
myScriptEngine.PostObjectEvent(localID, new EventParams(
"touch_end", new Object[] { new LSL_Types.LSLInteger(1) },
det));
}
public void changed(uint localID, uint change)
{
// Add to queue for all scripts in localID, Object pass change.
myScriptEngine.PostObjectEvent(localID, new EventParams(
"changed",new object[] { new LSL_Types.LSLInteger(change) },
new DetectParams[0]));
}
// state_entry: not processed here
// state_exit: not processed here
public void money(uint localID, UUID agentID, int amount)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"money", new object[] {
new LSL_Types.LSLString(agentID.ToString()),
new LSL_Types.LSLInteger(amount) },
new DetectParams[0]));
}
public void collision_start(uint localID, ColliderArgs col)
{
// Add to queue for all scripts in ObjectID object
List<DetectParams> det = new List<DetectParams>();
foreach (DetectedObject detobj in col.Colliders)
{
DetectParams d = new DetectParams();
d.Key =detobj.keyUUID;
d.Populate(myScriptEngine.World);
det.Add(d);
}
if (det.Count > 0)
myScriptEngine.PostObjectEvent(localID, new EventParams(
"collision_start",
new Object[] { new LSL_Types.LSLInteger(det.Count) },
det.ToArray()));
}
public void collision(uint localID, ColliderArgs col)
{
// Add to queue for all scripts in ObjectID object
List<DetectParams> det = new List<DetectParams>();
foreach (DetectedObject detobj in col.Colliders)
{
DetectParams d = new DetectParams();
d.Key =detobj.keyUUID;
d.Populate(myScriptEngine.World);
det.Add(d);
}
if (det.Count > 0)
myScriptEngine.PostObjectEvent(localID, new EventParams(
"collision", new Object[] { new LSL_Types.LSLInteger(det.Count) },
det.ToArray()));
}
public void collision_end(uint localID, ColliderArgs col)
{
// Add to queue for all scripts in ObjectID object
List<DetectParams> det = new List<DetectParams>();
foreach (DetectedObject detobj in col.Colliders)
{
DetectParams d = new DetectParams();
d.Key =detobj.keyUUID;
d.Populate(myScriptEngine.World);
det.Add(d);
}
if (det.Count > 0)
myScriptEngine.PostObjectEvent(localID, new EventParams(
"collision_end",
new Object[] { new LSL_Types.LSLInteger(det.Count) },
det.ToArray()));
}
public void land_collision_start(uint localID, ColliderArgs col)
{
List<DetectParams> det = new List<DetectParams>();
foreach (DetectedObject detobj in col.Colliders)
{
DetectParams d = new DetectParams();
d.Position = detobj.posVector;
d.Populate(myScriptEngine.World);
det.Add(d);
myScriptEngine.PostObjectEvent(localID, new EventParams(
"land_collision_start",
new Object[] { new LSL_Types.Vector3(d.Position) },
det.ToArray()));
}
}
public void land_collision(uint localID, ColliderArgs col)
{
List<DetectParams> det = new List<DetectParams>();
foreach (DetectedObject detobj in col.Colliders)
{
DetectParams d = new DetectParams();
d.Position = detobj.posVector;
d.Populate(myScriptEngine.World);
det.Add(d);
myScriptEngine.PostObjectEvent(localID, new EventParams(
"land_collision",
new Object[] { new LSL_Types.Vector3(d.Position) },
det.ToArray()));
}
}
public void land_collision_end(uint localID, ColliderArgs col)
{
List<DetectParams> det = new List<DetectParams>();
foreach (DetectedObject detobj in col.Colliders)
{
DetectParams d = new DetectParams();
d.Position = detobj.posVector;
d.Populate(myScriptEngine.World);
det.Add(d);
myScriptEngine.PostObjectEvent(localID, new EventParams(
"land_collision_end",
new Object[] { new LSL_Types.Vector3(d.Position) },
det.ToArray()));
}
}
// timer: not handled here
// listen: not handled here
public void control(UUID itemID, UUID agentID, uint held, uint change)
{
myScriptEngine.PostScriptEvent(itemID, new EventParams(
"control",new object[] {
new LSL_Types.LSLString(agentID.ToString()),
new LSL_Types.LSLInteger(held),
new LSL_Types.LSLInteger(change)},
new DetectParams[0]));
}
public void email(uint localID, UUID itemID, string timeSent,
string address, string subject, string message, int numLeft)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"email",new object[] {
new LSL_Types.LSLString(timeSent),
new LSL_Types.LSLString(address),
new LSL_Types.LSLString(subject),
new LSL_Types.LSLString(message),
new LSL_Types.LSLInteger(numLeft)},
new DetectParams[0]));
}
public void at_target(uint localID, uint handle, Vector3 targetpos,
Vector3 atpos)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"at_target", new object[] {
new LSL_Types.LSLInteger(handle),
new LSL_Types.Vector3(targetpos),
new LSL_Types.Vector3(atpos) },
new DetectParams[0]));
}
public void not_at_target(uint localID)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"not_at_target",new object[0],
new DetectParams[0]));
}
public void at_rot_target(uint localID, uint handle, Quaternion targetrot,
Quaternion atrot)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"at_rot_target", new object[] {
new LSL_Types.LSLInteger(handle),
new LSL_Types.Quaternion(targetrot),
new LSL_Types.Quaternion(atrot) },
new DetectParams[0]));
}
public void not_at_rot_target(uint localID)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"not_at_rot_target",new object[0],
new DetectParams[0]));
}
// run_time_permissions: not handled here
public void attach(uint localID, UUID itemID, UUID avatar)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"attach",new object[] {
new LSL_Types.LSLString(avatar.ToString()) },
new DetectParams[0]));
}
// dataserver: not handled here
// link_message: not handled here
public void moving_start(uint localID)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"moving_start",new object[0],
new DetectParams[0]));
}
public void moving_end(uint localID)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"moving_end",new object[0],
new DetectParams[0]));
}
// object_rez: not handled here
// remote_data: not handled here
// http_response: not handled here
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using ISLA2.Areas.HelpPage.ModelDescriptions;
using ISLA2.Areas.HelpPage.Models;
namespace ISLA2.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright (c) 2015 ZZZ Projects. All rights reserved
// Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods)
// Website: http://www.zzzprojects.com/
// Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927
// All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library
using System;
using System.IO;
using System.Linq;
public static partial class Extensions
{
/// <summary>
/// Returns an enumerable collection of directory names in a specified @this.
/// </summary>
/// <param name="this">The directory to search.</param>
/// <param name="predicate">The predicate.</param>
/// <returns>
/// An enumerable collection of the full names (including paths) for the directories in the directory specified by
/// <paramref
/// name="this" />
/// .
/// </returns>
/// ###
/// <exception cref="T:System.ArgumentException">
/// <paramref name="this " />is a zero-length string, contains only
/// white space, or contains invalid characters as defined by
/// <see
/// cref="M:System.IO.Path.GetInvalidPathChars" />
/// .
/// </exception>
/// ###
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="this" /> is null.
/// </exception>
/// ###
/// <exception cref="T:System.IO.DirectoryNotFoundException">
/// <paramref name="this" /> is invalid, such as
/// referring to an unmapped drive.
/// </exception>
/// ###
/// <exception cref="T:System.IO.IOException">
/// <paramref name="this" /> is a file name.
/// </exception>
/// ###
/// <exception cref="T:System.IO.PathTooLongException">
/// The specified @this, file name, or combined exceed the
/// system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters
/// and file names must be less than 260 characters.
/// </exception>
/// ###
/// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception>
/// ###
/// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
public static DirectoryInfo[] GetDirectoriesWhere(this DirectoryInfo @this, Func<DirectoryInfo, bool> predicate)
{
return Directory.EnumerateDirectories(@this.FullName).Select(x => new DirectoryInfo(x)).Where(x => predicate(x)).ToArray();
}
/// <summary>
/// Returns an enumerable collection of directory names that match a search pattern in a specified @this.
/// </summary>
/// <param name="this">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in
/// <paramref name="this" />.
/// </param>
/// <param name="predicate">The predicate.</param>
/// <returns>
/// An enumerable collection of the full names (including paths) for the directories in the directory specified by
/// <paramref
/// name="this" />
/// and that match the specified search pattern.
/// </returns>
/// <example>
/// <code>
/// using System;
/// using System.IO;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_GetDirectoriesWhere
/// {
/// [TestMethod]
/// public void GetDirectoriesWhere()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_GetDirectories"));
/// Directory.CreateDirectory(root.FullName);
/// root.CreateSubdirectory("DirFizz123");
/// root.CreateSubdirectory("DirBuzz123");
/// root.CreateSubdirectory("DirNotFound123");
///
/// // Exemples
/// DirectoryInfo[] result = root.GetDirectoriesWhere(x => x.Name.StartsWith("DirFizz") || x.Name.StartsWith("DirBuzz"));
///
/// // Unit Test
/// Assert.AreEqual(2, result.Length);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using System;
/// using System.IO;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_GetDirectoriesWhere
/// {
/// [TestMethod]
/// public void GetDirectoriesWhere()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_GetDirectories"));
/// Directory.CreateDirectory(root.FullName);
/// root.CreateSubdirectory("DirFizz123");
/// root.CreateSubdirectory("DirBuzz123");
/// root.CreateSubdirectory("DirNotFound123");
///
/// // Exemples
/// DirectoryInfo[] result = root.GetDirectoriesWhere(x => x.Name.StartsWith("DirFizz") || x.Name.StartsWith("DirBuzz"));
///
/// // Unit Test
/// Assert.AreEqual(2, result.Length);
/// }
/// }
/// }
/// </code>
/// </example>
/// ###
/// <exception cref="T:System.ArgumentException">
/// <paramref name="this " />is a zero-length string, contains only
/// white space, or contains invalid characters as defined by
/// <see
/// cref="M:System.IO.Path.GetInvalidPathChars" />
/// .- or -<paramref name="searchPattern" /> does not contain a valid pattern.
/// </exception>
/// ###
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="this" /> is null.-or-
/// <paramref name="searchPattern" /> is null.
/// </exception>
/// ###
/// <exception cref="T:System.IO.DirectoryNotFoundException">
/// <paramref name="this" /> is invalid, such as
/// referring to an unmapped drive.
/// </exception>
/// ###
/// <exception cref="T:System.IO.IOException">
/// <paramref name="this" /> is a file name.
/// </exception>
/// ###
/// <exception cref="T:System.IO.PathTooLongException">
/// The specified @this, file name, or combined exceed the
/// system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters
/// and file names must be less than 260 characters.
/// </exception>
/// ###
/// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception>
/// ###
/// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
public static DirectoryInfo[] GetDirectoriesWhere(this DirectoryInfo @this, String searchPattern, Func<DirectoryInfo, bool> predicate)
{
return Directory.EnumerateDirectories(@this.FullName, searchPattern).Select(x => new DirectoryInfo(x)).Where(x => predicate(x)).ToArray();
}
/// <summary>
/// Returns an enumerable collection of directory names that match a search pattern in a specified @this, and
/// optionally searches subdirectories.
/// </summary>
/// <param name="this">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in
/// <paramref name="this" />.
/// </param>
/// <param name="searchOption">
/// One of the enumeration values that specifies whether the search operation should
/// include only the current directory or should include all subdirectories.The default value is
/// <see
/// cref="F:System.IO.SearchOption.TopDirectoryOnly" />
/// .
/// </param>
/// <param name="predicate">The predicate.</param>
/// <returns>
/// An enumerable collection of the full names (including paths) for the directories in the directory specified by
/// <paramref
/// name="this" />
/// and that match the specified search pattern and option.
/// </returns>
/// <example>
/// <code>
/// using System;
/// using System.IO;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_GetDirectoriesWhere
/// {
/// [TestMethod]
/// public void GetDirectoriesWhere()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_GetDirectories"));
/// Directory.CreateDirectory(root.FullName);
/// root.CreateSubdirectory("DirFizz123");
/// root.CreateSubdirectory("DirBuzz123");
/// root.CreateSubdirectory("DirNotFound123");
///
/// // Exemples
/// DirectoryInfo[] result = root.GetDirectoriesWhere(x => x.Name.StartsWith("DirFizz") || x.Name.StartsWith("DirBuzz"));
///
/// // Unit Test
/// Assert.AreEqual(2, result.Length);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using System;
/// using System.IO;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_GetDirectoriesWhere
/// {
/// [TestMethod]
/// public void GetDirectoriesWhere()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_GetDirectories"));
/// Directory.CreateDirectory(root.FullName);
/// root.CreateSubdirectory("DirFizz123");
/// root.CreateSubdirectory("DirBuzz123");
/// root.CreateSubdirectory("DirNotFound123");
///
/// // Exemples
/// DirectoryInfo[] result = root.GetDirectoriesWhere(x => x.Name.StartsWith("DirFizz") || x.Name.StartsWith("DirBuzz"));
///
/// // Unit Test
/// Assert.AreEqual(2, result.Length);
/// }
/// }
/// }
/// </code>
/// </example>
/// ###
/// <exception cref="T:System.ArgumentException">
/// <paramref name="this " />is a zero-length string, contains only
/// white space, or contains invalid characters as defined by
/// <see
/// cref="M:System.IO.Path.GetInvalidPathChars" />
/// .- or -<paramref name="searchPattern" /> does not contain a valid pattern.
/// </exception>
/// ###
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="this" /> is null.-or-
/// <paramref name="searchPattern" /> is null.
/// </exception>
/// ###
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="searchOption" /> is not a valid
/// <see cref="T:System.IO.SearchOption" /> value.
/// </exception>
/// ###
/// <exception cref="T:System.IO.DirectoryNotFoundException">
/// <paramref name="this" /> is invalid, such as
/// referring to an unmapped drive.
/// </exception>
/// ###
/// <exception cref="T:System.IO.IOException">
/// <paramref name="this" /> is a file name.
/// </exception>
/// ###
/// <exception cref="T:System.IO.PathTooLongException">
/// The specified @this, file name, or combined exceed the
/// system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters
/// and file names must be less than 260 characters.
/// </exception>
/// ###
/// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception>
/// ###
/// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
public static DirectoryInfo[] GetDirectoriesWhere(this DirectoryInfo @this, String searchPattern, SearchOption searchOption, Func<DirectoryInfo, bool> predicate)
{
return Directory.EnumerateDirectories(@this.FullName, searchPattern, searchOption).Select(x => new DirectoryInfo(x)).Where(x => predicate(x)).ToArray();
}
/// <summary>
/// Returns an enumerable collection of directory names that match a search pattern in a specified @this.
/// </summary>
/// <param name="this">The directory to search.</param>
/// <param name="searchPatterns">The search string to match against the names of directories in.</param>
/// <param name="predicate">The predicate.</param>
/// <returns>
/// An enumerable collection of the full names (including paths) for the directories in the directory specified by
/// <paramref
/// name="this" />
/// and that match the specified search pattern.
/// </returns>
/// <example>
/// <code>
/// using System;
/// using System.IO;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_GetDirectoriesWhere
/// {
/// [TestMethod]
/// public void GetDirectoriesWhere()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_GetDirectories"));
/// Directory.CreateDirectory(root.FullName);
/// root.CreateSubdirectory("DirFizz123");
/// root.CreateSubdirectory("DirBuzz123");
/// root.CreateSubdirectory("DirNotFound123");
///
/// // Exemples
/// DirectoryInfo[] result = root.GetDirectoriesWhere(x => x.Name.StartsWith("DirFizz") || x.Name.StartsWith("DirBuzz"));
///
/// // Unit Test
/// Assert.AreEqual(2, result.Length);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using System;
/// using System.IO;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_GetDirectoriesWhere
/// {
/// [TestMethod]
/// public void GetDirectoriesWhere()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_GetDirectories"));
/// Directory.CreateDirectory(root.FullName);
/// root.CreateSubdirectory("DirFizz123");
/// root.CreateSubdirectory("DirBuzz123");
/// root.CreateSubdirectory("DirNotFound123");
///
/// // Exemples
/// DirectoryInfo[] result = root.GetDirectoriesWhere(x => x.Name.StartsWith("DirFizz") || x.Name.StartsWith("DirBuzz"));
///
/// // Unit Test
/// Assert.AreEqual(2, result.Length);
/// }
/// }
/// }
/// </code>
/// </example>
/// ###
/// <param name="searchPattern">
/// The search string to match against the names of directories in
/// <paramref name="this" />.
/// </param>
/// ###
/// <exception cref="T:System.ArgumentException">
/// <paramref name="this " />is a zero-length string, contains only
/// white space, or contains invalid characters as defined by
/// <see
/// cref="M:System.IO.Path.GetInvalidPathChars" />
/// .- or -<paramref name="searchPattern" /> does not contain a valid pattern.
/// </exception>
/// ###
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="this" /> is null.-or-
/// <paramref name="searchPattern" /> is null.
/// </exception>
/// ###
/// <exception cref="T:System.IO.DirectoryNotFoundException">
/// <paramref name="this" /> is invalid, such as
/// referring to an unmapped drive.
/// </exception>
/// ###
/// <exception cref="T:System.IO.IOException">
/// <paramref name="this" /> is a file name.
/// </exception>
/// ###
/// <exception cref="T:System.IO.PathTooLongException">
/// The specified @this, file name, or combined exceed the
/// system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters
/// and file names must be less than 260 characters.
/// </exception>
/// ###
/// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception>
/// ###
/// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
public static DirectoryInfo[] GetDirectoriesWhere(this DirectoryInfo @this, String[] searchPatterns, Func<DirectoryInfo, bool> predicate)
{
return searchPatterns.SelectMany(x => @this.GetDirectories(x)).Distinct().Where(x => predicate(x)).ToArray();
}
/// <summary>
/// Returns an enumerable collection of directory names that match a search pattern in a specified @this, and
/// optionally searches subdirectories.
/// </summary>
/// <param name="this">The directory to search.</param>
/// <param name="searchPatterns">
/// The search string to match against the names of directories in
/// <paramref name="this" />.
/// </param>
/// <param name="searchOption">
/// One of the enumeration values that specifies whether the search operation should
/// include only the current directory or should include all subdirectories.The default value is
/// <see
/// cref="F:System.IO.SearchOption.TopDirectoryOnly" />
/// .
/// </param>
/// <param name="predicate">The predicate.</param>
/// <returns>
/// An enumerable collection of the full names (including paths) for the directories in the directory specified by
/// <paramref
/// name="this" />
/// and that match the specified search pattern and option.
/// </returns>
/// <example>
/// <code>
/// using System;
/// using System.IO;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_GetDirectoriesWhere
/// {
/// [TestMethod]
/// public void GetDirectoriesWhere()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_GetDirectories"));
/// Directory.CreateDirectory(root.FullName);
/// root.CreateSubdirectory("DirFizz123");
/// root.CreateSubdirectory("DirBuzz123");
/// root.CreateSubdirectory("DirNotFound123");
///
/// // Exemples
/// DirectoryInfo[] result = root.GetDirectoriesWhere(x => x.Name.StartsWith("DirFizz") || x.Name.StartsWith("DirBuzz"));
///
/// // Unit Test
/// Assert.AreEqual(2, result.Length);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using System;
/// using System.IO;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_GetDirectoriesWhere
/// {
/// [TestMethod]
/// public void GetDirectoriesWhere()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_GetDirectories"));
/// Directory.CreateDirectory(root.FullName);
/// root.CreateSubdirectory("DirFizz123");
/// root.CreateSubdirectory("DirBuzz123");
/// root.CreateSubdirectory("DirNotFound123");
///
/// // Exemples
/// DirectoryInfo[] result = root.GetDirectoriesWhere(x => x.Name.StartsWith("DirFizz") || x.Name.StartsWith("DirBuzz"));
///
/// // Unit Test
/// Assert.AreEqual(2, result.Length);
/// }
/// }
/// }
/// </code>
/// </example>
/// ###
/// <exception cref="T:System.ArgumentException">
/// <paramref name="this " />is a zero-length string, contains only
/// white space, or contains invalid characters as defined by
/// <see
/// cref="M:System.IO.Path.GetInvalidPathChars" />
/// .- or -<paramref name="searchPattern" /> does not contain a valid pattern.
/// </exception>
/// ###
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="this" /> is null.-or-
/// <paramref name="searchPattern" /> is null.
/// </exception>
/// ###
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="searchOption" /> is not a valid
/// <see cref="T:System.IO.SearchOption" /> value.
/// </exception>
/// ###
/// <exception cref="T:System.IO.DirectoryNotFoundException">
/// <paramref name="this" /> is invalid, such as
/// referring to an unmapped drive.
/// </exception>
/// ###
/// <exception cref="T:System.IO.IOException">
/// <paramref name="this" /> is a file name.
/// </exception>
/// ###
/// <exception cref="T:System.IO.PathTooLongException">
/// The specified @this, file name, or combined exceed the
/// system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters
/// and file names must be less than 260 characters.
/// </exception>
/// ###
/// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception>
/// ###
/// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
public static DirectoryInfo[] GetDirectoriesWhere(this DirectoryInfo @this, String[] searchPatterns, SearchOption searchOption, Func<DirectoryInfo, bool> predicate)
{
return searchPatterns.SelectMany(x => @this.GetDirectories(x, searchOption)).Distinct().Where(x => predicate(x)).ToArray();
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlReaderSettings.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System.IO;
using System.Diagnostics;
using System.Security.Permissions;
#if !SILVERLIGHT
using Microsoft.Win32;
using System.Globalization;
using System.Security;
using System.Xml.Schema;
using System.Xml.XmlConfiguration;
#endif
using System.Runtime.Versioning;
namespace System.Xml {
// XmlReaderSettings class specifies basic features of an XmlReader.
#if !SILVERLIGHT
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
#endif
public sealed class XmlReaderSettings {
//
// Fields
//
#if ASYNC || FEATURE_NETCORE
bool useAsync;
#endif
// Nametable
XmlNameTable nameTable;
// XmlResolver
XmlResolver xmlResolver;
// Text settings
int lineNumberOffset;
int linePositionOffset;
// Conformance settings
ConformanceLevel conformanceLevel;
bool checkCharacters;
long maxCharactersInDocument;
long maxCharactersFromEntities;
// Filtering settings
bool ignoreWhitespace;
bool ignorePIs;
bool ignoreComments;
// security settings
DtdProcessing dtdProcessing;
#if !SILVERLIGHT
//Validation settings
ValidationType validationType;
XmlSchemaValidationFlags validationFlags;
XmlSchemaSet schemas;
ValidationEventHandler valEventHandler;
#endif
// other settings
bool closeInput;
// read-only flag
bool isReadOnly;
//
// Constructor
//
public XmlReaderSettings() {
Initialize();
}
#if !FEATURE_LEGACYNETCF
// introduced for supporting design-time loading of phone assemblies
[Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
#endif
public XmlReaderSettings(XmlResolver resolver) {
Initialize(resolver);
}
//
// Properties
//
#if ASYNC || FEATURE_NETCORE
public bool Async {
get {
return useAsync;
}
set {
CheckReadOnly("Async");
useAsync = value;
}
}
#endif
// Nametable
public XmlNameTable NameTable {
get {
return nameTable;
}
set {
CheckReadOnly("NameTable");
nameTable = value;
}
}
#if !SILVERLIGHT
// XmlResolver
internal bool IsXmlResolverSet {
get;
set; // keep set internal as we need to call it from the schema validation code
}
#endif
public XmlResolver XmlResolver {
set {
CheckReadOnly("XmlResolver");
xmlResolver = value;
#if !SILVERLIGHT
IsXmlResolverSet = true;
#endif
}
}
internal XmlResolver GetXmlResolver() {
return xmlResolver;
}
#if !SILVERLIGHT
//This is used by get XmlResolver in Xsd.
//Check if the config set to prohibit default resovler
//notice we must keep GetXmlResolver() to avoid dead lock when init System.Config.ConfigurationManager
internal XmlResolver GetXmlResolver_CheckConfig() {
if (System.Xml.XmlConfiguration.XmlReaderSection.ProhibitDefaultUrlResolver && !IsXmlResolverSet)
return null;
else
return xmlResolver;
}
#endif
// Text settings
public int LineNumberOffset {
get {
return lineNumberOffset;
}
set {
CheckReadOnly("LineNumberOffset");
lineNumberOffset = value;
}
}
public int LinePositionOffset {
get {
return linePositionOffset;
}
set {
CheckReadOnly("LinePositionOffset");
linePositionOffset = value;
}
}
// Conformance settings
public ConformanceLevel ConformanceLevel {
get {
return conformanceLevel;
}
set {
CheckReadOnly("ConformanceLevel");
if ((uint)value > (uint)ConformanceLevel.Document) {
throw new ArgumentOutOfRangeException("value");
}
conformanceLevel = value;
}
}
public bool CheckCharacters {
get {
return checkCharacters;
}
set {
CheckReadOnly("CheckCharacters");
checkCharacters = value;
}
}
public long MaxCharactersInDocument {
get {
return maxCharactersInDocument;
}
set {
CheckReadOnly("MaxCharactersInDocument");
if (value < 0) {
throw new ArgumentOutOfRangeException("value");
}
maxCharactersInDocument = value;
}
}
public long MaxCharactersFromEntities {
get {
return maxCharactersFromEntities;
}
set {
CheckReadOnly("MaxCharactersFromEntities");
if (value < 0) {
throw new ArgumentOutOfRangeException("value");
}
maxCharactersFromEntities = value;
}
}
// Filtering settings
public bool IgnoreWhitespace {
get {
return ignoreWhitespace;
}
set {
CheckReadOnly("IgnoreWhitespace");
ignoreWhitespace = value;
}
}
public bool IgnoreProcessingInstructions {
get {
return ignorePIs;
}
set {
CheckReadOnly("IgnoreProcessingInstructions");
ignorePIs = value;
}
}
public bool IgnoreComments {
get {
return ignoreComments;
}
set {
CheckReadOnly("IgnoreComments");
ignoreComments = value;
}
}
#if !SILVERLIGHT
[Obsolete("Use XmlReaderSettings.DtdProcessing property instead.")]
public bool ProhibitDtd {
get {
return dtdProcessing == DtdProcessing.Prohibit;
}
set {
CheckReadOnly("ProhibitDtd");
dtdProcessing = value ? DtdProcessing.Prohibit : DtdProcessing.Parse;
}
}
#endif
public DtdProcessing DtdProcessing {
get {
return dtdProcessing;
}
set {
CheckReadOnly("DtdProcessing");
if ((uint)value > (uint)DtdProcessing.Parse) {
throw new ArgumentOutOfRangeException("value");
}
dtdProcessing = value;
}
}
public bool CloseInput {
get {
return closeInput;
}
set {
CheckReadOnly("CloseInput");
closeInput = value;
}
}
#if !SILVERLIGHT
public ValidationType ValidationType {
get {
return validationType;
}
set {
CheckReadOnly("ValidationType");
if ((uint)value > (uint)ValidationType.Schema) {
throw new ArgumentOutOfRangeException("value");
}
validationType = value;
}
}
public XmlSchemaValidationFlags ValidationFlags {
get {
return validationFlags;
}
set {
CheckReadOnly("ValidationFlags");
if ((uint)value > (uint)(XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ProcessSchemaLocation |
XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.AllowXmlAttributes)) {
throw new ArgumentOutOfRangeException("value");
}
validationFlags = value;
}
}
public XmlSchemaSet Schemas {
get {
if (schemas == null) {
schemas = new XmlSchemaSet();
}
return schemas;
}
set {
CheckReadOnly("Schemas");
schemas = value;
}
}
public event ValidationEventHandler ValidationEventHandler {
add {
CheckReadOnly("ValidationEventHandler");
valEventHandler += value;
}
remove {
CheckReadOnly("ValidationEventHandler");
valEventHandler -= value;
}
}
#endif
//
// Public methods
//
public void Reset() {
CheckReadOnly("Reset");
Initialize();
}
public XmlReaderSettings Clone() {
XmlReaderSettings clonedSettings = this.MemberwiseClone() as XmlReaderSettings;
clonedSettings.ReadOnly = false;
return clonedSettings;
}
//
// Internal methods
//
#if !SILVERLIGHT
internal ValidationEventHandler GetEventHandler() {
return valEventHandler;
}
#endif
#if !SILVERLIGHT
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
#endif
internal XmlReader CreateReader(String inputUri, XmlParserContext inputContext) {
if (inputUri == null) {
throw new ArgumentNullException("inputUri");
}
if (inputUri.Length == 0) {
throw new ArgumentException(Res.GetString(Res.XmlConvert_BadUri), "inputUri");
}
// resolve and open the url
XmlResolver tmpResolver = this.GetXmlResolver();
if (tmpResolver == null) {
tmpResolver = CreateDefaultResolver();
}
// create text XML reader
XmlReader reader = new XmlTextReaderImpl(inputUri, this, inputContext, tmpResolver);
#if !SILVERLIGHT
// wrap with validating reader
if (this.ValidationType != ValidationType.None) {
reader = AddValidation(reader);
}
#endif
#if ASYNC
if (useAsync) {
reader = XmlAsyncCheckReader.CreateAsyncCheckWrapper(reader);
}
#endif
return reader;
}
internal XmlReader CreateReader(Stream input, Uri baseUri, string baseUriString, XmlParserContext inputContext) {
if (input == null) {
throw new ArgumentNullException("input");
}
if (baseUriString == null) {
if (baseUri == null) {
baseUriString = string.Empty;
}
else {
baseUriString = baseUri.ToString();
}
}
// create text XML reader
XmlReader reader = new XmlTextReaderImpl(input, null, 0, this, baseUri, baseUriString, inputContext, closeInput);
#if !SILVERLIGHT
// wrap with validating reader
if (this.ValidationType != ValidationType.None) {
reader = AddValidation(reader);
}
#endif
#if ASYNC
if (useAsync) {
reader = XmlAsyncCheckReader.CreateAsyncCheckWrapper(reader);
}
#endif
return reader;
}
internal XmlReader CreateReader(TextReader input, string baseUriString, XmlParserContext inputContext) {
if (input == null) {
throw new ArgumentNullException("input");
}
if (baseUriString == null) {
baseUriString = string.Empty;
}
// create xml text reader
XmlReader reader = new XmlTextReaderImpl(input, this, baseUriString, inputContext);
#if !SILVERLIGHT
// wrap with validating reader
if (this.ValidationType != ValidationType.None) {
reader = AddValidation(reader);
}
#endif
#if ASYNC
if (useAsync) {
reader = XmlAsyncCheckReader.CreateAsyncCheckWrapper(reader);
}
#endif
return reader;
}
internal XmlReader CreateReader(XmlReader reader) {
if (reader == null) {
throw new ArgumentNullException("reader");
}
#if !ASYNC || SILVERLIGHT || FEATURE_NETCORE
// wrap with conformance layer (if needed)
return AddConformanceWrapper(reader);
#else
return AddValidationAndConformanceWrapper(reader);
#endif // !ASYNC || SILVERLIGHT || FEATURE_NETCORE
}
internal bool ReadOnly {
get {
return isReadOnly;
}
set {
isReadOnly = value;
}
}
void CheckReadOnly(string propertyName) {
if (isReadOnly) {
throw new XmlException(Res.Xml_ReadOnlyProperty, this.GetType().Name + '.' + propertyName);
}
}
//
// Private methods
//
void Initialize() {
Initialize(null);
}
void Initialize(XmlResolver resolver) {
nameTable = null;
#if !SILVERLIGHT
if (!EnableLegacyXmlSettings())
{
xmlResolver = resolver;
// limit the entity resolving to 10 million character. the caller can still
// override it to any other value or set it to zero for unlimiting it
maxCharactersFromEntities = (long) 1e7;
}
else
#endif
{
xmlResolver = (resolver == null ? CreateDefaultResolver() : resolver);
maxCharactersFromEntities = 0;
}
lineNumberOffset = 0;
linePositionOffset = 0;
checkCharacters = true;
conformanceLevel = ConformanceLevel.Document;
ignoreWhitespace = false;
ignorePIs = false;
ignoreComments = false;
dtdProcessing = DtdProcessing.Prohibit;
closeInput = false;
maxCharactersInDocument = 0;
#if !SILVERLIGHT
schemas = null;
validationType = ValidationType.None;
validationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints;
validationFlags |= XmlSchemaValidationFlags.AllowXmlAttributes;
#endif
#if ASYNC || FEATURE_NETCORE
useAsync = false;
#endif
isReadOnly = false;
#if !SILVERLIGHT
IsXmlResolverSet = false;
#endif
}
static XmlResolver CreateDefaultResolver() {
#if SILVERLIGHT
return new XmlXapResolver();
#else
return new XmlUrlResolver();
#endif
}
#if !SILVERLIGHT
internal XmlReader AddValidation(XmlReader reader) {
if (this.validationType == ValidationType.Schema) {
XmlResolver resolver = GetXmlResolver_CheckConfig();
if (resolver == null &&
!this.IsXmlResolverSet &&
!EnableLegacyXmlSettings())
{
resolver = new XmlUrlResolver();
}
reader = new XsdValidatingReader(reader, resolver, this);
}
else if (this.validationType == ValidationType.DTD) {
reader = CreateDtdValidatingReader(reader);
}
return reader;
}
private XmlReader AddValidationAndConformanceWrapper(XmlReader reader) {
// wrap with DTD validating reader
if (this.validationType == ValidationType.DTD) {
reader = CreateDtdValidatingReader(reader);
}
// add conformance checking (must go after DTD validation because XmlValidatingReader works only on XmlTextReader),
// but before XSD validation because of typed value access
reader = AddConformanceWrapper(reader);
if (this.validationType == ValidationType.Schema) {
reader = new XsdValidatingReader(reader, GetXmlResolver_CheckConfig(), this);
}
return reader;
}
private XmlValidatingReaderImpl CreateDtdValidatingReader(XmlReader baseReader) {
return new XmlValidatingReaderImpl(baseReader, this.GetEventHandler(), (this.ValidationFlags & XmlSchemaValidationFlags.ProcessIdentityConstraints) != 0);
}
#endif // !SILVERLIGHT
internal XmlReader AddConformanceWrapper(XmlReader baseReader) {
XmlReaderSettings baseReaderSettings = baseReader.Settings;
bool checkChars = false;
bool noWhitespace = false;
bool noComments = false;
bool noPIs = false;
DtdProcessing dtdProc = (DtdProcessing)(-1);
bool needWrap = false;
if (baseReaderSettings == null) {
#pragma warning disable 618
#if SILVERLIGHT
if (this.conformanceLevel != ConformanceLevel.Auto) {
throw new InvalidOperationException(Res.GetString(Res.Xml_IncompatibleConformanceLevel, this.conformanceLevel.ToString()));
}
#else
if (this.conformanceLevel != ConformanceLevel.Auto && this.conformanceLevel != XmlReader.GetV1ConformanceLevel(baseReader)) {
throw new InvalidOperationException(Res.GetString(Res.Xml_IncompatibleConformanceLevel, this.conformanceLevel.ToString()));
}
#endif
#if !SILVERLIGHT
// get the V1 XmlTextReader ref
XmlTextReader v1XmlTextReader = baseReader as XmlTextReader;
if (v1XmlTextReader == null) {
XmlValidatingReader vr = baseReader as XmlValidatingReader;
if (vr != null) {
v1XmlTextReader = (XmlTextReader)vr.Reader;
}
}
#endif
// assume the V1 readers already do all conformance checking;
// wrap only if IgnoreWhitespace, IgnoreComments, IgnoreProcessingInstructions or ProhibitDtd is true;
if (this.ignoreWhitespace) {
WhitespaceHandling wh = WhitespaceHandling.All;
#if !SILVERLIGHT
// special-case our V1 readers to see if whey already filter whitespaces
if (v1XmlTextReader != null) {
wh = v1XmlTextReader.WhitespaceHandling;
}
#endif
if (wh == WhitespaceHandling.All) {
noWhitespace = true;
needWrap = true;
}
}
if (this.ignoreComments) {
noComments = true;
needWrap = true;
}
if (this.ignorePIs) {
noPIs = true;
needWrap = true;
}
// DTD processing
DtdProcessing baseDtdProcessing = DtdProcessing.Parse;
#if !SILVERLIGHT
if (v1XmlTextReader != null) {
baseDtdProcessing = v1XmlTextReader.DtdProcessing;
}
#endif
if ((this.dtdProcessing == DtdProcessing.Prohibit && baseDtdProcessing != DtdProcessing.Prohibit) ||
(this.dtdProcessing == DtdProcessing.Ignore && baseDtdProcessing == DtdProcessing.Parse)) {
dtdProc = this.dtdProcessing;
needWrap = true;
}
#pragma warning restore 618
}
else {
if (this.conformanceLevel != baseReaderSettings.ConformanceLevel && this.conformanceLevel != ConformanceLevel.Auto) {
throw new InvalidOperationException(Res.GetString(Res.Xml_IncompatibleConformanceLevel, this.conformanceLevel.ToString()));
}
if (this.checkCharacters && !baseReaderSettings.CheckCharacters) {
checkChars = true;
needWrap = true;
}
if (this.ignoreWhitespace && !baseReaderSettings.IgnoreWhitespace) {
noWhitespace = true;
needWrap = true;
}
if (this.ignoreComments && !baseReaderSettings.IgnoreComments) {
noComments = true;
needWrap = true;
}
if (this.ignorePIs && !baseReaderSettings.IgnoreProcessingInstructions) {
noPIs = true;
needWrap = true;
}
if ((this.dtdProcessing == DtdProcessing.Prohibit && baseReaderSettings.DtdProcessing != DtdProcessing.Prohibit) ||
(this.dtdProcessing == DtdProcessing.Ignore && baseReaderSettings.DtdProcessing == DtdProcessing.Parse)) {
dtdProc = this.dtdProcessing;
needWrap = true;
}
}
if (needWrap) {
IXmlNamespaceResolver readerAsNSResolver = baseReader as IXmlNamespaceResolver;
if (readerAsNSResolver != null) {
return new XmlCharCheckingReaderWithNS(baseReader, readerAsNSResolver, checkChars, noWhitespace, noComments, noPIs, dtdProc);
}
else {
return new XmlCharCheckingReader(baseReader, checkChars, noWhitespace, noComments, noPIs, dtdProc);
}
}
else {
return baseReader;
}
}
#if !SILVERLIGHT
private static bool? s_enableLegacyXmlSettings = null;
static internal bool EnableLegacyXmlSettings()
{
if (s_enableLegacyXmlSettings.HasValue)
{
return s_enableLegacyXmlSettings.Value;
}
if (!System.Xml.BinaryCompatibility.TargetsAtLeast_Desktop_V4_5_2)
{
s_enableLegacyXmlSettings = true;
return s_enableLegacyXmlSettings.Value;
}
bool enableSettings = false; // default value
if (!ReadSettingsFromRegistry(Registry.LocalMachine, ref enableSettings))
{
// still ok if this call return false too as we'll use the default value which is false
ReadSettingsFromRegistry(Registry.CurrentUser, ref enableSettings);
}
s_enableLegacyXmlSettings = enableSettings;
return s_enableLegacyXmlSettings.Value;
}
[RegistryPermission(SecurityAction.Assert, Unrestricted = true)]
[SecuritySafeCritical]
private static bool ReadSettingsFromRegistry(RegistryKey hive, ref bool value)
{
const string regValueName = "EnableLegacyXmlSettings";
const string regValuePath = @"SOFTWARE\Microsoft\.NETFramework\XML";
try
{
using (RegistryKey xmlRegKey = hive.OpenSubKey(regValuePath, false))
{
if (xmlRegKey != null)
{
if (xmlRegKey.GetValueKind(regValueName) == RegistryValueKind.DWord)
{
value = ((int)xmlRegKey.GetValue(regValueName)) == 1;
return true;
}
}
}
}
catch { /* use the default if we couldn't read the key */ }
return false;
}
#endif // SILVERLIGHT
}
}
| |
// 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.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.Metadata.Tests;
using Xunit;
namespace System.Reflection.PortableExecutable.Tests
{
public class PEReaderTests
{
[Fact]
public void Ctor()
{
Assert.Throws<ArgumentNullException>(() => new PEReader(null, PEStreamOptions.Default));
var invalid = new MemoryStream(new byte[] { 1, 2, 3, 4 });
// the stream should not be disposed if the arguments are bad
Assert.Throws<ArgumentOutOfRangeException>(() => new PEReader(invalid, (PEStreamOptions)int.MaxValue));
Assert.True(invalid.CanRead);
// no BadImageFormatException if we're prefetching the entire image:
var peReader0 = new PEReader(invalid, PEStreamOptions.PrefetchEntireImage | PEStreamOptions.LeaveOpen);
Assert.True(invalid.CanRead);
Assert.Throws<BadImageFormatException>(() => peReader0.PEHeaders);
invalid.Position = 0;
// BadImageFormatException if we're prefetching the entire image and metadata:
Assert.Throws<BadImageFormatException>(() => new PEReader(invalid, PEStreamOptions.PrefetchEntireImage | PEStreamOptions.PrefetchMetadata | PEStreamOptions.LeaveOpen));
Assert.True(invalid.CanRead);
invalid.Position = 0;
// the stream should be disposed if the content is bad:
Assert.Throws<BadImageFormatException>(() => new PEReader(invalid, PEStreamOptions.PrefetchMetadata));
Assert.False(invalid.CanRead);
// the stream should not be disposed if we specified LeaveOpen flag:
invalid = new MemoryStream(new byte[] { 1, 2, 3, 4 });
Assert.Throws<BadImageFormatException>(() => new PEReader(invalid, PEStreamOptions.PrefetchMetadata | PEStreamOptions.LeaveOpen));
Assert.True(invalid.CanRead);
// valid metadata:
var valid = new MemoryStream(Misc.Members);
var peReader = new PEReader(valid, PEStreamOptions.Default);
Assert.True(valid.CanRead);
peReader.Dispose();
Assert.False(valid.CanRead);
}
[Fact]
public void Ctor_Streams()
{
Assert.Throws<ArgumentException>(() => new PEReader(new CustomAccessMemoryStream(canRead: false, canSeek: false, canWrite: false)));
Assert.Throws<ArgumentException>(() => new PEReader(new CustomAccessMemoryStream(canRead: true, canSeek: false, canWrite: false)));
var s = new CustomAccessMemoryStream(canRead: true, canSeek: true, canWrite: false);
new PEReader(s);
new PEReader(s, PEStreamOptions.Default, 0);
Assert.Throws<ArgumentOutOfRangeException>(() => new PEReader(s, PEStreamOptions.Default, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new PEReader(s, PEStreamOptions.Default, 1));
}
[Fact]
public unsafe void Ctor_Loaded()
{
byte b = 1;
Assert.True(new PEReader(&b, 1, isLoadedImage: true).IsLoadedImage);
Assert.False(new PEReader(&b, 1, isLoadedImage: false).IsLoadedImage);
Assert.True(new PEReader(new MemoryStream(), PEStreamOptions.IsLoadedImage).IsLoadedImage);
Assert.False(new PEReader(new MemoryStream()).IsLoadedImage);
}
[Fact]
public void FromEmptyStream()
{
Assert.Throws<BadImageFormatException>(() => new PEReader(new MemoryStream(), PEStreamOptions.PrefetchMetadata));
Assert.Throws<BadImageFormatException>(() => new PEReader(new MemoryStream(), PEStreamOptions.PrefetchMetadata | PEStreamOptions.PrefetchEntireImage));
}
[Fact(Skip = "https://github.com/dotnet/corefx/issues/7996")]
[ActiveIssue(7996)]
public void SubStream()
{
var stream = new MemoryStream();
stream.WriteByte(0xff);
stream.Write(Misc.Members, 0, Misc.Members.Length);
stream.WriteByte(0xff);
stream.WriteByte(0xff);
stream.Position = 1;
var peReader1 = new PEReader(stream, PEStreamOptions.LeaveOpen, Misc.Members.Length);
Assert.Equal(Misc.Members.Length, peReader1.GetEntireImage().Length);
peReader1.GetMetadataReader();
stream.Position = 1;
var peReader2 = new PEReader(stream, PEStreamOptions.LeaveOpen | PEStreamOptions.PrefetchMetadata, Misc.Members.Length);
Assert.Equal(Misc.Members.Length, peReader2.GetEntireImage().Length);
peReader2.GetMetadataReader();
stream.Position = 1;
var peReader3 = new PEReader(stream, PEStreamOptions.LeaveOpen | PEStreamOptions.PrefetchEntireImage, Misc.Members.Length);
Assert.Equal(Misc.Members.Length, peReader3.GetEntireImage().Length);
peReader3.GetMetadataReader();
}
// TODO: Switch to small checked in native image.
/*
[Fact]
public void OpenNativeImage()
{
using (var reader = new PEReader(File.OpenRead(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "kernel32.dll"))))
{
Assert.False(reader.HasMetadata);
Assert.True(reader.PEHeaders.IsDll);
Assert.False(reader.PEHeaders.IsExe);
Assert.Throws<InvalidOperationException>(() => reader.GetMetadataReader());
}
}
*/
[Fact]
public void IL_LazyLoad()
{
var peStream = new MemoryStream(Misc.Members);
using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen))
{
var md = reader.GetMetadataReader();
var il = reader.GetMethodBody(md.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1)).RelativeVirtualAddress);
Assert.Equal(new byte[] { 0, 42 }, il.GetILBytes());
Assert.Equal(8, il.MaxStack);
}
}
[Fact]
public void IL_EagerLoad()
{
var peStream = new MemoryStream(Misc.Members);
using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen | PEStreamOptions.PrefetchMetadata | PEStreamOptions.PrefetchEntireImage))
{
var md = reader.GetMetadataReader();
var il = reader.GetMethodBody(md.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1)).RelativeVirtualAddress);
Assert.Equal(new byte[] { 0, 42 }, il.GetILBytes());
Assert.Equal(8, il.MaxStack);
}
}
[Fact]
public void Metadata_LazyLoad()
{
var peStream = new MemoryStream(Misc.Members);
using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen))
{
var md = reader.GetMetadataReader();
var method = md.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1));
Assert.Equal("MC1", md.GetString(method.Name));
}
}
[Fact]
public void Metadata_EagerLoad()
{
var peStream = new MemoryStream(Misc.Members);
using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen | PEStreamOptions.PrefetchMetadata))
{
var md = reader.GetMetadataReader();
var method = md.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1));
Assert.Equal("MC1", md.GetString(method.Name));
Assert.Throws<InvalidOperationException>(() => reader.GetEntireImage());
Assert.Throws<InvalidOperationException>(() => reader.GetMethodBody(method.RelativeVirtualAddress));
}
}
[Fact]
public void EntireImage_LazyLoad()
{
var peStream = new MemoryStream(Misc.Members);
using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen))
{
Assert.Equal(4608, reader.GetEntireImage().Length);
}
}
[Fact]
public void EntireImage_EagerLoad()
{
var peStream = new MemoryStream(Misc.Members);
using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen | PEStreamOptions.PrefetchMetadata | PEStreamOptions.PrefetchEntireImage))
{
Assert.Equal(4608, reader.GetEntireImage().Length);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get module handles
public void GetMethodBody_Loaded()
{
LoaderUtilities.LoadPEAndValidate(Misc.Members, reader =>
{
var md = reader.GetMetadataReader();
var il = reader.GetMethodBody(md.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1)).RelativeVirtualAddress);
Assert.Equal(new byte[] { 0, 42 }, il.GetILBytes());
Assert.Equal(8, il.MaxStack);
});
}
[Fact]
public void GetSectionData()
{
var peStream = new MemoryStream(Misc.Members);
using (var reader = new PEReader(peStream))
{
ValidateSectionData(reader);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get module handles
public void GetSectionData_Loaded()
{
LoaderUtilities.LoadPEAndValidate(Misc.Members, ValidateSectionData);
}
private unsafe void ValidateSectionData(PEReader reader)
{
var relocBlob1 = reader.GetSectionData(".reloc").GetContent();
var relocBlob2 = reader.GetSectionData(0x6000).GetContent();
AssertEx.Equal(new byte[]
{
0x00, 0x20, 0x00, 0x00,
0x0C, 0x00, 0x00, 0x00,
0xD0, 0x38, 0x00, 0x00
}, relocBlob1);
AssertEx.Equal(relocBlob1, relocBlob2);
var data = reader.GetSectionData(0x5fff);
Assert.True(data.Pointer == null);
Assert.Equal(0, data.Length);
AssertEx.Equal(new byte[0], data.GetContent());
data = reader.GetSectionData(0x600B);
Assert.True(data.Pointer != null);
Assert.Equal(1, data.Length);
AssertEx.Equal(new byte[] { 0x00 }, data.GetContent());
data = reader.GetSectionData(0x600C);
Assert.True(data.Pointer == null);
Assert.Equal(0, data.Length);
AssertEx.Equal(new byte[0], data.GetContent());
data = reader.GetSectionData(0x600D);
Assert.True(data.Pointer == null);
Assert.Equal(0, data.Length);
AssertEx.Equal(new byte[0], data.GetContent());
data = reader.GetSectionData(int.MaxValue);
Assert.True(data.Pointer == null);
Assert.Equal(0, data.Length);
AssertEx.Equal(new byte[0], data.GetContent());
data = reader.GetSectionData(".nonexisting");
Assert.True(data.Pointer == null);
Assert.Equal(0, data.Length);
AssertEx.Equal(new byte[0], data.GetContent());
data = reader.GetSectionData("");
Assert.True(data.Pointer == null);
Assert.Equal(0, data.Length);
AssertEx.Equal(new byte[0], data.GetContent());
}
[Fact]
public void GetSectionData_Errors()
{
var peStream = new MemoryStream(Misc.Members);
using (var reader = new PEReader(peStream))
{
Assert.Throws<ArgumentNullException>(() => reader.GetSectionData(null));
Assert.Throws<ArgumentOutOfRangeException>(() => reader.GetSectionData(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => reader.GetSectionData(int.MinValue));
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_Args()
{
var peStream = new MemoryStream(PortablePdbs.DocumentsDll);
using (var reader = new PEReader(peStream))
{
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.False(reader.TryOpenAssociatedPortablePdb(@"b.dll", _ => null, out pdbProvider, out pdbPath));
Assert.Throws<ArgumentNullException>(() => reader.TryOpenAssociatedPortablePdb(@"b.dll", null, out pdbProvider, out pdbPath));
Assert.Throws<ArgumentNullException>(() => reader.TryOpenAssociatedPortablePdb(null, _ => null, out pdbProvider, out pdbPath));
Assert.Throws<ArgumentException>("peImagePath", () => reader.TryOpenAssociatedPortablePdb("C:\\a\\\0\\b", _ => null, out pdbProvider, out pdbPath));
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_CollocatedFile()
{
var peStream = new MemoryStream(PortablePdbs.DocumentsDll);
using (var reader = new PEReader(peStream))
{
string pathQueried = null;
Func<string, Stream> streamProvider = p =>
{
Assert.Null(pathQueried);
pathQueried = p;
return new MemoryStream(PortablePdbs.DocumentsPdb);
};
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath));
Assert.Equal(Path.Combine("pedir", "Documents.pdb"), pathQueried);
Assert.Equal(Path.Combine("pedir", "Documents.pdb"), pdbPath);
var pdbReader = pdbProvider.GetMetadataReader();
Assert.Equal(13, pdbReader.Documents.Count);
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_Embedded()
{
var peStream = new MemoryStream(PortablePdbs.DocumentsEmbeddedDll);
using (var reader = new PEReader(peStream))
{
string pathQueried = null;
Func<string, Stream> streamProvider = p =>
{
Assert.Null(pathQueried);
pathQueried = p;
return null;
};
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath));
Assert.Equal(Path.Combine("pedir", "Documents.Embedded.pdb"), pathQueried);
Assert.Null(pdbPath);
var pdbReader = pdbProvider.GetMetadataReader();
Assert.Equal(13, pdbReader.Documents.Count);
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_EmbeddedOnly()
{
var peStream = new MemoryStream(PortablePdbs.DocumentsEmbeddedDll);
using (var reader = new PEReader(peStream))
{
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.True(reader.TryOpenAssociatedPortablePdb(@"x", _ => null, out pdbProvider, out pdbPath));
Assert.Null(pdbPath);
var pdbReader = pdbProvider.GetMetadataReader();
Assert.Equal(13, pdbReader.Documents.Count);
}
}
[Fact]
public unsafe void TryOpenAssociatedPortablePdb_EmbeddedUnused()
{
var peStream = new MemoryStream(PortablePdbs.DocumentsEmbeddedDll);
using (var reader = new PEReader(peStream))
{
using (MetadataReaderProvider embeddedProvider = reader.ReadEmbeddedPortablePdbDebugDirectoryData(reader.ReadDebugDirectory()[2]))
{
var embeddedReader = embeddedProvider.GetMetadataReader();
var embeddedBytes = new BlobReader(embeddedReader.MetadataPointer, embeddedReader.MetadataLength).ReadBytes(embeddedReader.MetadataLength);
string pathQueried = null;
Func<string, Stream> streamProvider = p =>
{
Assert.Null(pathQueried);
pathQueried = p;
return new MemoryStream(embeddedBytes);
};
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath));
Assert.Equal(Path.Combine("pedir", "Documents.Embedded.pdb"), pathQueried);
Assert.Equal(Path.Combine("pedir", "Documents.Embedded.pdb"), pdbPath);
var pdbReader = pdbProvider.GetMetadataReader();
Assert.Equal(13, pdbReader.Documents.Count);
}
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_UnixStylePath()
{
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"/abc/def.xyz", id, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
string pathQueried = null;
Func<string, Stream> streamProvider = p =>
{
Assert.Null(pathQueried);
pathQueried = p;
return null;
};
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.False(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath));
Assert.Equal(Path.Combine("pedir", "def.xyz"), pathQueried);
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_WindowsSpecificPath()
{
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"C:def.xyz", id, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
string pathQueried = null;
Func<string, Stream> streamProvider = p =>
{
Assert.Null(pathQueried);
pathQueried = p;
return null;
};
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.False(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath));
Assert.Equal(Path.Combine("pedir", "def.xyz"), pathQueried);
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_WindowsInvalidCharacters()
{
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"/a/*/c*.pdb", id, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
string pathQueried = null;
Func<string, Stream> streamProvider = p =>
{
Assert.Null(pathQueried);
pathQueried = p;
return null;
};
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.False(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath));
Assert.Equal(PathUtilities.CombinePathWithRelativePath("pedir", "c*.pdb"), pathQueried);
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_DuplicateEntries_CodeView()
{
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0);
ddBuilder.AddReproducibleEntry();
ddBuilder.AddCodeViewEntry(@"/a/b/c.pdb", id, portablePdbVersion: 0x0100);
ddBuilder.AddCodeViewEntry(@"/a/b/d.pdb", id, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
string pathQueried = null;
Func<string, Stream> streamProvider = p =>
{
Assert.Null(pathQueried);
pathQueried = p;
return null;
};
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.False(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath));
Assert.Equal(PathUtilities.CombinePathWithRelativePath("pedir", "c.pdb"), pathQueried);
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_DuplicateEntries_Embedded()
{
var pdbBuilder1 = new BlobBuilder();
pdbBuilder1.WriteBytes(PortablePdbs.DocumentsPdb);
var pdbBuilder2 = new BlobBuilder();
pdbBuilder2.WriteByte(1);
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0x0100);
ddBuilder.AddReproducibleEntry();
ddBuilder.AddEmbeddedPortablePdbEntry(pdbBuilder1, portablePdbVersion: 0x0100);
ddBuilder.AddEmbeddedPortablePdbEntry(pdbBuilder2, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
string pathQueried = null;
Func<string, Stream> streamProvider = p =>
{
Assert.Null(pathQueried);
pathQueried = p;
return null;
};
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath));
Assert.Equal(PathUtilities.CombinePathWithRelativePath("pedir", "a.pdb"), pathQueried);
Assert.Null(pdbPath);
Assert.Equal(13, pdbProvider.GetMetadataReader().Documents.Count);
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_CodeViewVsEmbedded_NonMatchingPdbId()
{
var pdbBuilder = new BlobBuilder();
pdbBuilder.WriteBytes(PortablePdbs.DocumentsPdb);
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0x0100);
ddBuilder.AddEmbeddedPortablePdbEntry(pdbBuilder, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
string pathQueried = null;
Func<string, Stream> streamProvider = p =>
{
Assert.Null(pathQueried);
pathQueried = p;
// Doesn't match the id
return new MemoryStream(PortablePdbs.DocumentsPdb);
};
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath));
Assert.Null(pdbPath);
Assert.Equal(PathUtilities.CombinePathWithRelativePath("pedir", "a.pdb"), pathQueried);
Assert.Equal(13, pdbProvider.GetMetadataReader().Documents.Count);
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_BadPdbFile_FallbackToEmbedded()
{
var pdbBuilder = new BlobBuilder();
pdbBuilder.WriteBytes(PortablePdbs.DocumentsPdb);
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0x0100);
ddBuilder.AddEmbeddedPortablePdbEntry(pdbBuilder, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
string pathQueried = null;
Func<string, Stream> streamProvider = p =>
{
Assert.Null(pathQueried);
pathQueried = p;
// Bad PDB
return new MemoryStream(new byte[] { 0x01 });
};
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath));
Assert.Null(pdbPath);
Assert.Equal(PathUtilities.CombinePathWithRelativePath("pedir", "a.pdb"), pathQueried);
Assert.Equal(13, pdbProvider.GetMetadataReader().Documents.Count);
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_ExpectedExceptionFromStreamProvider_FallbackOnEmbedded_Valid()
{
var pdbBuilder = new BlobBuilder();
pdbBuilder.WriteBytes(PortablePdbs.DocumentsPdb);
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0x0100);
ddBuilder.AddEmbeddedPortablePdbEntry(pdbBuilder, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new IOException(); }, out pdbProvider, out pdbPath));
Assert.Null(pdbPath);
Assert.Equal(13, pdbProvider.GetMetadataReader().Documents.Count);
Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new BadImageFormatException(); }, out pdbProvider, out pdbPath));
Assert.Null(pdbPath);
Assert.Equal(13, pdbProvider.GetMetadataReader().Documents.Count);
Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new FileNotFoundException(); }, out pdbProvider, out pdbPath));
Assert.Null(pdbPath);
Assert.Equal(13, pdbProvider.GetMetadataReader().Documents.Count);
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_ExpectedExceptionFromStreamProvider_FallbackOnEmbedded_Invalid()
{
var pdbBuilder = new BlobBuilder();
pdbBuilder.WriteBytes(new byte[] { 0x01 });
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0x0100);
ddBuilder.AddEmbeddedPortablePdbEntry(pdbBuilder, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
MetadataReaderProvider pdbProvider;
string pdbPath;
// reports the first error:
Assert.Throws<IOException>(() =>
reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new IOException(); }, out pdbProvider, out pdbPath));
// reports the first error:
AssertEx.Throws<BadImageFormatException>(() =>
reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new BadImageFormatException("Bang!"); }, out pdbProvider, out pdbPath),
e => Assert.Equal("Bang!", e.Message));
// file doesn't exist, fall back to embedded without reporting FileNotFoundExeception
Assert.Throws<BadImageFormatException>(() =>
reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new FileNotFoundException(); }, out pdbProvider, out pdbPath));
Assert.Throws<BadImageFormatException>(() =>
reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => null, out pdbProvider, out pdbPath));
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_ExpectedExceptionFromStreamProvider_NoFallback()
{
var pdbBuilder = new BlobBuilder();
pdbBuilder.WriteBytes(PortablePdbs.DocumentsPdb);
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.Throws<IOException>(() =>
reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new IOException(); }, out pdbProvider, out pdbPath));
AssertEx.Throws<BadImageFormatException>(() =>
reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new BadImageFormatException("Bang!"); }, out pdbProvider, out pdbPath),
e => Assert.Equal("Bang!", e.Message));
// file doesn't exist and no embedded => return false
Assert.False(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new FileNotFoundException(); }, out pdbProvider, out pdbPath));
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_BadStreamProvider()
{
var pdbBuilder = new BlobBuilder();
pdbBuilder.WriteBytes(PortablePdbs.DocumentsPdb);
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
MetadataReaderProvider pdbProvider;
string pdbPath;
// pass-thru:
Assert.Throws<ArgumentException>(() =>
reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new ArgumentException(); }, out pdbProvider, out pdbPath));
Assert.Throws<InvalidOperationException>(() =>
reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { return new TestStream(canRead: false, canWrite: true, canSeek: true); }, out pdbProvider, out pdbPath));
Assert.Throws<InvalidOperationException>(() =>
reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { return new TestStream(canRead: true, canWrite: true, canSeek: false); }, out pdbProvider, out pdbPath));
}
}
[Fact]
public void Dispose()
{
var peStream = new MemoryStream(PortablePdbs.DocumentsEmbeddedDll);
var reader = new PEReader(peStream);
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.True(reader.TryOpenAssociatedPortablePdb(@"x", _ => null, out pdbProvider, out pdbPath));
Assert.NotNull(pdbProvider);
Assert.Null(pdbPath);
var ddEntries = reader.ReadDebugDirectory();
var ddCodeView = ddEntries[0];
var ddEmbedded = ddEntries[2];
var embeddedPdbProvider = reader.ReadEmbeddedPortablePdbDebugDirectoryData(ddEmbedded);
// dispose the PEReader:
reader.Dispose();
Assert.False(reader.IsEntireImageAvailable);
Assert.Throws<ObjectDisposedException>(() => reader.PEHeaders);
Assert.Throws<ObjectDisposedException>(() => reader.HasMetadata);
Assert.Throws<ObjectDisposedException>(() => reader.GetMetadata());
Assert.Throws<ObjectDisposedException>(() => reader.GetSectionData(1000));
Assert.Throws<ObjectDisposedException>(() => reader.GetMetadataReader());
Assert.Throws<ObjectDisposedException>(() => reader.GetMethodBody(0));
Assert.Throws<ObjectDisposedException>(() => reader.GetEntireImage());
Assert.Throws<ObjectDisposedException>(() => reader.ReadDebugDirectory());
Assert.Throws<ObjectDisposedException>(() => reader.ReadCodeViewDebugDirectoryData(ddCodeView));
Assert.Throws<ObjectDisposedException>(() => reader.ReadEmbeddedPortablePdbDebugDirectoryData(ddEmbedded));
MetadataReaderProvider __;
string ___;
Assert.Throws<ObjectDisposedException>(() => reader.TryOpenAssociatedPortablePdb(@"x", _ => null, out __, out ___));
// ok to use providers after PEReader disposed:
var pdbReader = pdbProvider.GetMetadataReader();
Assert.Equal(13, pdbReader.Documents.Count);
pdbReader = embeddedPdbProvider.GetMetadataReader();
Assert.Equal(13, pdbReader.Documents.Count);
embeddedPdbProvider.Dispose();
}
}
}
| |
using System;
using System.Globalization;
using Lucene.Net.Documents;
using NUnit.Framework;
using Assert = Lucene.Net.TestFramework.Assert;
using Console = Lucene.Net.Util.SystemConsole;
namespace Lucene.Net.Search
{
/*
* 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 DefaultSimilarity = Lucene.Net.Search.Similarities.DefaultSimilarity;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using Field = Field;
using IndexReader = Lucene.Net.Index.IndexReader;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using Similarity = Lucene.Net.Search.Similarities.Similarity;
using Term = Lucene.Net.Index.Term;
/// <summary>
/// Test that BooleanQuery.setMinimumNumberShouldMatch works.
/// </summary>
[TestFixture]
public class TestBooleanMinShouldMatch : LuceneTestCase
{
private static Directory index;
private static IndexReader r;
private static IndexSearcher s;
/// <summary>
/// LUCENENET specific
/// Is non-static because NewStringField is no longer static.
/// </summary>
[OneTimeSetUp]
public override void BeforeClass()
{
base.BeforeClass();
string[] data = new string[] { "A 1 2 3 4 5 6", "Z 4 5 6", null, "B 2 4 5 6", "Y 3 5 6", null, "C 3 6", "X 4 5 6" };
index = NewDirectory();
RandomIndexWriter w = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, index);
for (int i = 0; i < data.Length; i++)
{
Document doc = new Document();
doc.Add(NewStringField("id", Convert.ToString(i), Field.Store.YES)); //Field.Keyword("id",String.valueOf(i)));
doc.Add(NewStringField("all", "all", Field.Store.YES)); //Field.Keyword("all","all"));
if (null != data[i])
{
doc.Add(NewTextField("data", data[i], Field.Store.YES)); //Field.Text("data",data[i]));
}
w.AddDocument(doc);
}
r = w.GetReader();
s = NewSearcher(r);
w.Dispose();
//System.out.println("Set up " + getName());
}
[OneTimeTearDown]
public override void AfterClass()
{
s = null;
r.Dispose();
r = null;
index.Dispose();
index = null;
base.AfterClass();
}
public virtual void VerifyNrHits(Query q, int expected)
{
// bs1
ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs;
if (expected != h.Length)
{
PrintHits(TestName, h, s);
}
Assert.AreEqual(expected, h.Length, "result count");
//System.out.println("TEST: now check");
// bs2
TopScoreDocCollector collector = TopScoreDocCollector.Create(1000, true);
s.Search(q, collector);
ScoreDoc[] h2 = collector.GetTopDocs().ScoreDocs;
if (expected != h2.Length)
{
PrintHits(TestName, h2, s);
}
Assert.AreEqual(expected, h2.Length, "result count (bs2)");
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, q, s);
}
[Test]
public virtual void TestAllOptional()
{
BooleanQuery q = new BooleanQuery();
for (int i = 1; i <= 4; i++)
{
q.Add(new TermQuery(new Term("data", "" + i)), Occur.SHOULD); //false, false);
}
q.MinimumNumberShouldMatch = 2; // match at least two of 4
VerifyNrHits(q, 2);
}
[Test]
public virtual void TestOneReqAndSomeOptional()
{
/* one required, some optional */
BooleanQuery q = new BooleanQuery();
q.Add(new TermQuery(new Term("all", "all")), Occur.MUST); //true, false);
q.Add(new TermQuery(new Term("data", "5")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "4")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "3")), Occur.SHOULD); //false, false);
q.MinimumNumberShouldMatch = 2; // 2 of 3 optional
VerifyNrHits(q, 5);
}
[Test]
public virtual void TestSomeReqAndSomeOptional()
{
/* two required, some optional */
BooleanQuery q = new BooleanQuery();
q.Add(new TermQuery(new Term("all", "all")), Occur.MUST); //true, false);
q.Add(new TermQuery(new Term("data", "6")), Occur.MUST); //true, false);
q.Add(new TermQuery(new Term("data", "5")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "4")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "3")), Occur.SHOULD); //false, false);
q.MinimumNumberShouldMatch = 2; // 2 of 3 optional
VerifyNrHits(q, 5);
}
[Test]
public virtual void TestOneProhibAndSomeOptional()
{
/* one prohibited, some optional */
BooleanQuery q = new BooleanQuery();
q.Add(new TermQuery(new Term("data", "1")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "2")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "3")), Occur.MUST_NOT); //false, true );
q.Add(new TermQuery(new Term("data", "4")), Occur.SHOULD); //false, false);
q.MinimumNumberShouldMatch = 2; // 2 of 3 optional
VerifyNrHits(q, 1);
}
[Test]
public virtual void TestSomeProhibAndSomeOptional()
{
/* two prohibited, some optional */
BooleanQuery q = new BooleanQuery();
q.Add(new TermQuery(new Term("data", "1")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "2")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "3")), Occur.MUST_NOT); //false, true );
q.Add(new TermQuery(new Term("data", "4")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "C")), Occur.MUST_NOT); //false, true );
q.MinimumNumberShouldMatch = 2; // 2 of 3 optional
VerifyNrHits(q, 1);
}
[Test]
public virtual void TestOneReqOneProhibAndSomeOptional()
{
/* one required, one prohibited, some optional */
BooleanQuery q = new BooleanQuery();
q.Add(new TermQuery(new Term("data", "6")), Occur.MUST); // true, false);
q.Add(new TermQuery(new Term("data", "5")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "4")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "3")), Occur.MUST_NOT); //false, true );
q.Add(new TermQuery(new Term("data", "2")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "1")), Occur.SHOULD); //false, false);
q.MinimumNumberShouldMatch = 3; // 3 of 4 optional
VerifyNrHits(q, 1);
}
[Test]
public virtual void TestSomeReqOneProhibAndSomeOptional()
{
/* two required, one prohibited, some optional */
BooleanQuery q = new BooleanQuery();
q.Add(new TermQuery(new Term("all", "all")), Occur.MUST); //true, false);
q.Add(new TermQuery(new Term("data", "6")), Occur.MUST); //true, false);
q.Add(new TermQuery(new Term("data", "5")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "4")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "3")), Occur.MUST_NOT); //false, true );
q.Add(new TermQuery(new Term("data", "2")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "1")), Occur.SHOULD); //false, false);
q.MinimumNumberShouldMatch = 3; // 3 of 4 optional
VerifyNrHits(q, 1);
}
[Test]
public virtual void TestOneReqSomeProhibAndSomeOptional()
{
/* one required, two prohibited, some optional */
BooleanQuery q = new BooleanQuery();
q.Add(new TermQuery(new Term("data", "6")), Occur.MUST); //true, false);
q.Add(new TermQuery(new Term("data", "5")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "4")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "3")), Occur.MUST_NOT); //false, true );
q.Add(new TermQuery(new Term("data", "2")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "1")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "C")), Occur.MUST_NOT); //false, true );
q.MinimumNumberShouldMatch = 3; // 3 of 4 optional
VerifyNrHits(q, 1);
}
[Test]
public virtual void TestSomeReqSomeProhibAndSomeOptional()
{
/* two required, two prohibited, some optional */
BooleanQuery q = new BooleanQuery();
q.Add(new TermQuery(new Term("all", "all")), Occur.MUST); //true, false);
q.Add(new TermQuery(new Term("data", "6")), Occur.MUST); //true, false);
q.Add(new TermQuery(new Term("data", "5")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "4")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "3")), Occur.MUST_NOT); //false, true );
q.Add(new TermQuery(new Term("data", "2")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "1")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "C")), Occur.MUST_NOT); //false, true );
q.MinimumNumberShouldMatch = 3; // 3 of 4 optional
VerifyNrHits(q, 1);
}
[Test]
public virtual void TestMinHigherThenNumOptional()
{
/* two required, two prohibited, some optional */
BooleanQuery q = new BooleanQuery();
q.Add(new TermQuery(new Term("all", "all")), Occur.MUST); //true, false);
q.Add(new TermQuery(new Term("data", "6")), Occur.MUST); //true, false);
q.Add(new TermQuery(new Term("data", "5")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "4")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "3")), Occur.MUST_NOT); //false, true );
q.Add(new TermQuery(new Term("data", "2")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "1")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "C")), Occur.MUST_NOT); //false, true );
q.MinimumNumberShouldMatch = 90; // 90 of 4 optional ?!?!?!
VerifyNrHits(q, 0);
}
[Test]
public virtual void TestMinEqualToNumOptional()
{
/* two required, two optional */
BooleanQuery q = new BooleanQuery();
q.Add(new TermQuery(new Term("all", "all")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "6")), Occur.MUST); //true, false);
q.Add(new TermQuery(new Term("data", "3")), Occur.MUST); //true, false);
q.Add(new TermQuery(new Term("data", "2")), Occur.SHOULD); //false, false);
q.MinimumNumberShouldMatch = 2; // 2 of 2 optional
VerifyNrHits(q, 1);
}
[Test]
public virtual void TestOneOptionalEqualToMin()
{
/* two required, one optional */
BooleanQuery q = new BooleanQuery();
q.Add(new TermQuery(new Term("all", "all")), Occur.MUST); //true, false);
q.Add(new TermQuery(new Term("data", "3")), Occur.SHOULD); //false, false);
q.Add(new TermQuery(new Term("data", "2")), Occur.MUST); //true, false);
q.MinimumNumberShouldMatch = 1; // 1 of 1 optional
VerifyNrHits(q, 1);
}
[Test]
public virtual void TestNoOptionalButMin()
{
/* two required, no optional */
BooleanQuery q = new BooleanQuery();
q.Add(new TermQuery(new Term("all", "all")), Occur.MUST); //true, false);
q.Add(new TermQuery(new Term("data", "2")), Occur.MUST); //true, false);
q.MinimumNumberShouldMatch = 1; // 1 of 0 optional
VerifyNrHits(q, 0);
}
[Test]
public virtual void TestNoOptionalButMin2()
{
/* one required, no optional */
BooleanQuery q = new BooleanQuery();
q.Add(new TermQuery(new Term("all", "all")), Occur.MUST); //true, false);
q.MinimumNumberShouldMatch = 1; // 1 of 0 optional
VerifyNrHits(q, 0);
}
[Test]
public virtual void TestRandomQueries()
{
const string field = "data";
string[] vals = new string[] { "1", "2", "3", "4", "5", "6", "A", "Z", "B", "Y", "Z", "X", "foo" };
int maxLev = 4;
// callback object to set a random setMinimumNumberShouldMatch
TestBoolean2.ICallback minNrCB = new CallbackAnonymousInnerClassHelper(this, field, vals);
// increase number of iterations for more complete testing
int num = AtLeast(20);
for (int i = 0; i < num; i++)
{
int lev = Random.Next(maxLev);
int seed = Random.Next();
BooleanQuery q1 = TestBoolean2.RandBoolQuery(new Random(seed), true, lev, field, vals, null);
// BooleanQuery q2 = TestBoolean2.randBoolQuery(new Random(seed), lev, field, vals, minNrCB);
BooleanQuery q2 = TestBoolean2.RandBoolQuery(new Random(seed), true, lev, field, vals, null);
// only set minimumNumberShouldMatch on the top level query since setting
// at a lower level can change the score.
minNrCB.PostCreate(q2);
// Can't use Hits because normalized scores will mess things
// up. The non-sorting version of search() that returns TopDocs
// will not normalize scores.
TopDocs top1 = s.Search(q1, null, 100);
TopDocs top2 = s.Search(q2, null, 100);
if (i < 100)
{
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, q1, s);
QueryUtils.Check(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, q2, s);
}
AssertSubsetOfSameScores(q2, top1, top2);
}
// System.out.println("Total hits:"+tot);
}
private class CallbackAnonymousInnerClassHelper : TestBoolean2.ICallback
{
private readonly TestBooleanMinShouldMatch outerInstance;
private readonly string field;
private readonly string[] vals;
public CallbackAnonymousInnerClassHelper(TestBooleanMinShouldMatch outerInstance, string field, string[] vals)
{
this.outerInstance = outerInstance;
this.field = field;
this.vals = vals;
}
public virtual void PostCreate(BooleanQuery q)
{
BooleanClause[] c = q.GetClauses();
int opt = 0;
for (int i = 0; i < c.Length; i++)
{
if (c[i].Occur == Occur.SHOULD)
{
opt++;
}
}
q.MinimumNumberShouldMatch = Random.Next(opt + 2);
if (Random.NextBoolean())
{
// also add a random negation
Term randomTerm = new Term(field, vals[Random.Next(vals.Length)]);
q.Add(new TermQuery(randomTerm), Occur.MUST_NOT);
}
}
}
private void AssertSubsetOfSameScores(Query q, TopDocs top1, TopDocs top2)
{
// The constrained query
// should be a subset to the unconstrained query.
if (top2.TotalHits > top1.TotalHits)
{
Assert.Fail("Constrained results not a subset:\n" + CheckHits.TopDocsString(top1, 0, 0) + CheckHits.TopDocsString(top2, 0, 0) + "for query:" + q.ToString());
}
for (int hit = 0; hit < top2.TotalHits; hit++)
{
int id = top2.ScoreDocs[hit].Doc;
float score = top2.ScoreDocs[hit].Score;
bool found = false;
// find this doc in other hits
for (int other = 0; other < top1.TotalHits; other++)
{
if (top1.ScoreDocs[other].Doc == id)
{
found = true;
float otherScore = top1.ScoreDocs[other].Score;
// check if scores match
Assert.AreEqual(score, otherScore, CheckHits.ExplainToleranceDelta(score, otherScore), "Doc " + id + " scores don't match\n" + CheckHits.TopDocsString(top1, 0, 0) + CheckHits.TopDocsString(top2, 0, 0) + "for query:" + q.ToString());
}
}
// check if subset
if (!found)
{
Assert.Fail("Doc " + id + " not found\n" + CheckHits.TopDocsString(top1, 0, 0) + CheckHits.TopDocsString(top2, 0, 0) + "for query:" + q.ToString());
}
}
}
[Test]
public virtual void TestRewriteCoord1()
{
Similarity oldSimilarity = s.Similarity;
try
{
s.Similarity = new DefaultSimilarityAnonymousInnerClassHelper(this);
BooleanQuery q1 = new BooleanQuery();
q1.Add(new TermQuery(new Term("data", "1")), Occur.SHOULD);
BooleanQuery q2 = new BooleanQuery();
q2.Add(new TermQuery(new Term("data", "1")), Occur.SHOULD);
q2.MinimumNumberShouldMatch = 1;
TopDocs top1 = s.Search(q1, null, 100);
TopDocs top2 = s.Search(q2, null, 100);
AssertSubsetOfSameScores(q2, top1, top2);
}
finally
{
s.Similarity = oldSimilarity;
}
}
private class DefaultSimilarityAnonymousInnerClassHelper : DefaultSimilarity
{
private readonly TestBooleanMinShouldMatch outerInstance;
public DefaultSimilarityAnonymousInnerClassHelper(TestBooleanMinShouldMatch outerInstance)
{
this.outerInstance = outerInstance;
}
public override float Coord(int overlap, int maxOverlap)
{
return overlap / ((float)maxOverlap + 1);
}
}
[Test]
public virtual void TestRewriteNegate()
{
Similarity oldSimilarity = s.Similarity;
try
{
s.Similarity = new DefaultSimilarityAnonymousInnerClassHelper2(this);
BooleanQuery q1 = new BooleanQuery();
q1.Add(new TermQuery(new Term("data", "1")), Occur.SHOULD);
BooleanQuery q2 = new BooleanQuery();
q2.Add(new TermQuery(new Term("data", "1")), Occur.SHOULD);
q2.Add(new TermQuery(new Term("data", "Z")), Occur.MUST_NOT);
TopDocs top1 = s.Search(q1, null, 100);
TopDocs top2 = s.Search(q2, null, 100);
AssertSubsetOfSameScores(q2, top1, top2);
}
finally
{
s.Similarity = oldSimilarity;
}
}
private class DefaultSimilarityAnonymousInnerClassHelper2 : DefaultSimilarity
{
private readonly TestBooleanMinShouldMatch outerInstance;
public DefaultSimilarityAnonymousInnerClassHelper2(TestBooleanMinShouldMatch outerInstance)
{
this.outerInstance = outerInstance;
}
public override float Coord(int overlap, int maxOverlap)
{
return overlap / ((float)maxOverlap + 1);
}
}
protected internal virtual void PrintHits(string test, ScoreDoc[] h, IndexSearcher searcher)
{
Console.Error.WriteLine("------- " + test + " -------");
NumberFormatInfo f = new NumberFormatInfo();
f.NumberDecimalSeparator = ".";
//DecimalFormat f = new DecimalFormat("0.000000", DecimalFormatSymbols.getInstance(Locale.ROOT));
for (int i = 0; i < h.Length; i++)
{
Document d = searcher.Doc(h[i].Doc);
decimal score = (decimal)h[i].Score;
Console.Error.WriteLine("#" + i + ": " + score.ToString(f) + " - " + d.Get("id") + " - " + d.Get("data"));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
partial class TcpClient
{
// The Unix implementation is separate from the Windows implementation due to a fundamental
// difference in socket support on the two platforms: on Unix once a socket has been used
// in a failed connect, its state is undefined and it can no longer be used (Windows supports
// this). This then means that the instance Socket.Connect methods that take either multiple
// addresses or a string host name that could be mapped to multiple addresses via DNS don't
// work, because we can't try to individually connect to a second address after failing the
// first. That then impacts TcpClient, which exposes not only such Connect methods that
// just delegate to the underlying Socket, but also the Socket itself.
//
// To address the most common cases, where the Socket isn't actually accessed directly by
// a consumer of TcpClient, whereas on Windows TcpClient creates the socket during construction,
// on Unix we create the socket on-demand, either when it's explicitly asked for via the Client
// property or when the TcpClient.Connect methods are called. In the former case, we have no
// choice but to create a Socket, after which point we'll throw PlatformNotSupportedException
// on any subsequent attempts to use Connect with multiple addresses. In the latter case, though,
// we can create a new Socket for each address we try, and only store as the "real" Client socket
// the one that successfully connected.
//
// However, TcpClient also exposes some properties for common configuration of the Socket, and
// if we simply forwarded those through Client, we'd frequently end up forcing the Socket's
// creation before Connect is used, thwarting this whole scheme. To address that, we maintain
// shadow values for the relevant state. When the properties are read, we read them initially
// from a temporary socket created just for the purpose of getting the system's default. When
// the properties are written, we store their values into these shadow properties instead of into
// an actual socket (though we do also create a temporary socket and store the property onto it,
// enabling errors to be caught earlier). This is a relatively expensive, but it enables
// TcpClient to be used in its recommended fashion and with its most popular APIs.
// Shadow values for storing data set through TcpClient's properties.
// We use a separate bool field to store whether the value has been set.
// We don't use nullables, due to one of the properties being a reference type.
private ShadowOptions _shadowOptions; // shadow state used in public properties before the socket is created
private int _connectRunning; // tracks whether a connect operation that could set _clientSocket is currently running
private void InitializeClientSocket()
{
// Nop. We want to lazily-allocate the socket.
}
private Socket ClientCore
{
get
{
EnterClientLock();
try
{
// The Client socket is being explicitly accessed, so we're forced
// to create it if it doesn't exist.
if (_clientSocket == null)
{
// Create the socket, and transfer to it any of our shadow properties.
_clientSocket = CreateSocket();
ApplyInitializedOptionsToSocket(_clientSocket);
}
return _clientSocket;
}
finally
{
ExitClientLock();
}
}
set
{
EnterClientLock();
try
{
_clientSocket = value;
ClearInitializedValues();
}
finally
{
ExitClientLock();
}
}
}
private void ApplyInitializedOptionsToSocket(Socket socket)
{
ShadowOptions so = _shadowOptions;
if (so == null)
{
return;
}
// For each shadow property where we have an initialized value,
// transfer that value to the provided socket.
if (so._exclusiveAddressUseInitialized)
{
socket.ExclusiveAddressUse = so._exclusiveAddressUse != 0;
}
if (so._receiveBufferSizeInitialized)
{
socket.ReceiveBufferSize = so._receiveBufferSize;
}
if (so._sendBufferSizeInitialized)
{
socket.SendBufferSize = so._sendBufferSize;
}
if (so._receiveTimeoutInitialized)
{
socket.ReceiveTimeout = so._receiveTimeout;
}
if (so._sendTimeoutInitialized)
{
socket.SendTimeout = so._sendTimeout;
}
if (so._lingerStateInitialized)
{
socket.LingerState = so._lingerState;
}
if (so._noDelayInitialized)
{
socket.NoDelay = so._noDelay != 0;
}
}
private void ClearInitializedValues()
{
ShadowOptions so = _shadowOptions;
if (so != null)
{
// Clear the initialized fields for all of our shadow properties.
so._exclusiveAddressUseInitialized =
so._receiveBufferSizeInitialized =
so._sendBufferSizeInitialized =
so._receiveTimeoutInitialized =
so._sendTimeoutInitialized =
so._lingerStateInitialized =
so._noDelayInitialized =
false;
}
}
private int AvailableCore
{
get
{
// If we have a client socket, return its available value.
// Otherwise, there isn't data available, so return 0.
return _clientSocket != null ? _clientSocket.Available : 0;
}
}
private bool ConnectedCore
{
get
{
// If we have a client socket, return whether it's connected.
// Otherwise as we don't have a socket, by definition it's not.
return _clientSocket != null && _clientSocket.Connected;
}
}
private Task ConnectAsyncCore(string host, int port)
{
// Validate the args, similar to how Socket.Connect(string, int) would.
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
}
// If the client socket has already materialized, this API can't be used.
if (_clientSocket != null)
{
throw new PlatformNotSupportedException(SR.net_sockets_connect_multiaddress_notsupported);
}
// Do the real work.
EnterClientLock();
return ConnectAsyncCorePrivate(host, port);
}
private async Task ConnectAsyncCorePrivate(string host, int port)
{
try
{
// Since Socket.Connect(host, port) won't work, get the addresses manually,
// and then delegate to Connect(IPAddress[], int).
IPAddress[] addresses = await Dns.GetHostAddressesAsync(host).ConfigureAwait(false);
await ConnectAsyncCorePrivate(addresses, port).ConfigureAwait(false);
}
finally
{
ExitClientLock();
}
}
private Task ConnectAsyncCore(IPAddress[] addresses, int port)
{
// Validate the args, similar to how Socket.Connect(IPAddress[], int) would.
if (addresses == null)
{
throw new ArgumentNullException(nameof(addresses));
}
if (addresses.Length == 0)
{
throw new ArgumentException(SR.net_invalidAddressList, nameof(addresses));
}
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
}
// If the client socket has already materialized, this API can't be used.
// Similarly if another operation to set the socket is already in progress.
if (_clientSocket != null)
{
throw new PlatformNotSupportedException(SR.net_sockets_connect_multiaddress_notsupported);
}
// Do the real work.
EnterClientLock();
return ConnectAsyncCorePrivate(addresses, port);
}
private async Task ConnectAsyncCorePrivate(IPAddress[] addresses, int port)
{
try
{
// For each address, create a new socket (configured appropriately) and try to connect
// to the endpoint. If we're successful, set the newly connected socket as the client
// socket, and we're done. If we're unsuccessful, try the next address.
ExceptionDispatchInfo lastException = null;
foreach (IPAddress address in addresses)
{
Socket s = CreateSocket();
try
{
ApplyInitializedOptionsToSocket(s);
await s.ConnectAsync(address, port).ConfigureAwait(false);
_clientSocket = s;
_active = true;
return;
}
catch (Exception exc)
{
s.Dispose();
lastException = ExceptionDispatchInfo.Capture(exc);
}
}
// None of the addresses worked. Throw whatever exception we last captured, or a
// new one if something went terribly wrong.
if (lastException != null)
{
lastException.Throw();
}
throw new ArgumentException(SR.net_invalidAddressList, nameof(addresses));
}
finally
{
ExitClientLock();
}
}
private int ReceiveBufferSizeCore
{
get
{
ShadowOptions so = EnsureShadowValuesInitialized();
return GetOption(ref so._receiveBufferSize, ref so._receiveBufferSizeInitialized, SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer);
}
set
{
ShadowOptions so = EnsureShadowValuesInitialized();
SetOption(ref so._receiveBufferSize, ref so._receiveBufferSizeInitialized, SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value);
}
}
private int SendBufferSizeCore
{
get
{
ShadowOptions so = EnsureShadowValuesInitialized();
return GetOption(ref so._sendBufferSize, ref so._sendBufferSizeInitialized, SocketOptionLevel.Socket, SocketOptionName.SendBuffer);
}
set
{
ShadowOptions so = EnsureShadowValuesInitialized();
SetOption(ref so._sendBufferSize, ref so._sendBufferSizeInitialized, SocketOptionLevel.Socket, SocketOptionName.SendBuffer, value);
}
}
private int ReceiveTimeoutCore
{
get
{
ShadowOptions so = EnsureShadowValuesInitialized();
return GetOption(ref so._receiveTimeout, ref so._receiveTimeoutInitialized, SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
}
set
{
ShadowOptions so = EnsureShadowValuesInitialized();
SetOption(ref so._receiveTimeout, ref so._receiveTimeoutInitialized, SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, value);
}
}
private int SendTimeoutCore
{
get
{
ShadowOptions so = EnsureShadowValuesInitialized();
return GetOption(ref so._sendTimeout, ref so._sendTimeoutInitialized, SocketOptionLevel.Socket, SocketOptionName.SendTimeout);
}
set
{
ShadowOptions so = EnsureShadowValuesInitialized();
SetOption(ref so._sendTimeout, ref so._sendTimeoutInitialized, SocketOptionLevel.Socket, SocketOptionName.SendTimeout, value);
}
}
private LingerOption LingerStateCore
{
get
{
ShadowOptions so = EnsureShadowValuesInitialized();
return GetOption(ref so._lingerState, ref so._lingerStateInitialized, SocketOptionLevel.Socket, SocketOptionName.Linger);
}
set
{
ShadowOptions so = EnsureShadowValuesInitialized();
SetOption(ref so._lingerState, ref so._lingerStateInitialized, SocketOptionLevel.Socket, SocketOptionName.Linger, value);
}
}
private bool NoDelayCore
{
get
{
ShadowOptions so = EnsureShadowValuesInitialized();
return GetOption(ref so._noDelay, ref so._noDelayInitialized, SocketOptionLevel.Tcp, SocketOptionName.NoDelay) != 0;
}
set
{
ShadowOptions so = EnsureShadowValuesInitialized();
SetOption(ref so._noDelay, ref so._noDelayInitialized, SocketOptionLevel.Tcp, SocketOptionName.NoDelay, value ? 1 : 0);
}
}
private bool ExclusiveAddressUseCore
{
get
{
ShadowOptions so = EnsureShadowValuesInitialized();
return GetOption(ref so._exclusiveAddressUse, ref so._exclusiveAddressUseInitialized, SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse) != 0;
}
set
{
// Unlike the rest of the properties, we code this one explicitly, so as to take advantage of validation done by Socket's property.
ShadowOptions so = EnsureShadowValuesInitialized();
so._exclusiveAddressUse = value ? 1 : 0;
so._exclusiveAddressUseInitialized = true;
if (_clientSocket != null)
{
_clientSocket.ExclusiveAddressUse = value; // Use setter explicitly as it does additional validation beyond that done by SetOption
}
}
}
private ShadowOptions EnsureShadowValuesInitialized()
{
return _shadowOptions ?? (_shadowOptions = new ShadowOptions());
}
private T GetOption<T>(ref T location, ref bool initialized, SocketOptionLevel level, SocketOptionName name)
{
// Used in the getter for each shadow property.
// If we already have our client socket set up, just get its value for the option.
// Otherwise, return our shadow property. If that shadow hasn't yet been initialized,
// first initialize it by creating a temporary socket from which we can obtain a default value.
if (_clientSocket != null)
{
return (T)_clientSocket.GetSocketOption(level, name);
}
if (!initialized)
{
using (Socket s = CreateSocket())
{
location = (T)s.GetSocketOption(level, name);
}
initialized = true;
}
return location;
}
private void SetOption<T>(ref T location, ref bool initialized, SocketOptionLevel level, SocketOptionName name, T value)
{
// Used in the setter for each shadow property.
// Store the option on to the client socket. If the client socket isn't yet set, we still want to set
// the property onto a socket so we can get validation performed by the underlying system on the option being
// set... so, albeit being a bit expensive, we create a temporary socket we can use for validation purposes.
Socket s = _clientSocket ?? CreateSocket();
try
{
if (typeof(T) == typeof(int))
{
s.SetSocketOption(level, name, (int)(object)value);
}
else
{
Debug.Assert(typeof(T) == typeof(LingerOption), $"Unexpected type: {typeof(T)}");
s.SetSocketOption(level, name, value);
}
}
finally
{
if (s != _clientSocket)
{
s.Dispose();
}
}
// Then if it was successful, store it into the shadow.
location = value;
initialized = true;
}
private void EnterClientLock()
{
// TcpClient is not safe to be used concurrently. But in case someone does access various members
// while an async Connect operation is running that could asynchronously transition _clientSocket
// from null to non-null, we have a simple lock... if it's taken when you try to take it, it throws
// a PlatformNotSupportedException indicating the limitations of Connect.
if (Interlocked.CompareExchange(ref _connectRunning, 1, 0) != 0)
{
throw new PlatformNotSupportedException(SR.net_sockets_connect_multiaddress_notsupported);
}
}
private void ExitClientLock()
{
Volatile.Write(ref _connectRunning, 0);
}
private sealed class ShadowOptions
{
internal int _exclusiveAddressUse;
internal bool _exclusiveAddressUseInitialized;
internal int _receiveBufferSize;
internal bool _receiveBufferSizeInitialized;
internal int _sendBufferSize;
internal bool _sendBufferSizeInitialized;
internal int _receiveTimeout;
internal bool _receiveTimeoutInitialized;
internal int _sendTimeout;
internal bool _sendTimeoutInitialized;
internal LingerOption _lingerState;
internal bool _lingerStateInitialized;
internal int _noDelay;
internal bool _noDelayInitialized;
}
}
}
| |
// 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 provides an implementation of the pieces of the Marshal class which are required by the Interop
// API contract but are not provided by the version of Marshal which is part of the Redhawk test library.
// This partial class is combined with the version from the Redhawk test library, in order to provide the
// Marshal implementation for System.Private.CoreLib.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices.ComTypes;
using Internal.Runtime.CompilerHelpers;
namespace System.Runtime.InteropServices
{
public static partial class Marshal
{
#if PLATFORM_WINDOWS
private const long HIWORDMASK = unchecked((long)0xffffffffffff0000L);
// Win32 has the concept of Atoms, where a pointer can either be a pointer
// or an int. If it's less than 64K, this is guaranteed to NOT be a
// pointer since the bottom 64K bytes are reserved in a process' page table.
// We should be careful about deallocating this stuff. Extracted to
// a function to avoid C# problems with lack of support for IntPtr.
// We have 2 of these methods for slightly different semantics for NULL.
private static bool IsWin32Atom(IntPtr ptr)
{
long lPtr = (long)ptr;
return 0 == (lPtr & HIWORDMASK);
}
private static bool IsNotWin32Atom(IntPtr ptr)
{
long lPtr = (long)ptr;
return 0 != (lPtr & HIWORDMASK);
}
#else // PLATFORM_WINDOWS
private static bool IsWin32Atom(IntPtr ptr) => false;
private static bool IsNotWin32Atom(IntPtr ptr) => true;
#endif // PLATFORM_WINDOWS
//====================================================================
// The default character size for the system. This is always 2 because
// the framework only runs on UTF-16 systems.
//====================================================================
public static readonly int SystemDefaultCharSize = 2;
//====================================================================
// The max DBCS character size for the system.
//====================================================================
public static readonly int SystemMaxDBCSCharSize = PInvokeMarshal.GetSystemMaxDBCSCharSize();
public static unsafe String PtrToStringAnsi(IntPtr ptr)
{
if (IntPtr.Zero == ptr)
{
return null;
}
else if (IsWin32Atom(ptr))
{
return null;
}
else
{
int nb = lstrlenA(ptr);
if (nb == 0)
{
return string.Empty;
}
else
{
return new string((sbyte*)ptr);
}
}
}
public static unsafe String PtrToStringAnsi(IntPtr ptr, int len)
{
if (ptr == IntPtr.Zero)
throw new ArgumentNullException(nameof(ptr));
if (len < 0)
throw new ArgumentException(nameof(len));
return ConvertToUnicode(ptr, len);
}
public static unsafe String PtrToStringUni(IntPtr ptr, int len)
{
if (ptr == IntPtr.Zero)
throw new ArgumentNullException(nameof(ptr));
if (len < 0)
throw new ArgumentException(nameof(len));
return new String((char*)ptr, 0, len);
}
public static unsafe String PtrToStringUni(IntPtr ptr)
{
if (IntPtr.Zero == ptr)
{
return null;
}
else if (IsWin32Atom(ptr))
{
return null;
}
else
{
return new String((char*)ptr);
}
}
public static String PtrToStringAuto(IntPtr ptr, int len)
{
// Ansi platforms are no longer supported
return PtrToStringUni(ptr, len);
}
public static String PtrToStringAuto(IntPtr ptr)
{
// Ansi platforms are no longer supported
return PtrToStringUni(ptr);
}
//====================================================================
// SizeOf()
//====================================================================
/// <summary>
/// Returns the size of an instance of a value type.
/// </summary>
public static int SizeOf<T>()
{
return SizeOf(typeof(T));
}
public static int SizeOf<T>(T structure)
{
return SizeOf<T>();
}
public static int SizeOf(Object structure)
{
if (structure == null)
throw new ArgumentNullException(nameof(structure));
// we never had a check for generics here
Contract.EndContractBlock();
return SizeOfHelper(structure.GetType(), true);
}
[Pure]
public static int SizeOf(Type t)
{
if (t == null)
throw new ArgumentNullException(nameof(t));
if (t.TypeHandle.IsGenericType() || t.TypeHandle.IsGenericTypeDefinition())
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t));
Contract.EndContractBlock();
return SizeOfHelper(t, true);
}
private static int SizeOfHelper(Type t, bool throwIfNotMarshalable)
{
RuntimeTypeHandle typeHandle = t.TypeHandle;
int size;
if (RuntimeInteropData.Instance.TryGetStructUnsafeStructSize(typeHandle, out size))
{
return size;
}
if (!typeHandle.IsBlittable() && !typeHandle.IsValueType())
{
throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, t);
}
else
{
return typeHandle.GetValueTypeSize();
}
}
//====================================================================
// OffsetOf()
//====================================================================
public static IntPtr OffsetOf(Type t, String fieldName)
{
if (t == null)
throw new ArgumentNullException(nameof(t));
if (String.IsNullOrEmpty(fieldName))
throw new ArgumentNullException(nameof(fieldName));
if (t.TypeHandle.IsGenericType() || t.TypeHandle.IsGenericTypeDefinition())
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t));
Contract.EndContractBlock();
return OffsetOfHelper(t, fieldName);
}
private static IntPtr OffsetOfHelper(Type t, String fieldName)
{
bool structExists;
uint offset;
if (RuntimeInteropData.Instance.TryGetStructFieldOffset(t.TypeHandle, fieldName, out structExists, out offset))
{
return new IntPtr(offset);
}
// if we can find the struct but couldn't find its field, throw Argument Exception
if (structExists)
{
throw new ArgumentException(SR.Format(SR.Argument_OffsetOfFieldNotFound, t.TypeHandle.GetDisplayName()), nameof(fieldName));
}
else
{
throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, t);
}
}
public static IntPtr OffsetOf<T>(String fieldName)
{
return OffsetOf(typeof(T), fieldName);
}
//====================================================================
// Copy blocks from CLR arrays to native memory.
//====================================================================
public static void Copy(int[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
public static void Copy(char[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
public static void Copy(short[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
public static void Copy(long[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
public static void Copy(float[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
public static void Copy(double[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
public static void Copy(byte[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
public static void Copy(IntPtr[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
private static void CopyToNative(Array source, int startIndex, IntPtr destination, int length)
{
InteropExtensions.CopyToNative(source, startIndex, destination, length);
}
//====================================================================
// Copy blocks from native memory to CLR arrays
//====================================================================
public static void Copy(IntPtr source, int[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, char[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, short[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, long[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, float[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, double[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, byte[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, IntPtr[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
private static void CopyToManaged(IntPtr source, Array destination, int startIndex, int length)
{
InteropExtensions.CopyToManaged(source, destination, startIndex, length);
}
//====================================================================
// Read from memory
//====================================================================
public static unsafe byte ReadByte(IntPtr ptr, int ofs)
{
byte* addr = (byte*)ptr + ofs;
return *addr;
}
public static byte ReadByte(IntPtr ptr)
{
return ReadByte(ptr, 0);
}
public static unsafe short ReadInt16(IntPtr ptr, int ofs)
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x1) == 0)
{
// aligned read
return *((short*)addr);
}
else
{
// unaligned read
short val;
byte* valPtr = (byte*)&val;
valPtr[0] = addr[0];
valPtr[1] = addr[1];
return val;
}
}
public static short ReadInt16(IntPtr ptr)
{
return ReadInt16(ptr, 0);
}
public static unsafe int ReadInt32(IntPtr ptr, int ofs)
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x3) == 0)
{
// aligned read
return *((int*)addr);
}
else
{
// unaligned read
int val;
byte* valPtr = (byte*)&val;
valPtr[0] = addr[0];
valPtr[1] = addr[1];
valPtr[2] = addr[2];
valPtr[3] = addr[3];
return val;
}
}
public static int ReadInt32(IntPtr ptr)
{
return ReadInt32(ptr, 0);
}
public static IntPtr ReadIntPtr([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs)
{
#if WIN32
return (IntPtr)ReadInt32(ptr, ofs);
#else
return (IntPtr)ReadInt64(ptr, ofs);
#endif
}
public static IntPtr ReadIntPtr(IntPtr ptr, int ofs)
{
#if WIN32
return (IntPtr)ReadInt32(ptr, ofs);
#else
return (IntPtr)ReadInt64(ptr, ofs);
#endif
}
public static IntPtr ReadIntPtr(IntPtr ptr)
{
#if WIN32
return (IntPtr)ReadInt32(ptr, 0);
#else
return (IntPtr)ReadInt64(ptr, 0);
#endif
}
public static unsafe long ReadInt64(IntPtr ptr, int ofs)
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x7) == 0)
{
// aligned read
return *((long*)addr);
}
else
{
// unaligned read
long val;
byte* valPtr = (byte*)&val;
valPtr[0] = addr[0];
valPtr[1] = addr[1];
valPtr[2] = addr[2];
valPtr[3] = addr[3];
valPtr[4] = addr[4];
valPtr[5] = addr[5];
valPtr[6] = addr[6];
valPtr[7] = addr[7];
return val;
}
}
public static long ReadInt64(IntPtr ptr)
{
return ReadInt64(ptr, 0);
}
//====================================================================
// Write to memory
//====================================================================
public static unsafe void WriteByte(IntPtr ptr, int ofs, byte val)
{
byte* addr = (byte*)ptr + ofs;
*addr = val;
}
public static void WriteByte(IntPtr ptr, byte val)
{
WriteByte(ptr, 0, val);
}
public static unsafe void WriteInt16(IntPtr ptr, int ofs, short val)
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x1) == 0)
{
// aligned write
*((short*)addr) = val;
}
else
{
// unaligned write
byte* valPtr = (byte*)&val;
addr[0] = valPtr[0];
addr[1] = valPtr[1];
}
}
public static void WriteInt16(IntPtr ptr, short val)
{
WriteInt16(ptr, 0, val);
}
public static void WriteInt16(IntPtr ptr, int ofs, char val)
{
WriteInt16(ptr, ofs, (short)val);
}
public static void WriteInt16([In, Out]Object ptr, int ofs, char val)
{
WriteInt16(ptr, ofs, (short)val);
}
public static void WriteInt16(IntPtr ptr, char val)
{
WriteInt16(ptr, 0, (short)val);
}
public static unsafe void WriteInt32(IntPtr ptr, int ofs, int val)
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x3) == 0)
{
// aligned write
*((int*)addr) = val;
}
else
{
// unaligned write
byte* valPtr = (byte*)&val;
addr[0] = valPtr[0];
addr[1] = valPtr[1];
addr[2] = valPtr[2];
addr[3] = valPtr[3];
}
}
public static void WriteInt32(IntPtr ptr, int val)
{
WriteInt32(ptr, 0, val);
}
public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val)
{
#if WIN32
WriteInt32(ptr, ofs, (int)val);
#else
WriteInt64(ptr, ofs, (long)val);
#endif
}
public static void WriteIntPtr([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, IntPtr val)
{
#if WIN32
WriteInt32(ptr, ofs, (int)val);
#else
WriteInt64(ptr, ofs, (long)val);
#endif
}
public static void WriteIntPtr(IntPtr ptr, IntPtr val)
{
#if WIN32
WriteInt32(ptr, 0, (int)val);
#else
WriteInt64(ptr, 0, (long)val);
#endif
}
public static unsafe void WriteInt64(IntPtr ptr, int ofs, long val)
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x7) == 0)
{
// aligned write
*((long*)addr) = val;
}
else
{
// unaligned write
byte* valPtr = (byte*)&val;
addr[0] = valPtr[0];
addr[1] = valPtr[1];
addr[2] = valPtr[2];
addr[3] = valPtr[3];
addr[4] = valPtr[4];
addr[5] = valPtr[5];
addr[6] = valPtr[6];
addr[7] = valPtr[7];
}
}
public static void WriteInt64(IntPtr ptr, long val)
{
WriteInt64(ptr, 0, val);
}
//====================================================================
// GetHRForLastWin32Error
//====================================================================
public static int GetHRForLastWin32Error()
{
int dwLastError = GetLastWin32Error();
if ((dwLastError & 0x80000000) == 0x80000000)
{
return dwLastError;
}
else
{
return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000);
}
}
public static Exception GetExceptionForHR(int errorCode, IntPtr errorInfo)
{
#if ENABLE_WINRT
if (errorInfo != new IntPtr(-1))
{
throw new PlatformNotSupportedException();
}
return ExceptionHelpers.GetMappingExceptionForHR(
errorCode,
message: null,
createCOMException: false,
hasErrorInfo: false);
#else
throw new PlatformNotSupportedException("GetExceptionForHR");
#endif // ENABLE_WINRT
}
//====================================================================
// Throws a CLR exception based on the HRESULT.
//====================================================================
public static void ThrowExceptionForHR(int errorCode)
{
ThrowExceptionForHRInternal(errorCode, new IntPtr(-1));
}
public static void ThrowExceptionForHR(int errorCode, IntPtr errorInfo)
{
ThrowExceptionForHRInternal(errorCode, errorInfo);
}
private static void ThrowExceptionForHRInternal(int errorCode, IntPtr errorInfo)
{
if (errorCode < 0)
{
throw GetExceptionForHR(errorCode, errorInfo);
}
}
//====================================================================
// Memory allocation and deallocation.
//====================================================================
public static unsafe IntPtr ReAllocHGlobal(IntPtr pv, IntPtr cb)
{
return PInvokeMarshal.MemReAlloc(pv, cb);
}
private static unsafe void ConvertToAnsi(string source, IntPtr pbNativeBuffer, int cbNativeBuffer)
{
Debug.Assert(source != null);
Debug.Assert(pbNativeBuffer != IntPtr.Zero);
Debug.Assert(cbNativeBuffer >= (source.Length + 1) * SystemMaxDBCSCharSize, "Insufficient buffer length passed to ConvertToAnsi");
fixed (char* pch = source)
{
int convertedBytes =
PInvokeMarshal.ConvertWideCharToMultiByte(pch, source.Length, (byte*)pbNativeBuffer, cbNativeBuffer, false, false);
((byte*)pbNativeBuffer)[convertedBytes] = 0;
}
}
private static unsafe string ConvertToUnicode(IntPtr sourceBuffer, int cbSourceBuffer)
{
if (IsWin32Atom(sourceBuffer))
{
throw new ArgumentException(SR.Arg_MustBeStringPtrNotAtom);
}
if (sourceBuffer == IntPtr.Zero || cbSourceBuffer == 0)
{
return String.Empty;
}
// MB_PRECOMPOSED is the default.
int charsRequired = PInvokeMarshal.GetCharCount((byte*)sourceBuffer, cbSourceBuffer);
if (charsRequired == 0)
{
throw new ArgumentException(SR.Arg_InvalidANSIString);
}
char[] wideChars = new char[charsRequired + 1];
fixed (char* pWideChars = &wideChars[0])
{
int converted = PInvokeMarshal.ConvertMultiByteToWideChar((byte*)sourceBuffer,
cbSourceBuffer,
pWideChars,
wideChars.Length);
if (converted == 0)
{
throw new ArgumentException(SR.Arg_InvalidANSIString);
}
wideChars[converted] = '\0';
return new String(pWideChars);
}
}
private static unsafe int lstrlenA(IntPtr sz)
{
Debug.Assert(sz != IntPtr.Zero);
byte* pb = (byte*)sz;
byte* start = pb;
while (*pb != 0)
{
++pb;
}
return (int)(pb - start);
}
private static unsafe int lstrlenW(IntPtr wsz)
{
Debug.Assert(wsz != IntPtr.Zero);
char* pc = (char*)wsz;
char* start = pc;
while (*pc != 0)
{
++pc;
}
return (int)(pc - start);
}
// Zero out the buffer pointed to by ptr, making sure that the compiler cannot
// replace the zeroing with a nop
private static unsafe void SecureZeroMemory(IntPtr ptr, int bytes)
{
Debug.Assert(ptr != IntPtr.Zero);
Debug.Assert(bytes >= 0);
byte* pBuffer = (byte*)ptr;
for (int i = 0; i < bytes; ++i)
{
Volatile.Write(ref pBuffer[i], 0);
}
}
//====================================================================
// String convertions.
//====================================================================
public static unsafe IntPtr StringToHGlobalAnsi(String s)
{
if (s == null)
{
return IntPtr.Zero;
}
else
{
int nb = (s.Length + 1) * SystemMaxDBCSCharSize;
// Overflow checking
if (nb < s.Length)
throw new ArgumentOutOfRangeException(nameof(s));
IntPtr hglobal = PInvokeMarshal.MemAlloc(new IntPtr(nb));
ConvertToAnsi(s, hglobal, nb);
return hglobal;
}
}
public static unsafe IntPtr StringToHGlobalUni(String s)
{
if (s == null)
{
return IntPtr.Zero;
}
else
{
int nb = (s.Length + 1) * 2;
// Overflow checking
if (nb < s.Length)
throw new ArgumentOutOfRangeException(nameof(s));
IntPtr hglobal = PInvokeMarshal.MemAlloc(new IntPtr(nb));
fixed (char* firstChar = s)
{
InteropExtensions.Memcpy(hglobal, new IntPtr(firstChar), nb);
}
return hglobal;
}
}
public static IntPtr StringToHGlobalAuto(String s)
{
// Ansi platforms are no longer supported
return StringToHGlobalUni(s);
}
//====================================================================
// return the IUnknown* for an Object if the current context
// is the one where the RCW was first seen. Will return null
// otherwise.
//====================================================================
public static IntPtr /* IUnknown* */ GetIUnknownForObject(Object o)
{
if (o == null)
{
throw new ArgumentNullException(nameof(o));
}
return MarshalAdapter.GetIUnknownForObject(o);
}
//====================================================================
// return an Object for IUnknown
//====================================================================
public static Object GetObjectForIUnknown(IntPtr /* IUnknown* */ pUnk)
{
if (pUnk == default(IntPtr))
{
throw new ArgumentNullException(nameof(pUnk));
}
return MarshalAdapter.GetObjectForIUnknown(pUnk);
}
//====================================================================
// check if the object is classic COM component
//====================================================================
public static bool IsComObject(Object o)
{
if (o == null)
throw new ArgumentNullException(nameof(o), SR.Arg_InvalidHandle);
return McgComHelpers.IsComObject(o);
}
public static unsafe IntPtr StringToCoTaskMemUni(String s)
{
if (s == null)
{
return IntPtr.Zero;
}
else
{
int nb = (s.Length + 1) * 2;
// Overflow checking
if (nb < s.Length)
throw new ArgumentOutOfRangeException(nameof(s));
IntPtr hglobal = PInvokeMarshal.CoTaskMemAlloc(new UIntPtr((uint)nb));
if (hglobal == IntPtr.Zero)
{
throw new OutOfMemoryException();
}
else
{
fixed (char* firstChar = s)
{
InteropExtensions.Memcpy(hglobal, new IntPtr(firstChar), nb);
}
return hglobal;
}
}
}
public static unsafe IntPtr StringToCoTaskMemAnsi(String s)
{
if (s == null)
{
return IntPtr.Zero;
}
else
{
int nb = (s.Length + 1) * SystemMaxDBCSCharSize;
// Overflow checking
if (nb < s.Length)
throw new ArgumentOutOfRangeException(nameof(s));
IntPtr hglobal = PInvokeMarshal.CoTaskMemAlloc(new UIntPtr((uint)nb));
if (hglobal == IntPtr.Zero)
{
throw new OutOfMemoryException();
}
else
{
ConvertToAnsi(s, hglobal, nb);
return hglobal;
}
}
}
public static IntPtr StringToCoTaskMemAuto(String s)
{
// Ansi platforms are no longer supported
return StringToCoTaskMemUni(s);
}
//====================================================================
// release the COM component and if the reference hits 0 zombie this object
// further usage of this Object might throw an exception
//====================================================================
public static int ReleaseComObject(Object o)
{
if (o == null)
throw new ArgumentNullException(nameof(o));
__ComObject co = null;
// Make sure the obj is an __ComObject.
try
{
co = (__ComObject)o;
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o));
}
return McgMarshal.Release(co);
}
//====================================================================
// release the COM component and zombie this object
// further usage of this Object might throw an exception
//====================================================================
public static Int32 FinalReleaseComObject(Object o)
{
if (o == null)
throw new ArgumentNullException(nameof(o));
Contract.EndContractBlock();
__ComObject co = null;
// Make sure the obj is an __ComObject.
try
{
co = (__ComObject)o;
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o));
}
co.FinalReleaseSelf();
return 0;
}
//====================================================================
// IUnknown Helpers
//====================================================================
public static int /* HRESULT */ QueryInterface(IntPtr /* IUnknown */ pUnk, ref Guid iid, out IntPtr ppv)
{
if (pUnk == IntPtr.Zero)
throw new ArgumentNullException(nameof(pUnk));
return McgMarshal.ComQueryInterfaceWithHR(pUnk, ref iid, out ppv);
}
public static int /* ULONG */ AddRef(IntPtr /* IUnknown */ pUnk)
{
if (pUnk == IntPtr.Zero)
throw new ArgumentNullException(nameof(pUnk));
return McgMarshal.ComAddRef(pUnk);
}
public static int /* ULONG */ Release(IntPtr /* IUnknown */ pUnk)
{
if (pUnk == IntPtr.Zero)
throw new ArgumentNullException(nameof(pUnk));
// This is documented to have "undefined behavior" when the ref count is already zero, so
// let's not AV if we can help it
return McgMarshal.ComSafeRelease(pUnk);
}
public static IntPtr ReAllocCoTaskMem(IntPtr pv, int cb)
{
IntPtr pNewMem = PInvokeMarshal.CoTaskMemReAlloc(pv, new IntPtr(cb));
if (pNewMem == IntPtr.Zero && cb != 0)
{
throw new OutOfMemoryException();
}
return pNewMem;
}
//====================================================================
// BSTR allocation and dealocation.
//====================================================================
public static void FreeBSTR(IntPtr ptr)
{
if (IsNotWin32Atom(ptr))
{
ExternalInterop.SysFreeString(ptr);
}
}
public static unsafe IntPtr StringToBSTR(String s)
{
if (s == null)
return IntPtr.Zero;
// Overflow checking
if (s.Length + 1 < s.Length)
throw new ArgumentOutOfRangeException(nameof(s));
fixed (char* pch = s)
{
IntPtr bstr = new IntPtr(ExternalInterop.SysAllocStringLen(pch, (uint)s.Length));
if (bstr == IntPtr.Zero)
throw new OutOfMemoryException();
return bstr;
}
}
public static String PtrToStringBSTR(IntPtr ptr)
{
return PtrToStringUni(ptr, (int)ExternalInterop.SysStringLen(ptr));
}
public static void ZeroFreeBSTR(IntPtr s)
{
SecureZeroMemory(s, (int)ExternalInterop.SysStringLen(s) * 2);
FreeBSTR(s);
}
public static void ZeroFreeCoTaskMemAnsi(IntPtr s)
{
SecureZeroMemory(s, lstrlenA(s));
FreeCoTaskMem(s);
}
public static void ZeroFreeCoTaskMemUnicode(IntPtr s)
{
SecureZeroMemory(s, lstrlenW(s));
FreeCoTaskMem(s);
}
public static void ZeroFreeGlobalAllocAnsi(IntPtr s)
{
SecureZeroMemory(s, lstrlenA(s));
FreeHGlobal(s);
}
public static void ZeroFreeGlobalAllocUnicode(IntPtr s)
{
SecureZeroMemory(s, lstrlenW(s));
FreeHGlobal(s);
}
/// <summary>
/// Returns the unmanaged function pointer for this delegate
/// </summary>
public static IntPtr GetFunctionPointerForDelegate(Delegate d)
{
if (d == null)
throw new ArgumentNullException(nameof(d));
return PInvokeMarshal.GetStubForPInvokeDelegate(d);
}
public static IntPtr GetFunctionPointerForDelegate<TDelegate>(TDelegate d)
{
return GetFunctionPointerForDelegate((Delegate)(object)d);
}
//====================================================================
// Marshals data from a native memory block to a preallocated structure class.
//====================================================================
private static unsafe void PtrToStructureHelper(IntPtr ptr, Object structure)
{
RuntimeTypeHandle structureTypeHandle = structure.GetType().TypeHandle;
// Boxed struct start at offset 1 (EEType* at offset 0) while class start at offset 0
int offset = structureTypeHandle.IsValueType() ? 1 : 0;
if (structureTypeHandle.IsBlittable() && structureTypeHandle.IsValueType())
{
int structSize = Marshal.SizeOf(structure);
InteropExtensions.PinObjectAndCall(structure,
unboxedStructPtr =>
{
InteropExtensions.Memcpy(
(IntPtr)((IntPtr*)unboxedStructPtr + offset), // safe (need to adjust offset as it could be class)
ptr, // unsafe (no need to adjust as it is always struct)
structSize
);
});
return;
}
IntPtr unmarshalStub;
if (RuntimeInteropData.Instance.TryGetStructUnmarshalStub(structureTypeHandle, out unmarshalStub))
{
InteropExtensions.PinObjectAndCall(structure,
unboxedStructPtr =>
{
CalliIntrinsics.Call<int>(
unmarshalStub,
(void*)ptr, // unsafe (no need to adjust as it is always struct)
((void*)((IntPtr*)unboxedStructPtr + offset)) // safe (need to adjust offset as it could be class)
);
});
return;
}
throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, structure.GetType());
}
//====================================================================
// Creates a new instance of "structuretype" and marshals data from a
// native memory block to it.
//====================================================================
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Object PtrToStructure(IntPtr ptr, Type structureType)
{
// Boxing the struct here is important to ensure that the original copy is written to,
// not the autoboxed copy
if (ptr == IntPtr.Zero)
throw new ArgumentNullException(nameof(ptr));
if (structureType == null)
throw new ArgumentNullException(nameof(structureType));
Object boxedStruct = InteropExtensions.RuntimeNewObject(structureType.TypeHandle);
PtrToStructureHelper(ptr, boxedStruct);
return boxedStruct;
}
public static T PtrToStructure<T>(IntPtr ptr)
{
return (T)PtrToStructure(ptr, typeof(T));
}
public static void PtrToStructure(IntPtr ptr, Object structure)
{
if (ptr == IntPtr.Zero)
throw new ArgumentNullException(nameof(ptr));
if (structure == null)
throw new ArgumentNullException(nameof(structure));
RuntimeTypeHandle structureTypeHandle = structure.GetType().TypeHandle;
if (structureTypeHandle.IsValueType())
{
throw new ArgumentException(nameof(structure), SR.Argument_StructMustNotBeValueClass);
}
PtrToStructureHelper(ptr, structure);
}
public static void PtrToStructure<T>(IntPtr ptr, T structure)
{
PtrToStructure(ptr, (object)structure);
}
//====================================================================
// Marshals data from a structure class to a native memory block.
// If the structure contains pointers to allocated blocks and
// "fDeleteOld" is true, this routine will call DestroyStructure() first.
//====================================================================
public static unsafe void StructureToPtr(Object structure, IntPtr ptr, bool fDeleteOld)
{
if (structure == null)
throw new ArgumentNullException(nameof(structure));
if (ptr == IntPtr.Zero)
throw new ArgumentNullException(nameof(ptr));
if (fDeleteOld)
{
DestroyStructure(ptr, structure.GetType());
}
RuntimeTypeHandle structureTypeHandle = structure.GetType().TypeHandle;
if (structureTypeHandle.IsGenericType() || structureTypeHandle.IsGenericTypeDefinition())
{
throw new ArgumentException(nameof(structure), SR.Argument_NeedNonGenericObject);
}
// Boxed struct start at offset 1 (EEType* at offset 0) while class start at offset 0
int offset = structureTypeHandle.IsValueType() ? 1 : 0;
bool isBlittable = false; // whether Mcg treat this struct as blittable struct
IntPtr marshalStub;
if (RuntimeInteropData.Instance.TryGetStructMarshalStub(structureTypeHandle, out marshalStub))
{
if (marshalStub != IntPtr.Zero)
{
InteropExtensions.PinObjectAndCall(structure,
unboxedStructPtr =>
{
CalliIntrinsics.Call<int>(
marshalStub,
((void*)((IntPtr*)unboxedStructPtr + offset)), // safe (need to adjust offset as it could be class)
(void*)ptr // unsafe (no need to adjust as it is always struct)
);
});
return;
}
else
{
isBlittable = true;
}
}
if (isBlittable || structureTypeHandle.IsBlittable()) // blittable
{
int structSize = Marshal.SizeOf(structure);
InteropExtensions.PinObjectAndCall(structure,
unboxedStructPtr =>
{
InteropExtensions.Memcpy(
ptr, // unsafe (no need to adjust as it is always struct)
(IntPtr)((IntPtr*)unboxedStructPtr + offset), // safe (need to adjust offset as it could be class)
structSize
);
});
return;
}
throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, structure.GetType());
}
public static void StructureToPtr<T>(T structure, IntPtr ptr, bool fDeleteOld)
{
StructureToPtr((object)structure, ptr, fDeleteOld);
}
//====================================================================
// DestroyStructure()
//
//====================================================================
public static void DestroyStructure(IntPtr ptr, Type structuretype)
{
if (ptr == IntPtr.Zero)
throw new ArgumentNullException(nameof(ptr));
if (structuretype == null)
throw new ArgumentNullException(nameof(structuretype));
RuntimeTypeHandle structureTypeHandle = structuretype.TypeHandle;
if (structureTypeHandle.IsGenericType() || structureTypeHandle.IsGenericTypeDefinition())
throw new ArgumentException(SR.Argument_NeedNonGenericType, "t");
if (structureTypeHandle.IsEnum() ||
structureTypeHandle.IsInterface() ||
InteropExtensions.AreTypesAssignable(typeof(Delegate).TypeHandle, structureTypeHandle))
{
throw new ArgumentException(SR.Argument_MustHaveLayoutOrBeBlittable, structureTypeHandle.GetDisplayName());
}
Contract.EndContractBlock();
DestroyStructureHelper(ptr, structuretype);
}
private static unsafe void DestroyStructureHelper(IntPtr ptr, Type structuretype)
{
RuntimeTypeHandle structureTypeHandle = structuretype.TypeHandle;
// Boxed struct start at offset 1 (EEType* at offset 0) while class start at offset 0
int offset = structureTypeHandle.IsValueType() ? 1 : 0;
if (structureTypeHandle.IsBlittable())
{
// ok to call with blittable structure, but no work to do in this case.
return;
}
IntPtr destroyStructureStub;
bool hasInvalidLayout;
if (RuntimeInteropData.Instance.TryGetDestroyStructureStub(structureTypeHandle, out destroyStructureStub, out hasInvalidLayout))
{
if (hasInvalidLayout)
throw new ArgumentException(SR.Argument_MustHaveLayoutOrBeBlittable, structureTypeHandle.GetDisplayName());
// DestroyStructureStub == IntPtr.Zero means its fields don't need to be destroied
if (destroyStructureStub != IntPtr.Zero)
{
CalliIntrinsics.Call<int>(
destroyStructureStub,
(void*)ptr // unsafe (no need to adjust as it is always struct)
);
}
return;
}
// Didn't find struct marshal data
throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, structuretype);
}
public static void DestroyStructure<T>(IntPtr ptr)
{
DestroyStructure(ptr, typeof(T));
}
public static IntPtr GetComInterfaceForObject<T, TInterface>(T o)
{
return GetComInterfaceForObject(o, typeof(TInterface));
}
public static IntPtr /* IUnknown* */ GetComInterfaceForObject(Object o, Type T)
{
return MarshalAdapter.GetComInterfaceForObject(o, T);
}
public static TDelegate GetDelegateForFunctionPointer<TDelegate>(IntPtr ptr)
{
return (TDelegate)(object)GetDelegateForFunctionPointer(ptr, typeof(TDelegate));
}
public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t)
{
// Validate the parameters
if (ptr == IntPtr.Zero)
throw new ArgumentNullException(nameof(ptr));
if (t == null)
throw new ArgumentNullException(nameof(t));
Contract.EndContractBlock();
if (t.TypeHandle.IsGenericType() || t.TypeHandle.IsGenericTypeDefinition())
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t));
bool isDelegateType = InteropExtensions.AreTypesAssignable(t.TypeHandle, typeof(MulticastDelegate).TypeHandle) ||
InteropExtensions.AreTypesAssignable(t.TypeHandle, typeof(Delegate).TypeHandle);
if (!isDelegateType)
throw new ArgumentException(SR.Arg_MustBeDelegateType, nameof(t));
return MarshalAdapter.GetDelegateForFunctionPointer(ptr, t);
}
//====================================================================
// GetNativeVariantForObject()
//
//====================================================================
public static void GetNativeVariantForObject<T>(T obj, IntPtr pDstNativeVariant)
{
GetNativeVariantForObject((object)obj, pDstNativeVariant);
}
public static unsafe void GetNativeVariantForObject(Object obj, /* VARIANT * */ IntPtr pDstNativeVariant)
{
// Obsolete
if (pDstNativeVariant == IntPtr.Zero)
throw new ArgumentNullException(nameof(pDstNativeVariant));
if (obj != null && (obj.GetType().TypeHandle.IsGenericType() || obj.GetType().TypeHandle.IsGenericTypeDefinition()))
throw new ArgumentException(SR.Argument_NeedNonGenericObject, nameof(obj));
Contract.EndContractBlock();
Variant* pVariant = (Variant*)pDstNativeVariant;
*pVariant = new Variant(obj);
}
//====================================================================
// GetObjectForNativeVariant()
//
//====================================================================
public static unsafe T GetObjectForNativeVariant<T>(IntPtr pSrcNativeVariant)
{
return (T)GetObjectForNativeVariant(pSrcNativeVariant);
}
public static unsafe Object GetObjectForNativeVariant(/* VARIANT * */ IntPtr pSrcNativeVariant)
{
// Obsolete
if (pSrcNativeVariant == IntPtr.Zero)
throw new ArgumentNullException(nameof(pSrcNativeVariant));
Contract.EndContractBlock();
Variant* pNativeVar = (Variant*)pSrcNativeVariant;
return pNativeVar->ToObject();
}
//====================================================================
// GetObjectsForNativeVariants()
//
//====================================================================
public static unsafe Object[] GetObjectsForNativeVariants(IntPtr aSrcNativeVariant, int cVars)
{
// Obsolete
if (aSrcNativeVariant == IntPtr.Zero)
throw new ArgumentNullException(nameof(aSrcNativeVariant));
if (cVars < 0)
throw new ArgumentOutOfRangeException(nameof(cVars), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
Object[] obj = new Object[cVars];
IntPtr aNativeVar = aSrcNativeVariant;
for (int i = 0; i < cVars; i++)
{
obj[i] = GetObjectForNativeVariant(aNativeVar);
aNativeVar = aNativeVar + sizeof(Variant);
}
return obj;
}
public static T[] GetObjectsForNativeVariants<T>(IntPtr aSrcNativeVariant, int cVars)
{
object[] objects = GetObjectsForNativeVariants(aSrcNativeVariant, cVars);
T[] result = null;
if (objects != null)
{
result = new T[objects.Length];
Array.Copy(objects, result, objects.Length);
}
return result;
}
//====================================================================
// UnsafeAddrOfPinnedArrayElement()
//
// IMPORTANT NOTICE: This method does not do any verification on the
// array. It must be used with EXTREME CAUTION since passing in
// an array that is not pinned or in the fixed heap can cause
// unexpected results !
//====================================================================
public static IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index)
{
if (arr == null)
throw new ArgumentNullException(nameof(arr));
if (index < 0 || index >= arr.Length)
throw new ArgumentOutOfRangeException(nameof(index));
Contract.EndContractBlock();
int offset = checked(index * arr.GetElementSize());
return arr.GetAddrOfPinnedArrayFromEETypeField() + offset;
}
public static IntPtr UnsafeAddrOfPinnedArrayElement<T>(T[] arr, int index)
{
return UnsafeAddrOfPinnedArrayElement((Array)arr, index);
}
//====================================================================
// This method binds to the specified moniker.
//====================================================================
public static Object BindToMoniker(String monikerName)
{
#if TARGET_CORE_API_SET // BindMoniker not available in core API set
throw new PlatformNotSupportedException();
#else
Object obj = null;
IBindCtx bindctx = null;
ExternalInterop.CreateBindCtx(0, out bindctx);
UInt32 cbEaten;
IMoniker pmoniker = null;
ExternalInterop.MkParseDisplayName(bindctx, monikerName, out cbEaten, out pmoniker);
ExternalInterop.BindMoniker(pmoniker, 0, ref Interop.COM.IID_IUnknown, out obj);
return obj;
#endif
}
#if ENABLE_WINRT
public static Type GetTypeFromCLSID(Guid clsid)
{
return Type.GetTypeFromCLSID(clsid);
}
//====================================================================
// Return a unique Object given an IUnknown. This ensures that you
// receive a fresh object (we will not look in the cache to match up this
// IUnknown to an already existing object). This is useful in cases
// where you want to be able to call ReleaseComObject on a RCW
// and not worry about other active uses of said RCW.
//====================================================================
public static Object GetUniqueObjectForIUnknown(IntPtr unknown)
{
throw new PlatformNotSupportedException();
}
public static bool AreComObjectsAvailableForCleanup()
{
throw new PlatformNotSupportedException();
}
public static IntPtr CreateAggregatedObject(IntPtr pOuter, Object o)
{
throw new PlatformNotSupportedException();
}
public static IntPtr CreateAggregatedObject<T>(IntPtr pOuter, T o)
{
return CreateAggregatedObject(pOuter, (object)o);
}
public static Object CreateWrapperOfType(Object o, Type t)
{
throw new PlatformNotSupportedException();
}
public static TWrapper CreateWrapperOfType<T, TWrapper>(T o)
{
return (TWrapper)CreateWrapperOfType(o, typeof(TWrapper));
}
public static IntPtr /* IUnknown* */ GetComInterfaceForObject(Object o, Type T, CustomQueryInterfaceMode mode)
{
// Obsolete
throw new PlatformNotSupportedException();
}
public static int GetExceptionCode()
{
// Obsolete
throw new PlatformNotSupportedException();
}
/// <summary>
/// <para>Returns the first valid COM slot that GetMethodInfoForSlot will work on
/// This will be 3 for IUnknown based interfaces and 7 for IDispatch based interfaces. </para>
/// </summary>
public static int GetStartComSlot(Type t)
{
throw new PlatformNotSupportedException();
}
//====================================================================
// Given a managed object that wraps an ITypeInfo, return its name
//====================================================================
public static String GetTypeInfoName(ITypeInfo typeInfo)
{
throw new PlatformNotSupportedException();
}
#endif //ENABLE_WINRT
public static byte ReadByte(Object ptr, int ofs)
{
// Obsolete
throw new PlatformNotSupportedException("ReadByte");
}
public static short ReadInt16(Object ptr, int ofs)
{
// Obsolete
throw new PlatformNotSupportedException("ReadInt16");
}
public static int ReadInt32(Object ptr, int ofs)
{
// Obsolete
throw new PlatformNotSupportedException("ReadInt32");
}
public static long ReadInt64(Object ptr, int ofs)
{
// Obsolete
throw new PlatformNotSupportedException("ReadInt64");
}
public static void WriteByte(Object ptr, int ofs, byte val)
{
// Obsolete
throw new PlatformNotSupportedException("WriteByte");
}
public static void WriteInt16(Object ptr, int ofs, short val)
{
// Obsolete
throw new PlatformNotSupportedException("WriteInt16");
}
public static void WriteInt32(Object ptr, int ofs, int val)
{
// Obsolete
throw new PlatformNotSupportedException("WriteInt32");
}
public static void WriteInt64(Object ptr, int ofs, long val)
{
// Obsolete
throw new PlatformNotSupportedException("WriteInt64");
}
public static void ChangeWrapperHandleStrength(Object otp, bool fIsWeak)
{
throw new PlatformNotSupportedException("ChangeWrapperHandleStrength");
}
public static void CleanupUnusedObjectsInCurrentContext()
{
// RCW cleanup implemented in native code in CoreCLR, and uses a global list to indicate which objects need to be collected. In
// CoreRT, RCWs are implemented in managed code and their cleanup is normally accomplished using finalizers. Implementing
// this method in a more complicated way (without calling WaitForPendingFinalizers) is non-trivial because it possible for timing
// problems to occur when competing with finalizers.
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
public static void Prelink(MethodInfo m)
{
if (m == null)
throw new ArgumentNullException(nameof(m));
Contract.EndContractBlock();
// Note: This method is effectively a no-op in ahead-of-time compilation scenarios. In CoreCLR and Desktop, this will pre-generate
// the P/Invoke, but everything is pre-generated in CoreRT.
}
public static void PrelinkAll(Type c)
{
if (c == null)
throw new ArgumentNullException(nameof(c));
Contract.EndContractBlock();
MethodInfo[] mi = c.GetMethods();
if (mi != null)
{
for (int i = 0; i < mi.Length; i++)
{
Prelink(mi[i]);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Serialization
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Text.RegularExpressions;
using System.Xml.Extensions;
internal class XmlSerializationILGen
{
private int _nextMethodNumber = 0;
private readonly Dictionary<TypeMapping, string> _methodNames = new Dictionary<TypeMapping, string>();
// Lookup name->created Method
private readonly Dictionary<string, MethodBuilderInfo> _methodBuilders = new Dictionary<string, MethodBuilderInfo>();
// Lookup name->created Type
internal Dictionary<string, Type> CreatedTypes = new Dictionary<string, Type>();
// Lookup name->class Member
internal Dictionary<string, MemberInfo> memberInfos = new Dictionary<string, MemberInfo>();
private readonly ReflectionAwareILGen _raCodeGen;
private readonly TypeScope[] _scopes;
private readonly TypeDesc _stringTypeDesc = null;
private readonly TypeDesc _qnameTypeDesc = null;
private readonly string _className;
private TypeMapping[] _referencedMethods;
private int _references = 0;
private readonly HashSet<TypeMapping> _generatedMethods = new HashSet<TypeMapping>();
private ModuleBuilder _moduleBuilder;
private readonly TypeAttributes _typeAttributes;
protected TypeBuilder typeBuilder;
protected CodeGenerator ilg;
internal XmlSerializationILGen(TypeScope[] scopes, string access, string className)
{
_scopes = scopes;
if (scopes.Length > 0)
{
_stringTypeDesc = scopes[0].GetTypeDesc(typeof(string));
_qnameTypeDesc = scopes[0].GetTypeDesc(typeof(XmlQualifiedName));
}
_raCodeGen = new ReflectionAwareILGen();
_className = className;
System.Diagnostics.Debug.Assert(access == "public");
_typeAttributes = TypeAttributes.Public;
}
internal int NextMethodNumber { get { return _nextMethodNumber; } set { _nextMethodNumber = value; } }
internal ReflectionAwareILGen RaCodeGen { get { return _raCodeGen; } }
internal TypeDesc StringTypeDesc { get { return _stringTypeDesc; } }
internal TypeDesc QnameTypeDesc { get { return _qnameTypeDesc; } }
internal string ClassName { get { return _className; } }
internal TypeScope[] Scopes { get { return _scopes; } }
internal Dictionary<TypeMapping, string> MethodNames { get { return _methodNames; } }
internal HashSet<TypeMapping> GeneratedMethods { get { return _generatedMethods; } }
internal ModuleBuilder ModuleBuilder
{
get { System.Diagnostics.Debug.Assert(_moduleBuilder != null); return _moduleBuilder; }
set { System.Diagnostics.Debug.Assert(_moduleBuilder == null && value != null); _moduleBuilder = value; }
}
internal TypeAttributes TypeAttributes { get { return _typeAttributes; } }
private static readonly Dictionary<string, Regex> s_regexs = new Dictionary<string, Regex>();
internal static Regex NewRegex(string pattern)
{
Regex regex;
lock (s_regexs)
{
if (!s_regexs.TryGetValue(pattern, out regex))
{
regex = new Regex(pattern);
s_regexs.Add(pattern, regex);
}
}
return regex;
}
internal MethodBuilder EnsureMethodBuilder(TypeBuilder typeBuilder, string methodName,
MethodAttributes attributes, Type returnType, Type[] parameterTypes)
{
MethodBuilderInfo methodBuilderInfo;
if (!_methodBuilders.TryGetValue(methodName, out methodBuilderInfo))
{
MethodBuilder methodBuilder = typeBuilder.DefineMethod(
methodName,
attributes,
returnType,
parameterTypes);
methodBuilderInfo = new MethodBuilderInfo(methodBuilder, parameterTypes);
_methodBuilders.Add(methodName, methodBuilderInfo);
}
#if DEBUG
else
{
methodBuilderInfo.Validate(returnType, parameterTypes, attributes);
}
#endif
return methodBuilderInfo.MethodBuilder;
}
internal MethodBuilderInfo GetMethodBuilder(string methodName)
{
System.Diagnostics.Debug.Assert(_methodBuilders.ContainsKey(methodName));
return _methodBuilders[methodName];
}
internal virtual void GenerateMethod(TypeMapping mapping) { }
internal void GenerateReferencedMethods()
{
while (_references > 0)
{
TypeMapping mapping = _referencedMethods[--_references];
GenerateMethod(mapping);
}
}
internal string ReferenceMapping(TypeMapping mapping)
{
if (!_generatedMethods.Contains(mapping))
{
_referencedMethods = EnsureArrayIndex(_referencedMethods, _references);
_referencedMethods[_references++] = mapping;
}
string methodName;
_methodNames.TryGetValue(mapping, out methodName);
return methodName;
}
private TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index)
{
if (a == null) return new TypeMapping[32];
if (index < a.Length) return a;
TypeMapping[] b = new TypeMapping[a.Length + 32];
Array.Copy(a, 0, b, 0, index);
return b;
}
internal string GetCSharpString(string value)
{
return ReflectionAwareILGen.GetCSharpString(value);
}
internal FieldBuilder GenerateHashtableGetBegin(string privateName, string publicName, TypeBuilder serializerContractTypeBuilder)
{
FieldBuilder fieldBuilder = serializerContractTypeBuilder.DefineField(
privateName,
typeof(Hashtable),
FieldAttributes.Private
);
ilg = new CodeGenerator(serializerContractTypeBuilder);
PropertyBuilder propertyBuilder = serializerContractTypeBuilder.DefineProperty(
publicName,
PropertyAttributes.None,
CallingConventions.HasThis,
typeof(Hashtable),
null, null, null, null, null);
ilg.BeginMethod(
typeof(Hashtable),
"get_" + publicName,
Array.Empty<Type>(),
Array.Empty<string>(),
CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName);
propertyBuilder.SetGetMethod(ilg.MethodBuilder);
ilg.Ldarg(0);
ilg.LoadMember(fieldBuilder);
ilg.Load(null);
// this 'if' ends in GenerateHashtableGetEnd
ilg.If(Cmp.EqualTo);
ConstructorInfo Hashtable_ctor = typeof(Hashtable).GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
LocalBuilder _tmpLoc = ilg.DeclareLocal(typeof(Hashtable), "_tmp");
ilg.New(Hashtable_ctor);
ilg.Stloc(_tmpLoc);
return fieldBuilder;
}
internal void GenerateHashtableGetEnd(FieldBuilder fieldBuilder)
{
ilg.Ldarg(0);
ilg.LoadMember(fieldBuilder);
ilg.Load(null);
ilg.If(Cmp.EqualTo);
{
ilg.Ldarg(0);
ilg.Ldloc(typeof(Hashtable), "_tmp");
ilg.StoreMember(fieldBuilder);
}
ilg.EndIf();
// 'endif' from GenerateHashtableGetBegin
ilg.EndIf();
ilg.Ldarg(0);
ilg.LoadMember(fieldBuilder);
ilg.GotoMethodEnd();
ilg.EndMethod();
}
internal FieldBuilder GeneratePublicMethods(string privateName, string publicName, string[] methods, XmlMapping[] xmlMappings, TypeBuilder serializerContractTypeBuilder)
{
FieldBuilder fieldBuilder = GenerateHashtableGetBegin(privateName, publicName, serializerContractTypeBuilder);
if (methods != null && methods.Length != 0 && xmlMappings != null && xmlMappings.Length == methods.Length)
{
MethodInfo Hashtable_set_Item = typeof(Hashtable).GetMethod(
"set_Item",
new Type[] { typeof(object), typeof(object) }
);
for (int i = 0; i < methods.Length; i++)
{
if (methods[i] == null)
continue;
ilg.Ldloc(typeof(Hashtable), "_tmp");
ilg.Ldstr(GetCSharpString(xmlMappings[i].Key));
ilg.Ldstr(GetCSharpString(methods[i]));
ilg.Call(Hashtable_set_Item);
}
}
GenerateHashtableGetEnd(fieldBuilder);
return fieldBuilder;
}
internal void GenerateSupportedTypes(Type[] types, TypeBuilder serializerContractTypeBuilder)
{
ilg = new CodeGenerator(serializerContractTypeBuilder);
ilg.BeginMethod(
typeof(bool),
"CanSerialize",
new Type[] { typeof(Type) },
new string[] { "type" },
CodeGenerator.PublicOverrideMethodAttributes);
var uniqueTypes = new HashSet<Type>();
for (int i = 0; i < types.Length; i++)
{
Type type = types[i];
if (type == null)
continue;
if (!type.IsPublic && !type.IsNestedPublic)
continue;
if (!uniqueTypes.Add(type))
continue;
// DDB172141: Wrong generated CS for serializer of List<string> type
if (type.IsGenericType || type.ContainsGenericParameters)
continue;
ilg.Ldarg("type");
ilg.Ldc(type);
ilg.If(Cmp.EqualTo);
{
ilg.Ldc(true);
ilg.GotoMethodEnd();
}
ilg.EndIf();
}
ilg.Ldc(false);
ilg.GotoMethodEnd();
ilg.EndMethod();
}
internal string GenerateBaseSerializer(string baseSerializer, string readerClass, string writerClass, CodeIdentifiers classes)
{
baseSerializer = CodeIdentifier.MakeValid(baseSerializer);
baseSerializer = classes.AddUnique(baseSerializer, baseSerializer);
TypeBuilder baseSerializerTypeBuilder = CodeGenerator.CreateTypeBuilder(
_moduleBuilder,
CodeIdentifier.GetCSharpName(baseSerializer),
TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.BeforeFieldInit,
typeof(XmlSerializer),
Array.Empty<Type>());
ConstructorInfo readerCtor = CreatedTypes[readerClass].GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg = new CodeGenerator(baseSerializerTypeBuilder);
ilg.BeginMethod(typeof(XmlSerializationReader),
"CreateReader",
Array.Empty<Type>(),
Array.Empty<string>(),
CodeGenerator.ProtectedOverrideMethodAttributes);
ilg.New(readerCtor);
ilg.EndMethod();
ConstructorInfo writerCtor = CreatedTypes[writerClass].GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg.BeginMethod(typeof(XmlSerializationWriter),
"CreateWriter",
Array.Empty<Type>(),
Array.Empty<string>(),
CodeGenerator.ProtectedOverrideMethodAttributes);
ilg.New(writerCtor);
ilg.EndMethod();
baseSerializerTypeBuilder.DefineDefaultConstructor(
MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
Type baseSerializerType = baseSerializerTypeBuilder.CreateTypeInfo().AsType();
CreatedTypes.Add(baseSerializerType.Name, baseSerializerType);
return baseSerializer;
}
internal string GenerateTypedSerializer(string readMethod, string writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass)
{
string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping.TypeDesc.Name));
serializerName = classes.AddUnique(serializerName + "Serializer", mapping);
TypeBuilder typedSerializerTypeBuilder = CodeGenerator.CreateTypeBuilder(
_moduleBuilder,
CodeIdentifier.GetCSharpName(serializerName),
TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit,
CreatedTypes[baseSerializer],
Array.Empty<Type>()
);
ilg = new CodeGenerator(typedSerializerTypeBuilder);
ilg.BeginMethod(
typeof(bool),
"CanDeserialize",
new Type[] { typeof(XmlReader) },
new string[] { "xmlReader" },
CodeGenerator.PublicOverrideMethodAttributes
);
if (mapping.Accessor.Any)
{
ilg.Ldc(true);
ilg.Stloc(ilg.ReturnLocal);
ilg.Br(ilg.ReturnLabel);
}
else
{
MethodInfo XmlReader_IsStartElement = typeof(XmlReader).GetMethod(
"IsStartElement",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string) }
);
ilg.Ldarg(ilg.GetArg("xmlReader"));
ilg.Ldstr(GetCSharpString(mapping.Accessor.Name));
ilg.Ldstr(GetCSharpString(mapping.Accessor.Namespace));
ilg.Call(XmlReader_IsStartElement);
ilg.Stloc(ilg.ReturnLocal);
ilg.Br(ilg.ReturnLabel);
}
ilg.MarkLabel(ilg.ReturnLabel);
ilg.Ldloc(ilg.ReturnLocal);
ilg.EndMethod();
if (writeMethod != null)
{
ilg = new CodeGenerator(typedSerializerTypeBuilder);
ilg.BeginMethod(
typeof(void),
"Serialize",
new Type[] { typeof(object), typeof(XmlSerializationWriter) },
new string[] { "objectToSerialize", "writer" },
CodeGenerator.ProtectedOverrideMethodAttributes);
MethodInfo writerType_writeMethod = CreatedTypes[writerClass].GetMethod(
writeMethod,
CodeGenerator.InstanceBindingFlags,
new Type[] { (mapping is XmlMembersMapping) ? typeof(object[]) : typeof(object) }
);
ilg.Ldarg("writer");
ilg.Castclass(CreatedTypes[writerClass]);
ilg.Ldarg("objectToSerialize");
if (mapping is XmlMembersMapping)
{
ilg.ConvertValue(typeof(object), typeof(object[]));
}
ilg.Call(writerType_writeMethod);
ilg.EndMethod();
}
if (readMethod != null)
{
ilg = new CodeGenerator(typedSerializerTypeBuilder);
ilg.BeginMethod(
typeof(object),
"Deserialize",
new Type[] { typeof(XmlSerializationReader) },
new string[] { "reader" },
CodeGenerator.ProtectedOverrideMethodAttributes);
MethodInfo readerType_readMethod = CreatedTypes[readerClass].GetMethod(
readMethod,
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg.Ldarg("reader");
ilg.Castclass(CreatedTypes[readerClass]);
ilg.Call(readerType_readMethod);
ilg.EndMethod();
}
typedSerializerTypeBuilder.DefineDefaultConstructor(CodeGenerator.PublicMethodAttributes);
Type typedSerializerType = typedSerializerTypeBuilder.CreateTypeInfo().AsType();
CreatedTypes.Add(typedSerializerType.Name, typedSerializerType);
return typedSerializerType.Name;
}
private FieldBuilder GenerateTypedSerializers(Dictionary<string, string> serializers, TypeBuilder serializerContractTypeBuilder)
{
string privateName = "typedSerializers";
FieldBuilder fieldBuilder = GenerateHashtableGetBegin(privateName, "TypedSerializers", serializerContractTypeBuilder);
MethodInfo Hashtable_Add = typeof(Hashtable).GetMethod(
"Add",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(object), typeof(object) }
);
foreach (string key in serializers.Keys)
{
ConstructorInfo ctor = CreatedTypes[(string)serializers[key]].GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg.Ldloc(typeof(Hashtable), "_tmp");
ilg.Ldstr(GetCSharpString(key));
ilg.New(ctor);
ilg.Call(Hashtable_Add);
}
GenerateHashtableGetEnd(fieldBuilder);
return fieldBuilder;
}
//GenerateGetSerializer(serializers, xmlMappings);
private void GenerateGetSerializer(Dictionary<string, string> serializers, XmlMapping[] xmlMappings, TypeBuilder serializerContractTypeBuilder)
{
ilg = new CodeGenerator(serializerContractTypeBuilder);
ilg.BeginMethod(
typeof(XmlSerializer),
"GetSerializer",
new Type[] { typeof(Type) },
new string[] { "type" },
CodeGenerator.PublicOverrideMethodAttributes);
for (int i = 0; i < xmlMappings.Length; i++)
{
if (xmlMappings[i] is XmlTypeMapping)
{
Type type = xmlMappings[i].Accessor.Mapping.TypeDesc.Type;
if (type == null)
continue;
if (!type.IsPublic && !type.IsNestedPublic)
continue;
// DDB172141: Wrong generated CS for serializer of List<string> type
if (type.IsGenericType || type.ContainsGenericParameters)
continue;
ilg.Ldarg("type");
ilg.Ldc(type);
ilg.If(Cmp.EqualTo);
{
ConstructorInfo ctor = CreatedTypes[(string)serializers[xmlMappings[i].Key]].GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg.New(ctor);
ilg.Stloc(ilg.ReturnLocal);
ilg.Br(ilg.ReturnLabel);
}
ilg.EndIf();
}
}
ilg.Load(null);
ilg.Stloc(ilg.ReturnLocal);
ilg.Br(ilg.ReturnLabel);
ilg.MarkLabel(ilg.ReturnLabel);
ilg.Ldloc(ilg.ReturnLocal);
ilg.EndMethod();
}
internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type[] types, string readerType, string[] readMethods, string writerType, string[] writerMethods, Dictionary<string, string> serializers)
{
TypeBuilder serializerContractTypeBuilder = CodeGenerator.CreateTypeBuilder(
_moduleBuilder,
"XmlSerializerContract",
TypeAttributes.Public | TypeAttributes.BeforeFieldInit,
typeof(XmlSerializerImplementation),
Array.Empty<Type>()
);
ilg = new CodeGenerator(serializerContractTypeBuilder);
PropertyBuilder propertyBuilder = serializerContractTypeBuilder.DefineProperty(
"Reader",
PropertyAttributes.None,
typeof(XmlSerializationReader),
null, null, null, null, null);
ilg.BeginMethod(
typeof(XmlSerializationReader),
"get_Reader",
Array.Empty<Type>(),
Array.Empty<string>(),
CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName);
propertyBuilder.SetGetMethod(ilg.MethodBuilder);
ConstructorInfo ctor = CreatedTypes[readerType].GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg.New(ctor);
ilg.EndMethod();
ilg = new CodeGenerator(serializerContractTypeBuilder);
propertyBuilder = serializerContractTypeBuilder.DefineProperty(
"Writer",
PropertyAttributes.None,
typeof(XmlSerializationWriter),
null, null, null, null, null);
ilg.BeginMethod(
typeof(XmlSerializationWriter),
"get_Writer",
Array.Empty<Type>(),
Array.Empty<string>(),
CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName);
propertyBuilder.SetGetMethod(ilg.MethodBuilder);
ctor = CreatedTypes[writerType].GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg.New(ctor);
ilg.EndMethod();
FieldBuilder readMethodsField = GeneratePublicMethods(nameof(readMethods), "ReadMethods", readMethods, xmlMappings, serializerContractTypeBuilder);
FieldBuilder writeMethodsField = GeneratePublicMethods("writeMethods", "WriteMethods", writerMethods, xmlMappings, serializerContractTypeBuilder);
FieldBuilder typedSerializersField = GenerateTypedSerializers(serializers, serializerContractTypeBuilder);
GenerateSupportedTypes(types, serializerContractTypeBuilder);
GenerateGetSerializer(serializers, xmlMappings, serializerContractTypeBuilder);
// Default ctor
ConstructorInfo baseCtor = typeof(XmlSerializerImplementation).GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg = new CodeGenerator(serializerContractTypeBuilder);
ilg.BeginMethod(
typeof(void),
".ctor",
Array.Empty<Type>(),
Array.Empty<string>(),
CodeGenerator.PublicMethodAttributes | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName
);
ilg.Ldarg(0);
ilg.Load(null);
ilg.StoreMember(readMethodsField);
ilg.Ldarg(0);
ilg.Load(null);
ilg.StoreMember(writeMethodsField);
ilg.Ldarg(0);
ilg.Load(null);
ilg.StoreMember(typedSerializersField);
ilg.Ldarg(0);
ilg.Call(baseCtor);
ilg.EndMethod();
// Instantiate type
Type serializerContractType = serializerContractTypeBuilder.CreateTypeInfo().AsType();
CreatedTypes.Add(serializerContractType.Name, serializerContractType);
}
internal static bool IsWildcard(SpecialMapping mapping)
{
if (mapping is SerializableMapping)
return ((SerializableMapping)mapping).IsAny;
return mapping.TypeDesc.CanBeElementValue;
}
internal void ILGenLoad(string source)
{
ILGenLoad(source, null);
}
internal void ILGenLoad(string source, Type type)
{
if (source.StartsWith("o.@", StringComparison.Ordinal))
{
System.Diagnostics.Debug.Assert(memberInfos.ContainsKey(source.Substring(3)));
MemberInfo memInfo = memberInfos[source.Substring(3)];
ilg.LoadMember(ilg.GetVariable("o"), memInfo);
if (type != null)
{
Type memType = (memInfo is FieldInfo) ? ((FieldInfo)memInfo).FieldType : ((PropertyInfo)memInfo).PropertyType;
ilg.ConvertValue(memType, type);
}
}
else
{
SourceInfo info = new SourceInfo(source, null, null, null, ilg);
info.Load(type);
}
}
}
}
| |
using LogShark.Plugins.Backgrounder.Model;
using LogShark.Plugins.Shared;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using LogShark.Extensions;
using LogShark.Shared;
using LogShark.Shared.Extensions;
using LogShark.Shared.LogReading.Containers;
namespace LogShark.Plugins.Backgrounder
{
public class BackgrounderEventParser
{
private readonly Dictionary<string, int?> _backgrounderIds;
private readonly IBackgrounderEventPersister _backgrounderEventPersister;
private readonly IProcessingNotificationsCollector _processingNotificationsCollector;
private readonly object _getBackgrounderIdLock;
#region Regex
private static readonly Regex BackgrounderIdFromFileNameRegex =
new Regex(@"backgrounder(_node\d+)?-(?<backgrounder_id>\d+)\.",
RegexOptions.ExplicitCapture | RegexOptions.Compiled);
//2018.2 linux/node1/backgrounder_0.20182.18.0627.22303567494456574693215/logs/backgrounder_node1-0.log:216:
//2018-08-08 11:16:31.950 +1000 (,,,,1,:update_vertica_keychains,-) scheduled-background-job-runner-1 backgrounder: INFO com.tableausoftware.backgrounder.runner.BackgroundJobRunner - Running job of type UpdateVerticaKeychains; no timeout; priority: 0; id: null; args: []
//-----------ts---------- ts_of ^^^^^--------job_type----------^ -------------thread-------------- --service--- sev- ----------------------------class-------------------------- ------------------------------------------message--------------------------------------
// ||||| |>local_req_id
// |||||>job_id
// ||||>vql_sess_id
// |||>data_sess_id
// ||>user
// |>site
private static readonly Regex NewBackgrounderRegex =
// 10.4+
// 10.4 added "job type" and 10.5 added "local request id", either of which may be empty and thus are marked optional here
new Regex(@"^
(?<ts>\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}.\d{3})
\s(?<ts_offset>[^\s]+)
\s\((?<site>[^,]*), (?<user>[^,]*), (?<data_sess_id>[^,]*), (?<vql_sess_id>[^,]*), (?<job_id>[^,]*), :?(?<job_type>[^,]*) ,(?<local_req_id>[^\s]*)\)
\s?(?<module>[^\s]*)?
\s(?<thread>[^\s]*)
\s(?<service>[^\s]*):
\s(?<sev>[A-Z]+)(\s+)
(?<class>[^\s]*)
\s?(?<callinfo>{.*})?
\s-\s(?<message>.*)",
RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline | RegexOptions.Compiled);
private static readonly object StartMessageRegexListLock = new object();
private static readonly List<Regex> StartMessageRegexList = new List<Regex>() {
// Running job of type UpdateVerticaKeychains; no timeout; priority: 0; id: null; args: []
// --------------job_type_long--------------- -timeout-- ^ -id- args
// |>priority ^comma delimited inside [], or "null"
new Regex(
@"^Running\sjob\sof\stype\s(?<job_type_long>[^;]+);\s(?<timeout>[^;]+);\spriority:\s(?<priority>[0-9]+);\sid:\s(?<id>[^;]+);\sargs:\s(?<args>.+)$",
RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled),
new Regex(
@"^activity=(?<activity>[^\s]*)\sjob_id=(?<job_id>[^\s]*)\sjob_type=(?<job_type_long>[^\s]*)\srequest_id=(?<request_id>[^\s]*)\sargs=""?\[?(?<args>.*?)\]?""?\ssite=(?<site>.*?)\stimeout=(?<timeout>.*)$",
RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled),
};
//2018.2 linux/node1/backgrounder_0.20182.18.0627.22303567494456574693215/logs/backgrounder_node1-0.log:219:
//2018-08-08 11:16:32.173 +1000 (,,,,1,:update_vertica_keychains,-) scheduled-background-job-runner-1 backgrounder: INFO com.tableausoftware.backgrounder.runner.BackgroundJobRunner - Job finished: SUCCESS;name: Update Vertica Keychains; type :update_vertica_keychains; id: 1; notes: null; total time: 601 sec; run time: 0 sec
// Job finished: SUCCESS;name: Update Vertica Keychains; type :update_vertica_keychains; id: 1; notes: null; total time: 601 sec; run time: 0 sec
// -----job_result------ ---------name----------- ----------type---------- ^ notes ^ ^
// |>id |>total_time |>run_time
private static readonly Regex EndMessageRegex =
new Regex(
@"(?<job_result>[^;]+);\s?name:\s(?<name>[^;]+);\s?type\s?:(?<type>[^;]+);\sid:\s(?<id>[^;]+);(\snotes:\s(?<notes>[^;]+);)?\stotal\stime:\s(?<total_time>[0-9]+)\ssec;\srun\stime:\s(?<run_time>[0-9]+)\ssec",
RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
// Sending email from tableau@test.com to john.doe@test.com from server mail.test.com
// --sender_email-- -recipient_email- -smtp_server--
private static readonly Regex SendEmailDetailsRegex =
new Regex(
@"Sending email from\s(?<sender_email>[^\s]*)\sto\s(?<recipient_email>[^\s]*)\sfrom server\s(?<smtp_server>.*)$",
RegexOptions.ExplicitCapture | RegexOptions.Compiled); // Not ignoring pattern whitespace to keep regex cleaner
// Starting Subscription Id 1071 for User test Created by test with Subject this is the subject
// -subscription_id- -user- -created_by_user- -subscription_name-
private static readonly Regex StartingSubscriptionRegex =
new Regex(
@"^
Starting\s[sS]ubscription\sId\s
(?<subscription_id>\d+)
\sfor\sUser\s
(?<user>[^\s]+)
(?:\sCreated\sby\s(?<created_by_user>[^\s]+))?
\s(?:with\s)?(?:Subject\s)?
\""?(?<subscription_name>.*?)\""?$",
RegexOptions.ExplicitCapture | RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace);
private static readonly Regex ExtractJobDetailsParseRegex = new Regex(@"\|(?<key>[a-zA-Z]+)=(?<value>[\s\S]*?)(?=\|[a-zA-Z]*=|$)",
RegexOptions.ExplicitCapture | RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace);
#endregion Regex
public BackgrounderEventParser(IBackgrounderEventPersister backgrounderEventPersister, IProcessingNotificationsCollector processingNotificationsCollector)
{
_backgrounderIds = new Dictionary<string, int?>();
_backgrounderEventPersister = backgrounderEventPersister;
_processingNotificationsCollector = processingNotificationsCollector;
_getBackgrounderIdLock = new object();
}
public void ParseAndPersistLine(LogLine logLine, string logLineText)
{
if (logLineText == null || logLine == null)
{
_processingNotificationsCollector.ReportError($"{nameof(BackgrounderEventParser)} received null log line or log string", logLine, nameof(BackgrounderPlugin));
return;
}
var backgrounderId = GetBackgrounderId(logLine);
var lineMatch = NewBackgrounderRegex.Match(logLineText);
if (!lineMatch.Success)
{
_processingNotificationsCollector.ReportError($"Failed to process string as Backgrounder event. This is expected for logs prior to 10.4", logLine, nameof(BackgrounderPlugin));
return;
}
var errorEvent = ParseErrorMessage(lineMatch, logLine);
if (errorEvent != null)
{
_backgrounderEventPersister.AddErrorEvent(errorEvent);
return;
}
if (!int.TryParse(lineMatch.Groups["job_id"].Value, out var jobId))
{
return; // We only allow error messages to not have job id
}
var startEvent = TryMatchStartMessage(lineMatch, logLine, backgrounderId, jobId);
if (startEvent != null)
{
_backgrounderEventPersister.AddStartEvent(startEvent);
return;
}
var endEvent = TryMatchEndMessage(lineMatch, logLine, jobId);
if (endEvent != null)
{
_backgrounderEventPersister.AddEndEvent(endEvent);
return;
}
var extractJobDetails = TryMatchExtractJobDetails(lineMatch, jobId, logLine);
if (extractJobDetails != null)
{
_backgrounderEventPersister.AddExtractJobDetails(extractJobDetails);
return;
}
var subscriptionJobDetails = TryMatchSubscriptionJobDetails(lineMatch, jobId);
if (subscriptionJobDetails != null)
{
_backgrounderEventPersister.AddSubscriptionJobDetails(subscriptionJobDetails);
return;
}
}
private int? GetBackgrounderId(LogLine logLine)
{
lock (_getBackgrounderIdLock)
{
if (_backgrounderIds.ContainsKey(logLine.LogFileInfo.FilePath))
{
return _backgrounderIds[logLine.LogFileInfo.FilePath];
}
var backgrounderIdMatch = BackgrounderIdFromFileNameRegex.Match(logLine.LogFileInfo.FileName);
var backgrounderIdValue = backgrounderIdMatch.Success &&
int.TryParse(backgrounderIdMatch.Groups["backgrounder_id"].Value,
out var parsedBackgrounderId)
? parsedBackgrounderId
: (int?) null;
if (backgrounderIdValue == null)
{
const string message =
"Failed to parse backgrounderId from filename. All events from this file will have null id";
_processingNotificationsCollector.ReportError(message, logLine, nameof(BackgrounderPlugin));
}
_backgrounderIds.Add(logLine.LogFileInfo.FilePath, backgrounderIdValue);
return backgrounderIdValue;
}
}
private static BackgrounderJobError ParseErrorMessage(Match lineMatch, LogLine logLine)
{
if (lineMatch.Groups["sev"].Value != "ERROR" && lineMatch.Groups["sev"].Value != "FATAL")
{
return null;
}
return new BackgrounderJobError
{
BackgrounderJobId = long.TryParse(lineMatch.Groups["job_id"].Value, out var jobId) ? jobId : default(long?),
Class = lineMatch.Groups["class"].Value,
File = logLine.LogFileInfo.FileName,
Line = logLine.LineNumber,
Message = lineMatch.Groups["message"].Value,
Severity = lineMatch.Groups["sev"].Value,
Site = lineMatch.Groups["site"].Value,
Thread = lineMatch.Groups["thread"].Value,
Timestamp = TimestampParsers.ParseJavaLogsTimestamp(lineMatch.Groups["ts"].Value),
};
}
private static BackgrounderJob TryMatchStartMessage(Match lineMatch, LogLine logLine, int? backgrounderId, long jobId)
{
var message = lineMatch.Groups["message"].Value;
var startMessageMatch = message?.GetRegexMatchAndMoveCorrectRegexUpFront(StartMessageRegexList, StartMessageRegexListLock);
if (startMessageMatch == null || !startMessageMatch.Success)
{
return null;
}
var args = startMessageMatch.Groups["args"].Value;
args = (args == "[]" || args == "null") ? null : args;
var timeoutStr = startMessageMatch.Groups["timeout"].Value?.Replace("timeout: ", "");
var timeout = int.TryParse(timeoutStr, out var to) ? to : default(int?);
return new BackgrounderJob
{
Args = args,
BackgrounderId = backgrounderId,
JobId = jobId,
JobType = lineMatch.Groups["job_type"].Value,
Priority = int.TryParse(startMessageMatch.Groups["priority"].Value, out var pri) ? pri : default(int),
StartFile = logLine.LogFileInfo.FileName,
StartLine = logLine.LineNumber,
StartTime = TimestampParsers.ParseJavaLogsTimestamp(lineMatch.Groups["ts"].Value),
Timeout = timeout,
WorkerId = logLine.LogFileInfo.Worker,
};
}
private static BackgrounderJob TryMatchEndMessage(Match lineMatch, LogLine logLine, int jobId)
{
var message = lineMatch.Groups["message"].Value;
if (!message.StartsWith("Job finished:") && !message.StartsWith("Error executing backgroundjob:"))
{
return null;
}
var endEvent = new BackgrounderJob
{
JobId = jobId,
EndFile = logLine.LogFileInfo.FileName,
EndLine = logLine.LineNumber,
EndTime = TimestampParsers.ParseJavaLogsTimestamp(lineMatch.Groups["ts"].Value),
};
var endMessageMatch = EndMessageRegex.Match(message);
var notes = endMessageMatch.Groups["notes"].Value;
if (notes == "null" || string.IsNullOrWhiteSpace(notes))
{
notes = null;
}
if (message.StartsWith("Job finished: SUCCESS"))
{
endEvent.Success = true;
endEvent.Notes = notes;
endEvent.TotalTime = int.TryParse(endMessageMatch.Groups["total_time"].Value, out var totalTime) ? totalTime : default(int?);
endEvent.RunTime = int.TryParse(endMessageMatch.Groups["run_time"].Value, out var runTime) ? runTime : default(int?);
}
else
{
endEvent.Success = false;
endEvent.ErrorMessage = message;
}
return endEvent;
}
private BackgrounderExtractJobDetail TryMatchExtractJobDetails(Match lineMatch, int jobId, LogLine logLine)
{
var eventClass = lineMatch.Groups["class"].Value;
var message = lineMatch.Groups["message"].Value;
switch (eventClass)
{
case "com.tableausoftware.model.workgroup.service.VqlSessionService":
return TryMatchOlderFormatOfExtractJobDetails(message, jobId, lineMatch.Groups["vql_sess_id"].Value);
case "com.tableausoftware.model.workgroup.workers.RefreshExtractsWorker":
return TryMatchNewFormatOfExtractJobDetails(message, jobId, logLine);
default:
return null;
}
}
//2019-04-30 06:16:53.626 -0400 (Enterprise Business Intelligence,,,3619ADAAA1B54302B9349F4368A3AAA3,4950695,:refresh_extracts,-) pool-19-thread-1 backgrounder: INFO com.tableausoftware.model.workgroup.service.VqlSessionService - Storing to SOS: OPPE/extract reducedDataId:9eb94068-5e1f-437b-9c4d-a1b700414ca8 size:134352 (twb) + 3604480 (guid={0F1B99B6-71A2-48C8-A9BC-7BA6D447515E}) = 3738832
// Storing to SOS: OPPE/extract reducedDataId:9eb94068-5e1f-437b-9c4d-a1b700414ca8 size:134352 (twb) + 3604480 (guid={0F1B99B6-71A2-48C8-A9BC-7BA6D447515E}) = 3738832
// extract_url- -------------extract_id------------- twb_size extract_size -----------extract_guid------------ total_size
private static readonly Regex VqlSessionExtractDetailsRegex =
new Regex(@"^
Storing\sto\s(repository|SOS):\s
(?<extract_url>.+?)/extract\s
(repoExtractId|reducedDataId):(?<extract_id>.+?)\s
size:(?<twb_size>\d+?)\s\(twb\)\s
\+\s(?<extract_size>\d+?)\s
\(guid={(?<extract_guid>[0-9A-F-]+?)}\)\s
=\s(?<total_size>\d+?)$",
RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
private static BackgrounderExtractJobDetail TryMatchOlderFormatOfExtractJobDetails(string message, int jobId, string vizqlSessionId)
{
var extractMatch = VqlSessionExtractDetailsRegex.Match(message);
if (!extractMatch.Success)
{
return null;
}
return new BackgrounderExtractJobDetail
{
BackgrounderJobId = jobId,
ExtractGuid = extractMatch.Groups["extract_guid"].Value,
ExtractId = extractMatch.Groups["extract_id"].Value,
ExtractSize = long.TryParse(extractMatch.Groups["extract_size"].Value, out var extractSize) ? extractSize : default(long?),
ExtractUrl = extractMatch.Groups["extract_url"].Value,
JobNotes = null, // Not available in the old format
ScheduleName = null, // Not available in the old format
Site = null, // Not available in the old format
TotalSize = long.TryParse(extractMatch.Groups["total_size"].Value, out var totalSize) ? totalSize : default(long?),
TwbSize = long.TryParse(extractMatch.Groups["twb_size"].Value, out var twbSize) ? twbSize : default(long?),
VizqlSessionId = vizqlSessionId
};
}
// New format log example
// 2019-08-09 21:50:17.641 +0000 (Default,,,,201,:refresh_extracts,ee6dd62e-f472-4252-a931-caf4dfb0009f) pool-12-thread-1 backgrounder: INFO com.tableausoftware.model.workgroup.workers.RefreshExtractsWorker - |status=ExtractTimingSuccess|jobId=201|jobLuid=ee6dd62e-f472-4252-a931-caf4dfb0009f|siteName="Default"|workbookName="Large1"|refreshedAt="2019-08-09T21:50:17.638Z"|sessionId=F7162DFF82CB48D386850188BD5B190A-1:1|scheduleName="Weekday early mornings"|scheduleType="FullRefresh"|jobName="Refresh Extracts"|jobType="RefreshExtracts"|totalTimeSeconds=48|runTimeSeconds=46|queuedTime="2019-08-09T21:49:29.076Z"|startedTime="2019-08-09T21:49:31.262Z"|endTime="2019-08-09T21:50:17.638Z"|correlationId=65|priority=0|serialId=null|extractsSizeBytes=57016320|jobNotes="Finished refresh of extracts (new extract id:{78C1FCC2-E70E-4B25-BFFE-7B7F0096A4FE}) for Workbook 'Large1' "
private static readonly Regex ExtractIdNewFormat = new Regex(
@"Finished refresh of extracts \(new extract id:{(?<extractGuid>[^\}]+)}\)",
RegexOptions.Compiled);
private BackgrounderExtractJobDetail TryMatchNewFormatOfExtractJobDetails(string message, int jobId, LogLine logLine)
{
if (!message.StartsWith('|'))
{
return null;
}
var messageParts = ExtractJobDetailsParseRegex.Matches(message).ToDictionary(m => m.Groups["key"].Value, m => m.Groups["value"].Value);
var jobNotes = messageParts.GetStringValueOrNull("jobNotes").TrimSurroundingDoubleQuotes();
var extractIdMatch = ExtractIdNewFormat.Match(jobNotes ?? string.Empty);
var extractId = extractIdMatch.Success
? extractIdMatch.Groups["extractGuid"].Value
: null;
return new BackgrounderExtractJobDetail
{
BackgrounderJobId = jobId,
ExtractGuid = null, // Not available in the new format
ExtractId = extractId,
ExtractSize = messageParts.GetLongValueOrNull("extractsSizeBytes"),
ExtractUrl = messageParts.GetStringValueOrNull("workbookName").TrimSurroundingDoubleQuotes()
?? messageParts.GetStringValueOrNull("datasourceName").TrimSurroundingDoubleQuotes(),
JobNotes = jobNotes,
ScheduleName = messageParts.GetStringValueOrNull("scheduleName").TrimSurroundingDoubleQuotes(),
Site = messageParts.GetStringValueOrNull("siteName").TrimSurroundingDoubleQuotes(),
TotalSize = null, // Not available in the new format
TwbSize = null, // Not available in the new format
VizqlSessionId = messageParts.GetStringValueOrNull("sessionId").TrimSurroundingDoubleQuotes()
};
}
private static BackgrounderSubscriptionJobDetail TryMatchSubscriptionJobDetails(Match lineMatch, int jobId)
{
var message = lineMatch.Groups["message"].Value;
var @class = lineMatch.Groups["class"].Value;
switch (@class)
{
case "com.tableausoftware.model.workgroup.service.VqlSessionService" when message.StartsWith("Created session id:"):
return new BackgrounderSubscriptionJobDetail
{
BackgrounderJobId = jobId,
VizqlSessionId = message.Split(':')[1]
};
case "com.tableausoftware.domain.subscription.SubscriptionRunner" when message.StartsWith("Starting subscription", System.StringComparison.InvariantCultureIgnoreCase):
case "com.tableausoftware.model.workgroup.service.subscriptions.SubscriptionRunner" when message.StartsWith("Starting subscription", System.StringComparison.InvariantCultureIgnoreCase):
var subscriptionMatch = StartingSubscriptionRegex.Match(message);
return new BackgrounderSubscriptionJobDetail
{
BackgrounderJobId = jobId,
SubscriptionName = subscriptionMatch.Groups["subscription_name"].Value
};
case "com.tableausoftware.model.workgroup.util.EmailHelper" when message.StartsWith("Sending email from"):
{
var emailMatch = SendEmailDetailsRegex.Match(message);
return new BackgrounderSubscriptionJobDetail
{
BackgrounderJobId = jobId,
SenderEmail = emailMatch.Groups["sender_email"].Value,
RecipientEmail = emailMatch.Groups["recipient_email"].Value,
SmtpServer = emailMatch.Groups["smtp_server"].Value,
};
}
default:
return null;
}
}
}
}
| |
using AutoMapper;
using Microsoft.Azure.Commands.Compute.Common;
using Microsoft.Azure.Commands.Compute.Models;
using Microsoft.Azure.Common.Authentication.Models;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Text.RegularExpressions;
namespace Microsoft.Azure.Commands.Compute.Extension.DSC
{
[Cmdlet(
VerbsCommon.Set,
ProfileNouns.VirtualMachineDscExtension,
SupportsShouldProcess = true,
DefaultParameterSetName = AzureBlobDscExtensionParamSet)]
[OutputType(typeof(PSComputeLongRunningOperation))]
public class SetAzureVMDscExtensionCommand : VirtualMachineExtensionBaseCmdlet
{
protected const string AzureBlobDscExtensionParamSet = "AzureBlobDscExtension";
[Parameter(
Mandatory = true,
Position = 2,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The name of the resource group that contains the virtual machine.")]
[ValidateNotNullOrEmpty]
public string ResourceGroupName { get; set; }
[Parameter(
Mandatory = true,
Position = 3,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Name of the virtual machine where dsc extension handler would be installed.")]
[ValidateNotNullOrEmpty]
public string VMName { get; set; }
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "Name of the DSC Extension handler. It will default to 'DSC' when it is not provided.")]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
/// <summary>
/// The name of the configuration archive that was previously uploaded by
/// Publish-AzureVMDSCConfiguration. This parameter must specify only the name
/// of the file, without any path.
/// A null value or empty string indicate that the VM extension should install DSC,
/// but not start any configuration
/// </summary>
[Alias("ConfigurationArchiveBlob")]
[Parameter(
Mandatory = true,
Position = 5,
ValueFromPipelineByPropertyName = true,
ParameterSetName = AzureBlobDscExtensionParamSet,
HelpMessage = "The name of the configuration file that was previously uploaded by Publish-AzureVMDSCConfiguration")]
[AllowEmptyString]
[AllowNull]
public string ArchiveBlobName { get; set; }
/// <summary>
/// The Azure Storage Account name used to upload the configuration script to the container specified by ArchiveContainerName.
/// </summary>
[Alias("StorageAccountName")]
[Parameter(
Mandatory = true,
Position = 4,
ValueFromPipelineByPropertyName = true,
ParameterSetName = AzureBlobDscExtensionParamSet,
HelpMessage = "The Azure Storage Account name used to download the ArchiveBlobName")]
[ValidateNotNullOrEmpty]
public String ArchiveStorageAccountName { get; set; }
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = AzureBlobDscExtensionParamSet,
HelpMessage = "The name of the resource group that contains the storage account containing the configuration archive. " +
"This param is optional if storage account and virtual machine both exists in the same resource group name, " +
"specified by ResourceGroupName param.")]
[ValidateNotNullOrEmpty]
public string ArchiveResourceGroupName { get; set; }
/// <summary>
/// The DNS endpoint suffix for all storage services, e.g. "core.windows.net".
/// </summary>
[Alias("StorageEndpointSuffix")]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = AzureBlobDscExtensionParamSet,
HelpMessage = "The Storage Endpoint Suffix.")]
[ValidateNotNullOrEmpty]
public string ArchiveStorageEndpointSuffix { get; set; }
/// <summary>
/// Name of the Azure Storage Container where the configuration script is located.
/// </summary>
[Alias("ContainerName")]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = AzureBlobDscExtensionParamSet,
HelpMessage = "Name of the Azure Storage Container where the configuration archive is located")]
[ValidateNotNullOrEmpty]
public string ArchiveContainerName { get; set; }
/// <summary>
/// Name of the configuration that will be invoked by the DSC Extension. The value of this parameter should be the name of one of the configurations
/// contained within the file specified by ArchiveBlobName.
///
/// If omitted, this parameter will default to the name of the file given by the ArchiveBlobName parameter, excluding any extension, for example if
/// ArchiveBlobName is "SalesWebSite.ps1", the default value for ConfigurationName will be "SalesWebSite".
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "Name of the configuration that will be invoked by the DSC Extension")]
[ValidateNotNullOrEmpty]
public string ConfigurationName { get; set; }
/// <summary>
/// A hashtable specifying the arguments to the ConfigurationFunction. The keys
/// correspond to the parameter names and the values to the parameter values.
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "A hashtable specifying the arguments to the ConfigurationFunction")]
[ValidateNotNullOrEmpty]
public Hashtable ConfigurationArgument { get; set; }
/// <summary>
/// Path to a .psd1 file that specifies the data for the Configuration. This
/// file must contain a hashtable with the items described in
/// http://technet.microsoft.com/en-us/library/dn249925.aspx.
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "Path to a .psd1 file that specifies the data for the Configuration")]
[ValidateNotNullOrEmpty]
public string ConfigurationData { get; set; }
/// <summary>
/// The specific version of the DSC extension that Set-AzureVMDSCExtension will
/// apply the settings to.
/// </summary>
[Alias("HandlerVersion")]
[Parameter(
Mandatory = true,
Position = 1,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The version of the DSC extension that Set-AzureVMDSCExtension will apply the settings to. " +
"Allowed format N.N")]
[ValidateNotNullOrEmpty]
public string Version { get; set; }
/// <summary>
/// By default Set-AzureVMDscExtension will not overwrite any existing blobs. Use -Force to overwrite them.
/// </summary>
[Parameter(
HelpMessage = "Use this parameter to overwrite any existing blobs")]
public SwitchParameter Force { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Location of the resource.")]
[ValidateNotNullOrEmpty]
public string Location { get; set; }
/// <summary>
/// We install the extension handler version specified by the version param. By default extension handler is not autoupdated.
/// Use -AutoUpdate to enable auto update of extension handler to the latest version as and when it is available.
/// </summary>
[Parameter(
HelpMessage = "Extension handler gets auto updated to the latest version if this switch is present.")]
public SwitchParameter AutoUpdate { get; set; }
//Private Variables
private const string VersionRegexExpr = @"^(([0-9])\.)\d+$";
/// <summary>
/// Credentials used to access Azure Storage
/// </summary>
private StorageCredentials _storageCredentials;
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
ValidateParameters();
CreateConfiguration();
}
//Private Methods
private void ValidateParameters()
{
if (string.IsNullOrEmpty(ArchiveBlobName))
{
if (ConfigurationName != null || ConfigurationArgument != null
|| ConfigurationData != null)
{
this.ThrowInvalidArgumentError(Properties.Resources.AzureVMDscNullArchiveNoConfiguragionParameters);
}
if (ArchiveContainerName != null || ArchiveStorageEndpointSuffix != null)
{
this.ThrowInvalidArgumentError(Properties.Resources.AzureVMDscNullArchiveNoStorageParameters);
}
}
else
{
if (string.Compare(
Path.GetFileName(ArchiveBlobName),
ArchiveBlobName,
StringComparison.InvariantCultureIgnoreCase) != 0)
{
this.ThrowInvalidArgumentError(Properties.Resources.AzureVMDscConfigurationDataFileShouldNotIncludePath);
}
if (ConfigurationData != null)
{
ConfigurationData = GetUnresolvedProviderPathFromPSPath(ConfigurationData);
if (!File.Exists(ConfigurationData))
{
this.ThrowInvalidArgumentError(
Properties.Resources.AzureVMDscCannotFindConfigurationDataFile,
ConfigurationData);
}
if (string.Compare(
Path.GetExtension(ConfigurationData),
".psd1",
StringComparison.InvariantCultureIgnoreCase) != 0)
{
this.ThrowInvalidArgumentError(Properties.Resources.AzureVMDscInvalidConfigurationDataFile);
}
}
if (ArchiveResourceGroupName == null)
{
ArchiveResourceGroupName = ResourceGroupName;
}
_storageCredentials = this.GetStorageCredentials(ArchiveResourceGroupName, ArchiveStorageAccountName);
if (ConfigurationName == null)
{
ConfigurationName = Path.GetFileNameWithoutExtension(ArchiveBlobName);
}
if (ArchiveContainerName == null)
{
ArchiveContainerName = DscExtensionCmdletConstants.DefaultContainerName;
}
if (ArchiveStorageEndpointSuffix == null)
{
ArchiveStorageEndpointSuffix =
Profile.Context.Environment.GetEndpoint(AzureEnvironment.Endpoint.StorageEndpointSuffix);
}
if (!(Regex.Match(Version, VersionRegexExpr).Success))
{
this.ThrowInvalidArgumentError(Properties.Resources.AzureVMDscExtensionInvalidVersion);
}
}
}
private void CreateConfiguration()
{
var publicSettings = new DscExtensionPublicSettings();
var privateSettings = new DscExtensionPrivateSettings();
if (!string.IsNullOrEmpty(ArchiveBlobName))
{
ConfigurationUris configurationUris = UploadConfigurationDataToBlob();
publicSettings.SasToken = configurationUris.SasToken;
publicSettings.ModulesUrl = configurationUris.ModulesUrl;
publicSettings.ConfigurationFunction = string.Format(
CultureInfo.InvariantCulture,
"{0}\\{1}",
Path.GetFileNameWithoutExtension(ArchiveBlobName),
ConfigurationName);
Tuple<DscExtensionPublicSettings.Property[], Hashtable> settings =
DscExtensionSettingsSerializer.SeparatePrivateItems(ConfigurationArgument);
publicSettings.Properties = settings.Item1;
privateSettings.Items = settings.Item2;
privateSettings.DataBlobUri = configurationUris.DataBlobUri;
}
var parameters = new VirtualMachineExtension
{
Location = Location,
Name = Name ?? DscExtensionCmdletConstants.ExtensionPublishedNamespace + "." + DscExtensionCmdletConstants.ExtensionPublishedName,
Type = VirtualMachineExtensionType,
Publisher = DscExtensionCmdletConstants.ExtensionPublishedNamespace,
ExtensionType = DscExtensionCmdletConstants.ExtensionPublishedName,
TypeHandlerVersion = Version,
// Define the public and private property bags that will be passed to the extension.
Settings = DscExtensionSettingsSerializer.SerializePublicSettings(publicSettings),
//PrivateConfuguration contains sensitive data in a plain text
ProtectedSettings = DscExtensionSettingsSerializer.SerializePrivateSettings(privateSettings),
AutoUpgradeMinorVersion = AutoUpdate.IsPresent
};
//Add retry logic due to CRP service restart known issue CRP bug: 3564713
var count = 1;
ComputeLongRunningOperationResponse op = null;
while (count <= 2)
{
op = VirtualMachineExtensionClient.CreateOrUpdate(
ResourceGroupName,
VMName,
parameters);
if (ComputeOperationStatus.Failed.Equals(op.Status) && op.Error != null && "InternalExecutionError".Equals(op.Error.Code))
{
count++;
}
else
{
break;
}
}
var result = Mapper.Map<PSComputeLongRunningOperation>(op);
WriteObject(result);
}
/// <summary>
/// Uploading configuration data to blob storage.
/// </summary>
/// <returns>ConfigurationUris collection that represent artifacts of uploading</returns>
private ConfigurationUris UploadConfigurationDataToBlob()
{
//
// Get a reference to the container in blob storage
//
var storageAccount = new CloudStorageAccount(_storageCredentials, ArchiveStorageEndpointSuffix, true);
var blobClient = storageAccount.CreateCloudBlobClient();
var containerReference = blobClient.GetContainerReference(ArchiveContainerName);
//
// Get a reference to the configuration blob and create a SAS token to access it
//
var blobAccessPolicy = new SharedAccessBlobPolicy
{
SharedAccessExpiryTime =
DateTime.UtcNow.AddHours(1),
Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Delete
};
var configurationBlobName = ArchiveBlobName;
var configurationBlobReference = containerReference.GetBlockBlobReference(configurationBlobName);
var configurationBlobSasToken = configurationBlobReference.GetSharedAccessSignature(blobAccessPolicy);
//
// Upload the configuration data to blob storage and get a SAS token
//
string configurationDataBlobUri = null;
if (ConfigurationData != null)
{
var guid = Guid.NewGuid();
// there may be multiple VMs using the same configuration
var configurationDataBlobName = string.Format(
CultureInfo.InvariantCulture,
"{0}-{1}.psd1",
ConfigurationName,
guid);
var configurationDataBlobReference =
containerReference.GetBlockBlobReference(configurationDataBlobName);
ConfirmAction(
true,
string.Empty,
string.Format(
CultureInfo.CurrentUICulture,
Properties.Resources.AzureVMDscUploadToBlobStorageAction,
ConfigurationData),
configurationDataBlobReference.Uri.AbsoluteUri,
() =>
{
if (!Force && configurationDataBlobReference.Exists())
{
ThrowTerminatingError(
new ErrorRecord(
new UnauthorizedAccessException(
string.Format(
CultureInfo.CurrentUICulture,
Properties.Resources.AzureVMDscStorageBlobAlreadyExists,
configurationDataBlobName)),
"StorageBlobAlreadyExists",
ErrorCategory.PermissionDenied,
null));
}
configurationDataBlobReference.UploadFromFile(ConfigurationData, FileMode.Open);
var configurationDataBlobSasToken =
configurationDataBlobReference.GetSharedAccessSignature(blobAccessPolicy);
configurationDataBlobUri =
configurationDataBlobReference.StorageUri.PrimaryUri.AbsoluteUri
+ configurationDataBlobSasToken;
});
}
return new ConfigurationUris
{
ModulesUrl = configurationBlobReference.StorageUri.PrimaryUri.AbsoluteUri,
SasToken = configurationBlobSasToken,
DataBlobUri = configurationDataBlobUri
};
}
/// <summary>
/// Class represent info about uploaded Configuration.
/// </summary>
private class ConfigurationUris
{
public string SasToken { get; set; }
public string DataBlobUri { get; set; }
public string ModulesUrl { get; set; }
}
}
}
| |
namespace java.io
{
[global::MonoJavaBridge.JavaClass()]
public partial class RandomAccessFile : java.lang.Object, DataOutput, DataInput, Closeable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected RandomAccessFile(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public virtual long length()
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.io.RandomAccessFile.staticClass, "length", "()J", ref global::java.io.RandomAccessFile._m0);
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual void write(byte[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.RandomAccessFile.staticClass, "write", "([B)V", ref global::java.io.RandomAccessFile._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual void write(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.RandomAccessFile.staticClass, "write", "(I)V", ref global::java.io.RandomAccessFile._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m3;
public virtual void write(byte[] arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.RandomAccessFile.staticClass, "write", "([BII)V", ref global::java.io.RandomAccessFile._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual global::java.lang.String readLine()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.io.RandomAccessFile.staticClass, "readLine", "()Ljava/lang/String;", ref global::java.io.RandomAccessFile._m4) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual void close()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.RandomAccessFile.staticClass, "close", "()V", ref global::java.io.RandomAccessFile._m5);
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual void writeInt(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.RandomAccessFile.staticClass, "writeInt", "(I)V", ref global::java.io.RandomAccessFile._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual int readInt()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.io.RandomAccessFile.staticClass, "readInt", "()I", ref global::java.io.RandomAccessFile._m7);
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual void setLength(long arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.RandomAccessFile.staticClass, "setLength", "(J)V", ref global::java.io.RandomAccessFile._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual void writeChar(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.RandomAccessFile.staticClass, "writeChar", "(I)V", ref global::java.io.RandomAccessFile._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m10;
public virtual char readChar()
{
return global::MonoJavaBridge.JavaBridge.CallCharMethod(this, global::java.io.RandomAccessFile.staticClass, "readChar", "()C", ref global::java.io.RandomAccessFile._m10);
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual int read()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.io.RandomAccessFile.staticClass, "read", "()I", ref global::java.io.RandomAccessFile._m11);
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual int read(byte[] arg0, int arg1, int arg2)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.io.RandomAccessFile.staticClass, "read", "([BII)I", ref global::java.io.RandomAccessFile._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual int read(byte[] arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.io.RandomAccessFile.staticClass, "read", "([B)I", ref global::java.io.RandomAccessFile._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::java.io.FileDescriptor FD
{
get
{
return getFD();
}
}
private static global::MonoJavaBridge.MethodId _m14;
public virtual global::java.io.FileDescriptor getFD()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.io.FileDescriptor>(this, global::java.io.RandomAccessFile.staticClass, "getFD", "()Ljava/io/FileDescriptor;", ref global::java.io.RandomAccessFile._m14) as java.io.FileDescriptor;
}
public new global::java.nio.channels.FileChannel Channel
{
get
{
return getChannel();
}
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual global::java.nio.channels.FileChannel getChannel()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.io.RandomAccessFile.staticClass, "getChannel", "()Ljava/nio/channels/FileChannel;", ref global::java.io.RandomAccessFile._m15) as java.nio.channels.FileChannel;
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual void writeBytes(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.RandomAccessFile.staticClass, "writeBytes", "(Ljava/lang/String;)V", ref global::java.io.RandomAccessFile._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual void writeUTF(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.RandomAccessFile.staticClass, "writeUTF", "(Ljava/lang/String;)V", ref global::java.io.RandomAccessFile._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual global::java.lang.String readUTF()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.io.RandomAccessFile.staticClass, "readUTF", "()Ljava/lang/String;", ref global::java.io.RandomAccessFile._m18) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m19;
public virtual void readFully(byte[] arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.RandomAccessFile.staticClass, "readFully", "([BII)V", ref global::java.io.RandomAccessFile._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m20;
public virtual void readFully(byte[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.RandomAccessFile.staticClass, "readFully", "([B)V", ref global::java.io.RandomAccessFile._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m21;
public virtual long readLong()
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.io.RandomAccessFile.staticClass, "readLong", "()J", ref global::java.io.RandomAccessFile._m21);
}
private static global::MonoJavaBridge.MethodId _m22;
public virtual byte readByte()
{
return global::MonoJavaBridge.JavaBridge.CallByteMethod(this, global::java.io.RandomAccessFile.staticClass, "readByte", "()B", ref global::java.io.RandomAccessFile._m22);
}
private static global::MonoJavaBridge.MethodId _m23;
public virtual short readShort()
{
return global::MonoJavaBridge.JavaBridge.CallShortMethod(this, global::java.io.RandomAccessFile.staticClass, "readShort", "()S", ref global::java.io.RandomAccessFile._m23);
}
private static global::MonoJavaBridge.MethodId _m24;
public virtual void writeLong(long arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.RandomAccessFile.staticClass, "writeLong", "(J)V", ref global::java.io.RandomAccessFile._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m25;
public virtual void writeByte(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.RandomAccessFile.staticClass, "writeByte", "(I)V", ref global::java.io.RandomAccessFile._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m26;
public virtual void writeShort(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.RandomAccessFile.staticClass, "writeShort", "(I)V", ref global::java.io.RandomAccessFile._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m27;
public virtual void writeFloat(float arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.RandomAccessFile.staticClass, "writeFloat", "(F)V", ref global::java.io.RandomAccessFile._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m28;
public virtual float readFloat()
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::java.io.RandomAccessFile.staticClass, "readFloat", "()F", ref global::java.io.RandomAccessFile._m28);
}
private static global::MonoJavaBridge.MethodId _m29;
public virtual int skipBytes(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.io.RandomAccessFile.staticClass, "skipBytes", "(I)I", ref global::java.io.RandomAccessFile._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m30;
public virtual bool readBoolean()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.io.RandomAccessFile.staticClass, "readBoolean", "()Z", ref global::java.io.RandomAccessFile._m30);
}
private static global::MonoJavaBridge.MethodId _m31;
public virtual int readUnsignedByte()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.io.RandomAccessFile.staticClass, "readUnsignedByte", "()I", ref global::java.io.RandomAccessFile._m31);
}
private static global::MonoJavaBridge.MethodId _m32;
public virtual int readUnsignedShort()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.io.RandomAccessFile.staticClass, "readUnsignedShort", "()I", ref global::java.io.RandomAccessFile._m32);
}
private static global::MonoJavaBridge.MethodId _m33;
public virtual double readDouble()
{
return global::MonoJavaBridge.JavaBridge.CallDoubleMethod(this, global::java.io.RandomAccessFile.staticClass, "readDouble", "()D", ref global::java.io.RandomAccessFile._m33);
}
private static global::MonoJavaBridge.MethodId _m34;
public virtual void writeDouble(double arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.RandomAccessFile.staticClass, "writeDouble", "(D)V", ref global::java.io.RandomAccessFile._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m35;
public virtual void writeBoolean(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.RandomAccessFile.staticClass, "writeBoolean", "(Z)V", ref global::java.io.RandomAccessFile._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m36;
public virtual void writeChars(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.RandomAccessFile.staticClass, "writeChars", "(Ljava/lang/String;)V", ref global::java.io.RandomAccessFile._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new long FilePointer
{
get
{
return getFilePointer();
}
}
private static global::MonoJavaBridge.MethodId _m37;
public virtual long getFilePointer()
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.io.RandomAccessFile.staticClass, "getFilePointer", "()J", ref global::java.io.RandomAccessFile._m37);
}
private static global::MonoJavaBridge.MethodId _m38;
public virtual void seek(long arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.RandomAccessFile.staticClass, "seek", "(J)V", ref global::java.io.RandomAccessFile._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m39;
public RandomAccessFile(java.lang.String arg0, java.lang.String arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.io.RandomAccessFile._m39.native == global::System.IntPtr.Zero)
global::java.io.RandomAccessFile._m39 = @__env.GetMethodIDNoThrow(global::java.io.RandomAccessFile.staticClass, "<init>", "(Ljava/lang/String;Ljava/lang/String;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.io.RandomAccessFile.staticClass, global::java.io.RandomAccessFile._m39, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m40;
public RandomAccessFile(java.io.File arg0, java.lang.String arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.io.RandomAccessFile._m40.native == global::System.IntPtr.Zero)
global::java.io.RandomAccessFile._m40 = @__env.GetMethodIDNoThrow(global::java.io.RandomAccessFile.staticClass, "<init>", "(Ljava/io/File;Ljava/lang/String;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.io.RandomAccessFile.staticClass, global::java.io.RandomAccessFile._m40, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
static RandomAccessFile()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.io.RandomAccessFile.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/io/RandomAccessFile"));
}
}
}
| |
using System;
using System.IO;
using Ionic.Zip;
using Sitecore.Diagnostics.Base;
using Sitecore.Diagnostics.Base.Annotations;
namespace SIM.FileSystem
{
public class UncZipProvider : ZipProvider
{
#region Fields
[NotNull]
private readonly FileSystem fileSystem;
#endregion
#region Constructors
public UncZipProvider([NotNull] FileSystem fileSystem) : base(fileSystem)
{
Assert.ArgumentNotNull(fileSystem, nameof(fileSystem));
this.fileSystem = fileSystem;
}
#endregion
#region Public methods
public override void CheckZip(string path)
{
try
{
base.CheckZip(path);
}
catch (ZipException ex)
{
if (!(ex.InnerException is PathTooLongException))
{
throw;
}
using (var temp = FileSystem.Local.Directory.GetTempFolder(path))
{
var shortPath = Path.Combine(temp.Path, Path.GetFileName(path));
this.fileSystem.File.Copy(path, shortPath);
base.CheckZip(shortPath);
}
}
}
public override void CreateZip(string path, string zipFileName, string ignore = null, int compressionLevel = 0)
{
try
{
base.CreateZip(path, zipFileName, ignore);
}
catch (ZipException ex)
{
if (!(ex.InnerException is PathTooLongException))
{
throw;
}
using (var tempPath = FileSystem.Local.Directory.GetTempFolder(path))
{
using (var tempZip = FileSystem.Local.Directory.GetTempFolder(zipFileName))
{
var shortPath = Path.Combine(tempPath.Path, Path.GetFileName(path));
this.fileSystem.Directory.Copy(path, shortPath, true);
var shortZipPath = Path.Combine(tempZip.Path, Path.GetFileName(zipFileName));
base.CreateZip(shortPath, shortZipPath, ignore);
this.fileSystem.File.Copy(shortZipPath, zipFileName);
}
}
}
}
public override string GetFirstRootFolder(string path)
{
try
{
return base.GetFirstRootFolder(path);
}
catch (ZipException ex)
{
if (!(ex.InnerException is PathTooLongException))
{
throw;
}
using (var temp = FileSystem.Local.Directory.GetTempFolder(path))
{
var shortPath = Path.Combine(temp.Path, Path.GetFileName(path));
this.fileSystem.File.Copy(path, shortPath);
return base.GetFirstRootFolder(shortPath);
}
}
}
public override void UnpackZip(string packagePath, string path, string entriesPattern = null, int stepsCount = 1, Action incrementProgress = null, bool skipErrors = false)
{
try
{
base.UnpackZip(packagePath, path, entriesPattern, stepsCount, incrementProgress, skipErrors);
}
catch (ZipException ex)
{
if (!(ex.InnerException is PathTooLongException))
{
throw;
}
using (var tempPath = FileSystem.Local.Directory.GetTempFolder(path))
{
using (var tempPkg = FileSystem.Local.Directory.GetTempFolder(packagePath))
{
var shortPath = Path.Combine(tempPath.Path, Path.GetFileName(path));
var shortPkgPath = Path.Combine(tempPkg.Path, Path.GetFileName(packagePath));
this.fileSystem.File.Copy(packagePath, shortPkgPath);
base.UnpackZip(shortPkgPath, shortPath, entriesPattern, stepsCount, incrementProgress, skipErrors);
this.fileSystem.Directory.Copy(shortPath, path, true);
}
}
}
}
public override void UnpackZipWithActualWebRootName(string packagePath, string path, string webRootName, string entriesPattern = null, int stepsCount = 1, Action incrementProgress = null)
{
try
{
base.UnpackZipWithActualWebRootName(packagePath, path, webRootName, entriesPattern, stepsCount, incrementProgress);
}
catch (ZipException ex)
{
if (!(ex.InnerException is PathTooLongException))
{
throw;
}
throw new NotImplementedException("Not implemented yet");
}
}
public override bool ZipContainsFile(string path, string innerFileName)
{
try
{
return base.ZipContainsFile(path, innerFileName);
}
catch (ZipException ex)
{
if (!(ex.InnerException is PathTooLongException))
{
throw;
}
using (var temp = FileSystem.Local.Directory.GetTempFolder(path))
{
var shortPath = Path.Combine(temp.Path, Path.GetFileName(path));
this.fileSystem.File.Copy(path, shortPath);
return base.ZipContainsFile(shortPath, innerFileName);
}
}
}
public override bool ZipContainsSingleFile(string path, string innerFileName)
{
try
{
return base.ZipContainsSingleFile(path, innerFileName);
}
catch (ZipException ex)
{
if (!(ex.InnerException is PathTooLongException))
{
throw;
}
using (var temp = FileSystem.Local.Directory.GetTempFolder(path))
{
var shortPath = Path.Combine(temp.Path, Path.GetFileName(path));
this.fileSystem.File.Copy(path, shortPath);
return base.ZipContainsSingleFile(path, innerFileName);
}
}
}
public override string ZipUnpackFile(string pathToZip, string pathToUnpack, string fileName)
{
try
{
return base.ZipUnpackFile(pathToZip, pathToUnpack, fileName);
}
catch (ZipException ex)
{
if (!(ex.InnerException is PathTooLongException))
{
throw;
}
using (var tempPath = FileSystem.Local.Directory.GetTempFolder(pathToUnpack))
{
using (var tempPkg = FileSystem.Local.Directory.GetTempFolder(pathToZip))
{
var shortPath = Path.Combine(tempPath.Path, Path.GetFileName(pathToUnpack));
var shortPkgPath = Path.Combine(tempPkg.Path, Path.GetFileName(pathToZip));
this.fileSystem.File.Copy(pathToZip, shortPkgPath);
var result = base.ZipUnpackFile(shortPkgPath, shortPath, fileName);
var destFileName = Path.Combine(pathToUnpack, fileName);
this.fileSystem.File.Move(result, destFileName);
return destFileName;
}
}
}
}
public override string ZipUnpackFolder(string pathToZip, string pathToUnpack, string folderName)
{
try
{
return base.ZipUnpackFolder(pathToZip, pathToUnpack, folderName);
}
catch (ZipException ex)
{
if (!(ex.InnerException is PathTooLongException))
{
throw;
}
using (var tempPath = FileSystem.Local.Directory.GetTempFolder(pathToUnpack))
{
using (var tempPkg = FileSystem.Local.Directory.GetTempFolder(pathToZip))
{
var shortPath = Path.Combine(tempPath.Path, Path.GetFileName(pathToUnpack));
var shortPkgPath = Path.Combine(tempPkg.Path, Path.GetFileName(pathToZip));
this.fileSystem.File.Copy(pathToZip, shortPkgPath);
var result = base.ZipUnpackFolder(shortPkgPath, shortPath, folderName);
var destFileName = Path.Combine(pathToUnpack, folderName);
this.fileSystem.Directory.Move(result, destFileName);
return destFileName;
}
}
}
}
#endregion
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Configuration.Install;
using System.Reflection;
using Microsoft.Win32;
using System.IO;
using System.Text;
using System.Threading;
using System.Globalization;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
/// <summary>
///
/// PSInstaller is a class for facilitating installation
/// of monad engine and monad PSSnapin's.
///
/// This class implements installer api from CLR. At install
/// time, installation utilities (like InstallUtil.exe) will
/// call api implementation functions in this class automatically.
/// This includes functions like Install, Uninstall, Rollback
/// and Commit.
///
/// This class is an abstract class for handling installation needs
/// that are common for all monad components, which include,
///
/// 1. accessing system registry
/// 2. support of additional command line parameters.
/// 3. writing registry files
/// 4. automatically extract information like vender, version, etc.
///
/// Different monad component will derive from this class. Two common
/// components that need install include,
///
/// 1. PSSnapin. Installation of PSSnapin will require information
/// about PSSnapin assembly, version, vendor, etc to be
/// written to registry.
///
/// 2. Engine. Installation of monad engine will require information
/// about engine assembly, version, CLR information to be
/// written to registry.
///
/// </summary>
///
/// <remarks>
/// This is an abstract class to be derived by monad engine and PSSnapin installers
/// only. Developer should not directly derive from this class.
/// </remarks>
public abstract class PSInstaller : Installer
{
private static string[] MshRegistryRoots
{
get
{
// For 3.0 PowerShell, we use "3" as the registry version key only for Engine
// related data like ApplicationBase.
// For 3.0 PowerShell, we still use "1" as the registry version key for
// Snapin and Custom shell lookup/discovery.
return new string[] {
"HKEY_LOCAL_MACHINE\\Software\\Microsoft\\PowerShell\\" + PSVersionInfo.RegistryVersion1Key + "\\"
};
}
}
/// <summary>
///
/// </summary>
internal abstract string RegKey
{
get;
}
/// <summary>
///
/// </summary>
internal abstract Dictionary<String, object> RegValues
{
get;
}
/// <summary>
///
/// </summary>
/// <param name="stateSaver"></param>
public sealed override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
WriteRegistry();
return;
}
private void WriteRegistry()
{
foreach (string root in MshRegistryRoots)
{
RegistryKey key = GetRegistryKey(root + RegKey);
foreach (var pair in RegValues)
{
key.SetValue(pair.Key, pair.Value);
}
}
}
private RegistryKey GetRegistryKey(string keyPath)
{
RegistryKey root = GetRootHive(keyPath);
if (root == null)
return null;
return root.CreateSubKey(GetSubkeyPath(keyPath));
}
private static string GetSubkeyPath(string keyPath)
{
int index = keyPath.IndexOf('\\');
if (index > 0)
{
return keyPath.Substring(index + 1);
}
return null;
}
private static RegistryKey GetRootHive(string keyPath)
{
string root;
int index = keyPath.IndexOf('\\');
if (index > 0)
{
root = keyPath.Substring(0, index);
}
else
{
root = keyPath;
}
switch (root.ToUpperInvariant())
{
case "HKEY_CURRENT_USER":
return Registry.CurrentUser;
case "HKEY_LOCAL_MACHINE":
return Registry.LocalMachine;
case "HKEY_CLASSES_ROOT":
return Registry.ClassesRoot;
case "HKEY_CURRENT_CONFIG":
return Registry.CurrentConfig;
case "HKEY_PERFORMANCE_DATA":
return Registry.PerformanceData;
case "HKEY_USERS":
return Registry.Users;
}
return null;
}
/// <summary>
/// Uninstall this msh component
/// </summary>
/// <param name="savedState"></param>
public sealed override void Uninstall(IDictionary savedState)
{
base.Uninstall(savedState);
if (this.Context != null && this.Context.Parameters != null && this.Context.Parameters.ContainsKey("RegFile"))
{
string regFile = this.Context.Parameters["RegFile"];
// If regfile is specified. Don't uninstall.
if (!String.IsNullOrEmpty(regFile))
return;
}
string keyName;
string parentKey;
int index = RegKey.LastIndexOf('\\');
if (index >= 0)
{
parentKey = RegKey.Substring(0, index);
keyName = RegKey.Substring(index + 1);
}
else
{
parentKey = "";
keyName = RegKey;
}
foreach (string root in MshRegistryRoots)
{
RegistryKey key = GetRegistryKey(root + parentKey);
key.DeleteSubKey(keyName);
}
return;
}
/// <summary>
/// Rollback this msh component
/// </summary>
/// <param name="savedState"></param>
public sealed override void Rollback(IDictionary savedState)
{
Uninstall(savedState);
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace Revit.SDK.Samples.ShaftHolePuncher.CS
{
/// <summary>
/// ProfileBeam class contains the information about profile of beam,
/// and contains method used to create opening on a beam.
/// </summary>
public class ProfileBeam : Profile
{
private FamilyInstance m_data = null; //beam
//store the transform used to change points in beam coordinate system to Revit coordinate system
Transform m_beamTransform = null;
bool m_isZaxis = true; //decide whether to create opening on Zaxis of beam or Yaixs of beam
//if m_haveOpening is true means beam has already had opening on it
//then the points get from get_Geometry(Option) do not need to be transformed
//by the Transform get from Instance object anymore.
bool m_haveOpening = false;
Matrix4 m_MatrixZaxis = null; //transform points to plane whose normal is Zaxis of beam
Matrix4 m_MatrixYaxis = null; //transform points to plane whose normal is Yaxis of beam
/// <summary>
/// constructor
/// </summary>
/// <param name="beam">beam to create opening on</param>
/// <param name="commandData">object which contains reference to Revit Application</param>
public ProfileBeam(FamilyInstance beam, ExternalCommandData commandData)
: base(commandData)
{
m_data = beam;
List<List<Edge>> faces = GetFaces(m_data);
m_points = GetNeedPoints(faces);
m_to2DMatrix = GetTo2DMatrix();
m_moveToCenterMatrix = ToCenterMatrix();
}
/// <summary>
/// Get points of the first face
/// </summary>
/// <param name="faces">edges in all faces</param>
/// <returns>points of first face</returns>
public override List<List<XYZ>> GetNeedPoints(List<List<Edge>> faces)
{
List<List<XYZ>> needPoints = new List<List<XYZ>>();
for (int i = 0; i < faces.Count; i++)
{
foreach (Edge edge in faces[i])
{
List<XYZ> edgexyzs = edge.Tessellate() as List<XYZ>;
if (false == m_haveOpening)
{
List<XYZ> transformedPoints = new List<XYZ>();
for (int j = 0; j < edgexyzs.Count; j++)
{
Autodesk.Revit.DB.XYZ xyz = edgexyzs[j];
Autodesk.Revit.DB.XYZ transformedXYZ = m_beamTransform.OfPoint(xyz);
transformedPoints.Add(transformedXYZ);
}
edgexyzs = transformedPoints;
}
needPoints.Add(edgexyzs);
}
}
return needPoints;
}
/// <summary>
/// Get the bound of a face
/// </summary>
/// <returns>points array stores the bound of the face</returns>
public override PointF[] GetFaceBounds()
{
Matrix4 matrix = m_to2DMatrix;
Matrix4 inverseMatrix = matrix.Inverse();
float minX = 0, maxX = 0, minY = 0, maxY = 0;
bool bFirstPoint = true;
//get the max and min point on the face
for (int i = 0; i < m_points.Count; i++)
{
List<XYZ> points = m_points[i];
foreach (Autodesk.Revit.DB.XYZ point in points)
{
Vector4 v = new Vector4(point);
Vector4 v1 = inverseMatrix.Transform(v);
if (bFirstPoint)
{
minX = maxX = v1.X;
minY = maxY = v1.Y;
bFirstPoint = false;
}
else
{
if (v1.X < minX)
{
minX = v1.X;
}
else if (v1.X > maxX)
{
maxX = v1.X;
}
if (v1.Y < minY)
{
minY = v1.Y;
}
else if (v1.Y > maxY)
{
maxY = v1.Y;
}
}
}
}
//return an array with max and min value of face
PointF[] resultPoints = new PointF[2] {
new PointF(minX, minY), new PointF(maxX, maxY) };
return resultPoints;
}
/// <summary>
/// Get a matrix which can transform points to 2D
/// </summary>
/// <returns>matrix which can transform points to 2D</returns>
public override Matrix4 GetTo2DMatrix()
{
//get transform used to transform points to plane whose normal is Zaxis of beam
Vector4 xAxis = new Vector4(m_data.HandOrientation);
xAxis.Normalize();
//Because Y axis in windows UI is downward, so we should Multiply(-1) here
Vector4 yAxis = new Vector4(m_data.FacingOrientation.Multiply(-1));
yAxis.Normalize();
Vector4 zAxis = yAxis.CrossProduct(xAxis);
zAxis.Normalize();
Vector4 vOrigin = new Vector4(m_points[0][0]);
Matrix4 result = new Matrix4(xAxis, yAxis, zAxis, vOrigin);
m_MatrixZaxis = result;
//get transform used to transform points to plane whose normal is Yaxis of beam
xAxis = new Vector4(m_data.HandOrientation);
xAxis.Normalize();
zAxis = new Vector4(m_data.FacingOrientation);
zAxis.Normalize();
yAxis = (xAxis.CrossProduct(zAxis)) * (-1);
yAxis.Normalize();
result = new Matrix4(xAxis, yAxis, zAxis, vOrigin);
m_MatrixYaxis = result;
return m_MatrixZaxis;
}
/// <summary>
/// Get edges of element's profile
/// </summary>
/// <param name="elem">selected element</param>
/// <returns>all the faces in the selected Element</returns>
public override List<List<Edge>> GetFaces(Autodesk.Revit.DB.Element elem)
{
List<List<Edge>> faceEdges = new List<List<Edge>>();
Options options = m_appCreator.NewGeometryOptions();
options.DetailLevel = DetailLevels.Medium;
//make sure references to geometric objects are computed.
options.ComputeReferences = true;
Autodesk.Revit.DB.GeometryElement geoElem = elem.get_Geometry(options);
GeometryObjectArray gObjects = geoElem.Objects;
//get all the edges in the Geometry object
foreach (GeometryObject geo in gObjects)
{
//if beam doesn't contain opening on it, then we can get edges from instance
//and the points we get should be transformed by instance.Tranceform
if (geo is Autodesk.Revit.DB.GeometryInstance)
{
Autodesk.Revit.DB.GeometryInstance instance = geo as Autodesk.Revit.DB.GeometryInstance;
m_beamTransform = instance.Transform;
Autodesk.Revit.DB.GeometryElement elemGeo = instance.SymbolGeometry;
GeometryObjectArray objectsGeo = elemGeo.Objects;
foreach (GeometryObject objGeo in objectsGeo)
{
Solid solid = objGeo as Solid;
if (null != solid)
{
FaceArray faces = solid.Faces;
foreach (Face face in faces)
{
EdgeArrayArray edgeArrarr = face.EdgeLoops;
foreach (EdgeArray edgeArr in edgeArrarr)
{
List<Edge> edgesList = new List<Edge>();
foreach (Edge edge in edgeArr)
{
edgesList.Add(edge);
}
faceEdges.Add(edgesList);
}
}
}
}
}
//if beam contains opening on it, then we can get edges from solid
//and the points we get do not need transform anymore
else if (geo is Autodesk.Revit.DB.Solid)
{
m_haveOpening = true;
Solid solid = geo as Solid;
FaceArray faces = solid.Faces;
foreach (Face face in faces)
{
EdgeArrayArray edgeArrarr = face.EdgeLoops;
foreach (EdgeArray edgeArr in edgeArrarr)
{
List<Edge> edgesList = new List<Edge>();
foreach (Edge edge in edgeArr)
{
edgesList.Add(edge);
}
faceEdges.Add(edgesList);
}
}
}
}
return faceEdges;
}
/// <summary>
/// Create Opening on beam
/// </summary>
/// <param name="points">points used to create Opening</param>
/// <returns>newly created Opening</returns>
public override Opening CreateOpening(List<Vector4> points)
{
Autodesk.Revit.DB.XYZ p1, p2; Line curve;
CurveArray curves = m_appCreator.NewCurveArray();
for (int i = 0; i < points.Count - 1; i++)
{
p1 = new Autodesk.Revit.DB.XYZ (points[i].X, points[i].Y, points[i].Z);
p2 = new Autodesk.Revit.DB.XYZ (points[i + 1].X, points[i + 1].Y, points[i + 1].Z);
curve = m_appCreator.NewLine(p1, p2, true);
curves.Append(curve);
}
//close the curve
p1 = new Autodesk.Revit.DB.XYZ (points[0].X, points[0].Y, points[0].Z);
p2 = new Autodesk.Revit.DB.XYZ (points[points.Count - 1].X, points[points.Count - 1].Y, points[points.Count - 1].Z);
curve = m_appCreator.NewLine(p1, p2, true);
curves.Append(curve);
if (false == m_isZaxis)
{
return m_docCreator.NewOpening(m_data, curves, Autodesk.Revit.Creation.eRefFace.CenterY);
}
else
{
return m_docCreator.NewOpening(m_data, curves, Autodesk.Revit.Creation.eRefFace.CenterZ);
}
}
/// <summary>
/// Change transform matrix used to transform points to 2d.
/// </summary>
/// <param name="isZaxis">transform points to which plane.
/// true means transform points to plane whose normal is Zaxis of beam.
/// false means transform points to plane whose normal is Yaxis of beam
/// </param>
public void ChangeTransformMatrix(bool isZaxis)
{
m_isZaxis = isZaxis;
if (isZaxis)
{
m_to2DMatrix = m_MatrixZaxis;
}
else
{
m_to2DMatrix = m_MatrixYaxis;
}
//re-calculate matrix used to move points to center
m_moveToCenterMatrix = ToCenterMatrix();
}
}
}
| |
/*
* Copyright 2013 Monoscape
*
* 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.
*
* History:
* 2011/11/10 Imesh Gunaratne <imesh@monoscape.org> Created.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using Monoscape.Common.Model;
using System.Runtime.Serialization.Formatters.Binary;
using Monoscape.Common.Exceptions;
namespace Monoscape.Common.Sockets.FileServer
{
/// <summary>
/// Implement this class in the context of the end point.
/// </summary>
public abstract class AbstractFileReceiveSocket
{
private Socket serverSocket;
private IPAddress ipAddress;
private int port;
private string fileStorePath;
private bool socketOpen = false;
private Thread thread;
private Socket clientSocket;
protected abstract string SocketName { get; }
public AbstractFileReceiveSocket(string fileStorePath, IPAddress ipAddress, int port)
{
if (fileStorePath.Last() != Path.DirectorySeparatorChar)
this.fileStorePath = fileStorePath + Path.DirectorySeparatorChar;
else
this.fileStorePath = fileStorePath;
this.ipAddress = ipAddress;
this.port = port;
}
public void Open()
{
Log.Debug(this, "Starting " + SocketName + " thread...");
thread = new Thread(new ThreadStart(OpenSocket));
thread.Start();
Log.Debug(this, SocketName + " started");
}
private void OpenSocket()
{
socketOpen = true;
ReceiveFile();
}
public void Close()
{
socketOpen = false;
CloseSockets();
thread.Abort();
}
private void ReceiveFile()
{
try
{
IPEndPoint ipEnd = new IPEndPoint(ipAddress, port);
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
serverSocket.Bind(ipEnd);
serverSocket.Listen(100);
while (socketOpen)
{
// Wait for the next connection
clientSocket = serverSocket.Accept();
// Read File Header
// FileHeader: [fileNameInBytesLength (4bytes) | fileNameInBytes | fileSizeInBytesLength (8bytes) | fileSizeInBytes]
byte[] fileNameInBytesLengthInBytes = new byte[4];
Log.Debug(this, "Reading file name length in bytes");
int bytesRead = clientSocket.Receive(fileNameInBytesLengthInBytes, 4, SocketFlags.None);
if (bytesRead == 4)
{
int fileNameInBytesLength = BitConverter.ToInt32(fileNameInBytesLengthInBytes, 0);
Log.Debug(this, "File name length in bytes: " + fileNameInBytesLength);
Log.Debug(this, "Reading file name");
byte[] fileNameInBytes = new byte[fileNameInBytesLength];
bytesRead = clientSocket.Receive(fileNameInBytes, fileNameInBytesLength, 0);
if (bytesRead == fileNameInBytesLength)
{
string fileName = Encoding.ASCII.GetString(fileNameInBytes);
Log.Debug(this, "File name: " + fileName);
Log.Debug(this, "Reading file size length in bytes");
byte[] fileSizeInBytesLengthInBytes = new byte[8];
bytesRead = clientSocket.Receive(fileSizeInBytesLengthInBytes, 8, SocketFlags.None);
if (bytesRead == 8)
{
int fileSizeInBytesLength = BitConverter.ToInt32(fileSizeInBytesLengthInBytes, 0);
Log.Debug(this, "File size length in bytes: " + fileSizeInBytesLength);
Log.Debug(this, "Reading file size length");
byte[] fileSizeInBytes = new byte[fileSizeInBytesLength];
bytesRead = clientSocket.Receive(fileSizeInBytes, 8, SocketFlags.None);
if (bytesRead == 8)
{
long fileSize = BitConverter.ToInt32(fileSizeInBytes, 0);
Log.Debug(this, "File size: " + fileSize);
if (!Directory.Exists(fileStorePath))
Directory.CreateDirectory(fileStorePath);
string filePath = Path.Combine(fileStorePath, fileName);
// Read File Content
long buffer = 65536; // Block size = 64K
byte[] fileData = new byte[fileSize];
using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
bytesRead = 0;
long totalBytesRead = 0;
long bytesToRead = buffer;
Log.Debug(this, "Reading file content... ");
while (bytesToRead > 0)
{
bytesRead = clientSocket.Receive(fileData, (int)totalBytesRead, (int)buffer, SocketFlags.None);
if (bytesRead == 0)
break;
fileStream.Write(fileData, (int)totalBytesRead, (int)bytesRead);
totalBytesRead = totalBytesRead + bytesRead;
bytesToRead = fileSize - totalBytesRead;
if (bytesToRead < buffer)
buffer = bytesToRead;
Log.Debug(this, "Received bytes: " + (fileSize - bytesToRead));
}
}
Log.Debug(this, "File " + fileName + " written to application store");
}
else
{
throw new MonoscapeException("File header is not valid, could not receive file.");
}
}
else
{
throw new MonoscapeException("File header is not valid, could not receive file.");
}
}
else
{
throw new MonoscapeException("File header is not valid, could not receive file.");
}
}
else
{
throw new MonoscapeException("File header is not valid, could not receive file.");
}
}
}
catch (Exception e)
{
if(socketOpen)
{
Log.Error(this, "File receiving failed", e);
if(serverSocket.Connected)
throw e;
}
}
finally
{
CloseSockets();
}
}
private void CloseSockets()
{
socketOpen = false;
if (serverSocket != null)
serverSocket.Close();
if (clientSocket != null)
clientSocket.Close();
}
private static object DeSerialize_(byte[] dataBuffer)
{
using (MemoryStream stream = new MemoryStream(dataBuffer))
{
stream.Position = 0;
var formatter = new BinaryFormatter();
return formatter.Deserialize(stream);
}
}
private Object DeSerialize(byte[] dataBuffer)
{
BinaryFormatter bin = new BinaryFormatter();
MemoryStream mem = new MemoryStream();
mem.Write(dataBuffer, 0, dataBuffer.Length);
mem.Seek(0, SeekOrigin.Begin);
return bin.Deserialize(mem);
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System;
using System.Collections;
using System.Diagnostics;
namespace IdentityServer4.Models
{
/// <summary>
/// Models an OpenID Connect or OAuth2 client
/// </summary>
[DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")]
public class Client
{
// setting grant types should be atomic
private ICollection<string> _allowedGrantTypes = new GrantTypeValidatingHashSet();
private string DebuggerDisplay => ClientId ?? $"{{{typeof(Client)}}}";
/// <summary>
/// Specifies if client is enabled (defaults to <c>true</c>)
/// </summary>
public bool Enabled { get; set; } = true;
/// <summary>
/// Unique ID of the client
/// </summary>
public string ClientId { get; set; }
/// <summary>
/// Gets or sets the protocol type.
/// </summary>
/// <value>
/// The protocol type.
/// </value>
public string ProtocolType { get; set; } = IdentityServerConstants.ProtocolTypes.OpenIdConnect;
/// <summary>
/// Client secrets - only relevant for flows that require a secret
/// </summary>
public ICollection<Secret> ClientSecrets { get; set; } = new HashSet<Secret>();
/// <summary>
/// If set to false, no client secret is needed to request tokens at the token endpoint (defaults to <c>true</c>)
/// </summary>
public bool RequireClientSecret { get; set; } = true;
/// <summary>
/// Client display name (used for logging and consent screen)
/// </summary>
public string ClientName { get; set; }
/// <summary>
/// Description of the client.
/// </summary>
public string Description { get; set; }
/// <summary>
/// URI to further information about client (used on consent screen)
/// </summary>
public string ClientUri { get; set; }
/// <summary>
/// URI to client logo (used on consent screen)
/// </summary>
public string LogoUri { get; set; }
/// <summary>
/// Specifies whether a consent screen is required (defaults to <c>false</c>)
/// </summary>
public bool RequireConsent { get; set; } = false;
/// <summary>
/// Specifies whether user can choose to store consent decisions (defaults to <c>true</c>)
/// </summary>
public bool AllowRememberConsent { get; set; } = true;
/// <summary>
/// Specifies the allowed grant types (legal combinations of AuthorizationCode, Implicit, Hybrid, ResourceOwner, ClientCredentials).
/// </summary>
public ICollection<string> AllowedGrantTypes
{
get { return _allowedGrantTypes; }
set
{
ValidateGrantTypes(value);
_allowedGrantTypes = new GrantTypeValidatingHashSet(value);
}
}
/// <summary>
/// Specifies whether a proof key is required for authorization code based token requests (defaults to <c>true</c>).
/// </summary>
public bool RequirePkce { get; set; } = true;
/// <summary>
/// Specifies whether a proof key can be sent using plain method (not recommended and defaults to <c>false</c>.)
/// </summary>
public bool AllowPlainTextPkce { get; set; } = false;
/// <summary>
/// Specifies whether the client must use a request object on authorize requests (defaults to <c>false</c>.)
/// </summary>
public bool RequireRequestObject { get; set; } = false;
/// <summary>
/// Controls whether access tokens are transmitted via the browser for this client (defaults to <c>false</c>).
/// This can prevent accidental leakage of access tokens when multiple response types are allowed.
/// </summary>
/// <value>
/// <c>true</c> if access tokens can be transmitted via the browser; otherwise, <c>false</c>.
/// </value>
public bool AllowAccessTokensViaBrowser { get; set; } = false;
/// <summary>
/// Specifies allowed URIs to return tokens or authorization codes to
/// </summary>
public ICollection<string> RedirectUris { get; set; } = new HashSet<string>();
/// <summary>
/// Specifies allowed URIs to redirect to after logout
/// </summary>
public ICollection<string> PostLogoutRedirectUris { get; set; } = new HashSet<string>();
/// <summary>
/// Specifies logout URI at client for HTTP front-channel based logout.
/// </summary>
public string FrontChannelLogoutUri { get; set; }
/// <summary>
/// Specifies if the user's session id should be sent to the FrontChannelLogoutUri. Defaults to <c>true</c>.
/// </summary>
public bool FrontChannelLogoutSessionRequired { get; set; } = true;
/// <summary>
/// Specifies logout URI at client for HTTP back-channel based logout.
/// </summary>
public string BackChannelLogoutUri { get; set; }
/// <summary>
/// Specifies if the user's session id should be sent to the BackChannelLogoutUri. Defaults to <c>true</c>.
/// </summary>
public bool BackChannelLogoutSessionRequired { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether [allow offline access]. Defaults to <c>false</c>.
/// </summary>
public bool AllowOfflineAccess { get; set; } = false;
/// <summary>
/// Specifies the api scopes that the client is allowed to request. If empty, the client can't access any scope
/// </summary>
public ICollection<string> AllowedScopes { get; set; } = new HashSet<string>();
/// <summary>
/// When requesting both an id token and access token, should the user claims always be added to the id token instead of requiring the client to use the userinfo endpoint.
/// Defaults to <c>false</c>.
/// </summary>
public bool AlwaysIncludeUserClaimsInIdToken { get; set; } = false;
/// <summary>
/// Lifetime of identity token in seconds (defaults to 300 seconds / 5 minutes)
/// </summary>
public int IdentityTokenLifetime { get; set; } = 300;
/// <summary>
/// Signing algorithm for identity token. If empty, will use the server default signing algorithm.
/// </summary>
public ICollection<string> AllowedIdentityTokenSigningAlgorithms { get; set; } = new HashSet<string>();
/// <summary>
/// Lifetime of access token in seconds (defaults to 3600 seconds / 1 hour)
/// </summary>
public int AccessTokenLifetime { get; set; } = 3600;
/// <summary>
/// Lifetime of authorization code in seconds (defaults to 300 seconds / 5 minutes)
/// </summary>
public int AuthorizationCodeLifetime { get; set; } = 300;
/// <summary>
/// Maximum lifetime of a refresh token in seconds. Defaults to 2592000 seconds / 30 days
/// </summary>
public int AbsoluteRefreshTokenLifetime { get; set; } = 2592000;
/// <summary>
/// Sliding lifetime of a refresh token in seconds. Defaults to 1296000 seconds / 15 days
/// </summary>
public int SlidingRefreshTokenLifetime { get; set; } = 1296000;
/// <summary>
/// Lifetime of a user consent in seconds. Defaults to null (no expiration)
/// </summary>
public int? ConsentLifetime { get; set; } = null;
/// <summary>
/// ReUse: the refresh token handle will stay the same when refreshing tokens
/// OneTime: the refresh token handle will be updated when refreshing tokens
/// </summary>
public TokenUsage RefreshTokenUsage { get; set; } = TokenUsage.OneTimeOnly;
/// <summary>
/// Gets or sets a value indicating whether the access token (and its claims) should be updated on a refresh token request.
/// Defaults to <c>false</c>.
/// </summary>
/// <value>
/// <c>true</c> if the token should be updated; otherwise, <c>false</c>.
/// </value>
public bool UpdateAccessTokenClaimsOnRefresh { get; set; } = false;
/// <summary>
/// Absolute: the refresh token will expire on a fixed point in time (specified by the AbsoluteRefreshTokenLifetime)
/// Sliding: when refreshing the token, the lifetime of the refresh token will be renewed (by the amount specified in SlidingRefreshTokenLifetime). The lifetime will not exceed AbsoluteRefreshTokenLifetime.
/// </summary>
public TokenExpiration RefreshTokenExpiration { get; set; } = TokenExpiration.Absolute;
/// <summary>
/// Specifies whether the access token is a reference token or a self contained JWT token (defaults to Jwt).
/// </summary>
public AccessTokenType AccessTokenType { get; set; } = AccessTokenType.Jwt;
/// <summary>
/// Gets or sets a value indicating whether the local login is allowed for this client. Defaults to <c>true</c>.
/// </summary>
/// <value>
/// <c>true</c> if local logins are enabled; otherwise, <c>false</c>.
/// </value>
public bool EnableLocalLogin { get; set; } = true;
/// <summary>
/// Specifies which external IdPs can be used with this client (if list is empty all IdPs are allowed). Defaults to empty.
/// </summary>
public ICollection<string> IdentityProviderRestrictions { get; set; } = new HashSet<string>();
/// <summary>
/// Gets or sets a value indicating whether JWT access tokens should include an identifier. Defaults to <c>true</c>.
/// </summary>
/// <value>
/// <c>true</c> to add an id; otherwise, <c>false</c>.
/// </value>
public bool IncludeJwtId { get; set; } = true;
/// <summary>
/// Allows settings claims for the client (will be included in the access token).
/// </summary>
/// <value>
/// The claims.
/// </value>
public ICollection<ClientClaim> Claims { get; set; } = new HashSet<ClientClaim>();
/// <summary>
/// Gets or sets a value indicating whether client claims should be always included in the access tokens - or only for client credentials flow.
/// Defaults to <c>false</c>
/// </summary>
/// <value>
/// <c>true</c> if claims should always be sent; otherwise, <c>false</c>.
/// </value>
public bool AlwaysSendClientClaims { get; set; } = false;
/// <summary>
/// Gets or sets a value to prefix it on client claim types. Defaults to <c>client_</c>.
/// </summary>
/// <value>
/// Any non empty string if claims should be prefixed with the value; otherwise, <c>null</c>.
/// </value>
public string ClientClaimsPrefix { get; set; } = "client_";
/// <summary>
/// Gets or sets a salt value used in pair-wise subjectId generation for users of this client.
/// </summary>
public string PairWiseSubjectSalt { get; set; }
/// <summary>
/// The maximum duration (in seconds) since the last time the user authenticated.
/// </summary>
public int? UserSsoLifetime { get; set; }
/// <summary>
/// Gets or sets the type of the device flow user code.
/// </summary>
/// <value>
/// The type of the device flow user code.
/// </value>
public string UserCodeType { get; set; }
/// <summary>
/// Gets or sets the device code lifetime.
/// </summary>
/// <value>
/// The device code lifetime.
/// </value>
public int DeviceCodeLifetime { get; set; } = 300;
/// <summary>
/// Gets or sets the allowed CORS origins for JavaScript clients.
/// </summary>
/// <value>
/// The allowed CORS origins.
/// </value>
public ICollection<string> AllowedCorsOrigins { get; set; } = new HashSet<string>();
/// <summary>
/// Gets or sets the custom properties for the client.
/// </summary>
/// <value>
/// The properties.
/// </value>
public IDictionary<string, string> Properties { get; set; } = new Dictionary<string, string>();
/// <summary>
/// Validates the grant types.
/// </summary>
/// <param name="grantTypes">The grant types.</param>
/// <exception cref="System.InvalidOperationException">
/// Grant types list is empty
/// or
/// Grant types cannot contain spaces
/// or
/// Grant types list contains duplicate values
/// </exception>
public static void ValidateGrantTypes(IEnumerable<string> grantTypes)
{
if (grantTypes == null)
{
throw new ArgumentNullException(nameof(grantTypes));
}
// spaces are not allowed in grant types
foreach (var type in grantTypes)
{
if (type.Contains(' '))
{
throw new InvalidOperationException("Grant types cannot contain spaces");
}
}
// single grant type, seems to be fine
if (grantTypes.Count() == 1) return;
// don't allow duplicate grant types
if (grantTypes.Count() != grantTypes.Distinct().Count())
{
throw new InvalidOperationException("Grant types list contains duplicate values");
}
// would allow response_type downgrade attack from code to token
DisallowGrantTypeCombination(GrantType.Implicit, GrantType.AuthorizationCode, grantTypes);
DisallowGrantTypeCombination(GrantType.Implicit, GrantType.Hybrid, grantTypes);
DisallowGrantTypeCombination(GrantType.AuthorizationCode, GrantType.Hybrid, grantTypes);
}
private static void DisallowGrantTypeCombination(string value1, string value2, IEnumerable<string> grantTypes)
{
if (grantTypes.Contains(value1, StringComparer.Ordinal) &&
grantTypes.Contains(value2, StringComparer.Ordinal))
{
throw new InvalidOperationException($"Grant types list cannot contain both {value1} and {value2}");
}
}
internal class GrantTypeValidatingHashSet : ICollection<string>
{
private readonly ICollection<string> _inner;
public GrantTypeValidatingHashSet()
{
_inner = new HashSet<string>();
}
public GrantTypeValidatingHashSet(IEnumerable<string> values)
{
_inner = new HashSet<string>(values);
}
private ICollection<string> Clone()
{
return new HashSet<string>(this);
}
private ICollection<string> CloneWith(params string[] values)
{
var clone = Clone();
foreach (var item in values) clone.Add(item);
return clone;
}
public int Count => _inner.Count;
public bool IsReadOnly => _inner.IsReadOnly;
public void Add(string item)
{
ValidateGrantTypes(CloneWith(item));
_inner.Add(item);
}
public void Clear()
{
_inner.Clear();
}
public bool Contains(string item)
{
return _inner.Contains(item);
}
public void CopyTo(string[] array, int arrayIndex)
{
_inner.CopyTo(array, arrayIndex);
}
public IEnumerator<string> GetEnumerator()
{
return _inner.GetEnumerator();
}
public bool Remove(string item)
{
return _inner.Remove(item);
}
IEnumerator IEnumerable.GetEnumerator()
{
return _inner.GetEnumerator();
}
}
}
}
| |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus SDK License Version 3.4.1 (the "License");
you may not use the Oculus 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/sdk-3.4.1
Unless required by applicable law or agreed to in writing, the Oculus 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.
************************************************************************************/
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using System;
using System.IO;
[InitializeOnLoad]
class OVREngineConfigurationUpdater
{
private const string prefName = "OVREngineConfigurationUpdater_Enabled";
private const string menuItemName = "Tools/Oculus/Use Required Project Settings";
private const string androidAssetsPath = "Assets/Plugins/Android/assets";
private const string androidManifestPath = "Assets/Plugins/Android/AndroidManifest.xml";
static bool setPrefsForUtilities;
[MenuItem(menuItemName)]
static void ToggleUtilities()
{
setPrefsForUtilities = !setPrefsForUtilities;
Menu.SetChecked(menuItemName, setPrefsForUtilities);
int newValue = (setPrefsForUtilities) ? 1 : 0;
PlayerPrefs.SetInt(prefName, newValue);
PlayerPrefs.Save();
Debug.Log("Using required project settings: " + setPrefsForUtilities);
}
#if UNITY_2017_3_OR_NEWER
private static readonly string dashSupportEnableConfirmedKey = "Oculus_Utilities_OVREngineConfiguration_DashSupportEnableConfirmed_" + Application.unityVersion + OVRManager.utilitiesVersion;
private static bool dashSupportEnableConfirmed
{
get
{
return PlayerPrefs.GetInt(dashSupportEnableConfirmedKey, 0) == 1;
}
set
{
PlayerPrefs.SetInt(dashSupportEnableConfirmedKey, value ? 1 : 0);
}
}
private static void DashSupportWarningPrompt()
{
/// <summary>
/// Since Unity 2017.3.0f1 and 2017.3.0f2 have "Dash Support" enabled by default
/// We need prompt developers in case they never test their app with dash
/// </summary>
///
if (Application.unityVersion == "2017.3.0f1" || Application.unityVersion == "2017.3.0f2")
{
if (!dashSupportEnableConfirmed)
{
bool dialogResult = EditorUtility.DisplayDialog("Oculus Dash support", "Your current Unity engine " + Application.unityVersion +
" has Oculus Dash Supporting enabled by default. please make sure to test your app with Dash enabled runtime 1.21 or newer," +
" Otherwise, you can also turn it off under XR Settings -> Oculus", "Understand", "Learn more ");
if (!dialogResult)
{
Application.OpenURL("https://developer.oculus.com/documentation/unity/latest/concepts/unity-lifecycle/");
}
dashSupportEnableConfirmed = true;
}
}
}
#endif
static OVREngineConfigurationUpdater()
{
EditorApplication.delayCall += OnDelayCall;
EditorApplication.update += OnUpdate;
#if UNITY_2017_3_OR_NEWER
DashSupportWarningPrompt();
#endif
}
static void OnDelayCall()
{
setPrefsForUtilities = PlayerPrefs.GetInt(prefName, 1) != 0;
Menu.SetChecked(menuItemName, setPrefsForUtilities);
if (!setPrefsForUtilities)
return;
OVRPlugin.SendEvent("build_target", EditorUserBuildSettings.activeBuildTarget.ToString());
EnforceAndroidSettings();
EnforceInputManagerBindings();
#if UNITY_ANDROID
EnforceOSIG();
#endif
}
static void OnUpdate()
{
if (!setPrefsForUtilities)
return;
EnforceBundleId();
EnforceVRSupport();
EnforceInstallLocation();
}
static void EnforceAndroidSettings()
{
if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.Android)
return;
if (PlayerSettings.defaultInterfaceOrientation != UIOrientation.LandscapeLeft)
{
Debug.Log("OVREngineConfigurationUpdater: Setting orientation to Landscape Left");
// Default screen orientation must be set to landscape left.
PlayerSettings.defaultInterfaceOrientation = UIOrientation.LandscapeLeft;
}
if (!PlayerSettings.virtualRealitySupported)
{
// NOTE: This value should not affect the main window surface
// when Built-in VR support is enabled.
// NOTE: On Adreno Lollipop, it is an error to have antiAliasing set on the
// main window surface with front buffer rendering enabled. The view will
// render black.
// On Adreno KitKat, some tiling control modes will cause the view to render
// black.
if (QualitySettings.antiAliasing != 0 && QualitySettings.antiAliasing != 1)
{
Debug.Log("OVREngineConfigurationUpdater: Disabling antiAliasing");
QualitySettings.antiAliasing = 1;
}
}
if (QualitySettings.vSyncCount != 0)
{
Debug.Log("OVREngineConfigurationUpdater: Setting vsyncCount to 0");
// We sync in the TimeWarp, so we don't want unity syncing elsewhere.
QualitySettings.vSyncCount = 0;
}
}
static void EnforceVRSupport()
{
if (PlayerSettings.virtualRealitySupported)
return;
var mgrs = GameObject.FindObjectsOfType<OVRManager>();
for (int i = 0; i < mgrs.Length; ++i)
{
if (mgrs [i].isActiveAndEnabled)
{
Debug.Log ("Enabling Unity VR support");
PlayerSettings.virtualRealitySupported = true;
bool oculusFound = false;
#if UNITY_2017_2_OR_NEWER
foreach (var device in UnityEngine.XR.XRSettings.supportedDevices)
#else
foreach (var device in UnityEngine.VR.VRSettings.supportedDevices)
#endif
oculusFound |= (device == "Oculus");
if (!oculusFound)
Debug.LogError("Please add Oculus to the list of supported devices to use the Utilities.");
return;
}
}
}
private static void EnforceBundleId()
{
if (!PlayerSettings.virtualRealitySupported)
return;
if (PlayerSettings.applicationIdentifier == "" || PlayerSettings.applicationIdentifier == "com.Company.ProductName")
{
string defaultBundleId = "com.oculus.UnitySample";
Debug.LogWarning("\"" + PlayerSettings.applicationIdentifier + "\" is not a valid bundle identifier. Defaulting to \"" + defaultBundleId + "\".");
PlayerSettings.applicationIdentifier = defaultBundleId;
}
}
private static void EnforceInstallLocation()
{
if (PlayerSettings.Android.preferredInstallLocation != AndroidPreferredInstallLocation.Auto)
PlayerSettings.Android.preferredInstallLocation = AndroidPreferredInstallLocation.Auto;
}
private static void EnforceInputManagerBindings()
{
try
{
BindAxis(new Axis() { name = "Oculus_GearVR_LThumbstickX", axis = 0, });
BindAxis(new Axis() { name = "Oculus_GearVR_LThumbstickY", axis = 1, invert = true });
BindAxis(new Axis() { name = "Oculus_GearVR_RThumbstickX", axis = 2, });
BindAxis(new Axis() { name = "Oculus_GearVR_RThumbstickY", axis = 3, invert = true });
BindAxis(new Axis() { name = "Oculus_GearVR_DpadX", axis = 4, });
BindAxis(new Axis() { name = "Oculus_GearVR_DpadY", axis = 5, invert = true });
BindAxis(new Axis() { name = "Oculus_GearVR_LIndexTrigger", axis = 12, });
BindAxis(new Axis() { name = "Oculus_GearVR_RIndexTrigger", axis = 11, });
BindAxis(new Axis() { name = "Oculus_CrossPlatform_Button2", positiveButton = "joystick button 0", gravity = 1000f, sensitivity = 1000f, type = 0 });
BindAxis(new Axis() { name = "Oculus_CrossPlatform_Button4", positiveButton = "joystick button 2", gravity = 1000f, sensitivity = 1000f, type = 0 });
BindAxis(new Axis() { name = "Oculus_CrossPlatform_PrimaryThumbstick", positiveButton = "joystick button 8", gravity = 0f, dead = 0f, sensitivity = 0.1f, type = 0 });
BindAxis(new Axis() { name = "Oculus_CrossPlatform_SecondaryThumbstick", positiveButton = "joystick button 9", gravity = 0f, dead = 0f, sensitivity = 0.1f, type = 0 });
BindAxis(new Axis() { name = "Oculus_CrossPlatform_PrimaryIndexTrigger", dead = 0.19f, type = 2, axis = 8, joyNum = 0 });
BindAxis(new Axis() { name = "Oculus_CrossPlatform_SecondaryIndexTrigger", dead = 0.19f, type = 2, axis = 9, joyNum = 0 });
BindAxis(new Axis() { name = "Oculus_CrossPlatform_PrimaryHandTrigger", dead = 0.19f, type = 2, axis = 10, joyNum = 0 });
BindAxis(new Axis() { name = "Oculus_CrossPlatform_SecondaryHandTrigger", dead = 0.19f, type = 2, axis = 11, joyNum = 0 });
BindAxis(new Axis() { name = "Oculus_CrossPlatform_PrimaryThumbstickHorizontal", dead = 0.19f, type = 2, axis = 0, joyNum = 0 });
BindAxis(new Axis() { name = "Oculus_CrossPlatform_PrimaryThumbstickVertical", dead = 0.19f, type = 2, axis = 1, joyNum = 0, invert = true });
BindAxis(new Axis() { name = "Oculus_CrossPlatform_SecondaryThumbstickHorizontal", dead = 0.19f, type = 2, axis = 3, joyNum = 0 });
BindAxis(new Axis() { name = "Oculus_CrossPlatform_SecondaryThumbstickVertical", dead = 0.19f, type = 2, axis = 4, joyNum = 0, invert = true });
}
catch
{
Debug.LogError("Failed to apply Oculus GearVR input manager bindings.");
}
}
private static void EnforceOSIG()
{
// Don't bug the user in play mode.
if (Application.isPlaying)
return;
// Don't warn if the project may be set up for submission or global signing.
if (File.Exists(androidManifestPath))
return;
bool foundPossibleOsig = false;
if (Directory.Exists(androidAssetsPath))
{
var files = Directory.GetFiles(androidAssetsPath);
for (int i = 0; i < files.Length; ++i)
{
if (!files[i].Contains(".txt"))
{
foundPossibleOsig = true;
break;
}
}
}
if (!foundPossibleOsig)
Debug.LogWarning("Missing Gear VR OSIG at " + androidAssetsPath + ". Please see https://dashboard.oculus.com/tools/osig-generator");
}
private class Axis
{
public string name = String.Empty;
public string descriptiveName = String.Empty;
public string descriptiveNegativeName = String.Empty;
public string negativeButton = String.Empty;
public string positiveButton = String.Empty;
public string altNegativeButton = String.Empty;
public string altPositiveButton = String.Empty;
public float gravity = 0.0f;
public float dead = 0.001f;
public float sensitivity = 1.0f;
public bool snap = false;
public bool invert = false;
public int type = 2;
public int axis = 0;
public int joyNum = 0;
}
private static void BindAxis(Axis axis)
{
SerializedObject serializedObject = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/InputManager.asset")[0]);
SerializedProperty axesProperty = serializedObject.FindProperty("m_Axes");
SerializedProperty axisIter = axesProperty.Copy();
axisIter.Next(true);
axisIter.Next(true);
while (axisIter.Next(false))
{
if (axisIter.FindPropertyRelative("m_Name").stringValue == axis.name)
{
// Axis already exists. Don't create binding.
return;
}
}
axesProperty.arraySize++;
serializedObject.ApplyModifiedProperties();
SerializedProperty axisProperty = axesProperty.GetArrayElementAtIndex(axesProperty.arraySize - 1);
axisProperty.FindPropertyRelative("m_Name").stringValue = axis.name;
axisProperty.FindPropertyRelative("descriptiveName").stringValue = axis.descriptiveName;
axisProperty.FindPropertyRelative("descriptiveNegativeName").stringValue = axis.descriptiveNegativeName;
axisProperty.FindPropertyRelative("negativeButton").stringValue = axis.negativeButton;
axisProperty.FindPropertyRelative("positiveButton").stringValue = axis.positiveButton;
axisProperty.FindPropertyRelative("altNegativeButton").stringValue = axis.altNegativeButton;
axisProperty.FindPropertyRelative("altPositiveButton").stringValue = axis.altPositiveButton;
axisProperty.FindPropertyRelative("gravity").floatValue = axis.gravity;
axisProperty.FindPropertyRelative("dead").floatValue = axis.dead;
axisProperty.FindPropertyRelative("sensitivity").floatValue = axis.sensitivity;
axisProperty.FindPropertyRelative("snap").boolValue = axis.snap;
axisProperty.FindPropertyRelative("invert").boolValue = axis.invert;
axisProperty.FindPropertyRelative("type").intValue = axis.type;
axisProperty.FindPropertyRelative("axis").intValue = axis.axis;
axisProperty.FindPropertyRelative("joyNum").intValue = axis.joyNum;
serializedObject.ApplyModifiedProperties();
}
}
#endif
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace ParquetSharp.Filter2
{
using System.IO;
public class IncrementallyUpdatedFilterPredicateGenerator
{
private readonly string file;
public static void Main(string[] args)
{
string srcFile = Path.Combine(args[0], "ParquetColumn\\src\\Filter2\\RecordLevel\\IncrementallyUpdatedFilterPredicateBuilder.cs");
new IncrementallyUpdatedFilterPredicateGenerator(srcFile).run();
}
public IncrementallyUpdatedFilterPredicateGenerator(string file)
{
this.file = file;
}
private class TypeInfo
{
public readonly string className;
public readonly string primitiveName;
public readonly bool useComparable;
public readonly bool supportsInequality;
public TypeInfo(string className, string primitiveName, bool useComparable, bool supportsInequality)
{
this.className = className;
this.primitiveName = primitiveName;
this.useComparable = useComparable;
this.supportsInequality = supportsInequality;
}
}
private static readonly TypeInfo[] TYPES = new TypeInfo[]
{
new TypeInfo("Integer", "int", false, true),
new TypeInfo("Long", "long", false, true),
new TypeInfo("Boolean", "boolean", false, false),
new TypeInfo("Float", "float", false, true),
new TypeInfo("Double", "double", false, true),
new TypeInfo("Binary", "Binary", true, true),
};
public void run()
{
using (Stream stream = File.OpenWrite(this.file))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine("/**");
writer.WriteLine(" * This class is auto-generated by {@link parquet.filter2.IncrementallyUpdatedFilterPredicateGenerator}");
writer.WriteLine(" * Do not manually edit!");
writer.WriteLine(" * See {@link IncrementallyUpdatedFilterPredicateBuilderBase}");
writer.WriteLine(" */");
writer.WriteLine();
writer.WriteLine("namespace ParquetSharp.Filter2.RecordLevel");
writer.WriteLine("{");
writer.WriteLine(" using ParquetSharp.Filter2.Predicate;");
writer.WriteLine(" using ParquetSharp.Hadoop.Metadata;");
writer.WriteLine(" using ValueInspector = IncrementallyUpdatedFilterPredicate.ValueInspector;");
writer.WriteLine();
writer.WriteLine(" public class IncrementallyUpdatedFilterPredicateBuilder : IncrementallyUpdatedFilterPredicateBuilderBase");
writer.WriteLine(" {");
addVisitBegin(writer, "Eq");
foreach (TypeInfo info in TYPES)
{
addEqNotEqCase(writer, info, true);
}
addVisitEnd(writer);
addVisitBegin(writer, "NotEq");
foreach (TypeInfo info in TYPES)
{
addEqNotEqCase(writer, info, false);
}
addVisitEnd(writer);
addVisitBegin(writer, "Lt");
foreach (TypeInfo info in TYPES)
{
addInequalityCase(writer, info, "<");
}
addVisitEnd(writer);
addVisitBegin(writer, "LtEq");
foreach (TypeInfo info in TYPES)
{
addInequalityCase(writer, info, "<=");
}
addVisitEnd(writer);
addVisitBegin(writer, "Gt");
foreach (TypeInfo info in TYPES)
{
addInequalityCase(writer, info, ">");
}
addVisitEnd(writer);
addVisitBegin(writer, "GtEq");
foreach (TypeInfo info in TYPES)
{
addInequalityCase(writer, info, ">=");
}
addVisitEnd(writer);
writer.WriteLine(" public override IncrementallyUpdatedFilterPredicate visit<T, U>(Operators.UserDefined<T, U> udp)");
writer.WriteLine(" {");
addUdpBegin(writer);
foreach (TypeInfo info in TYPES)
{
addUdpCase(writer, info, false);
}
addVisitEnd(writer);
writer.WriteLine(" public override IncrementallyUpdatedFilterPredicate visit<T, U>(Operators.LogicalNotUserDefined<T, U> udp)");
writer.WriteLine(" {");
writer.WriteLine(" Operators.UserDefined<T, U> pred = notPred.getUserDefined();");
addUdpBegin(writer);
foreach (TypeInfo info in TYPES)
{
addUdpCase(writer, info, true);
}
addVisitEnd(writer);
writer.WriteLine(" }");
writer.WriteLine("}");
}
}
private void addVisitBegin(StreamWriter writer, string inVar)
{
writer.WriteLine(" public override IncrementallyUpdatedFilterPredicate visit<T>(Operators." + inVar + "<T> pred)");
writer.WriteLine(" {");
writer.WriteLine(" ColumnPath columnPath = pred.getColumn().getColumnPath();");
writer.WriteLine(" System.Type type = pred.getColumn().getColumnType();");
writer.WriteLine();
writer.WriteLine(" ValueInspector valueInspector = null;");
writer.WriteLine();
}
private void addVisitEnd(StreamWriter writer)
{
writer.WriteLine(" if (valueInspector == null)");
writer.WriteLine(" {");
writer.WriteLine(" throw new ArgumentException(\"Encountered unknown type \" + clazz);");
writer.WriteLine(" }");
writer.WriteLine();
writer.WriteLine(" addValueInspector(columnPath, valueInspector);");
writer.WriteLine(" return valueInspector;");
writer.WriteLine(" }");
writer.WriteLine();
}
private void addEqNotEqCase(StreamWriter writer, TypeInfo info, bool isEq)
{
writer.WriteLine(" if (type == typeof(" + info.className + ")) {");
writer.WriteLine(" if (pred.getValue() == null) {");
writer.WriteLine(" valueInspector = new ValueInspector() {");
writer.WriteLine(" @Override");
writer.WriteLine(" public void updateNull() {");
writer.WriteLine(" setResult({0});", isEq ? "true" : "false");
writer.WriteLine(" }");
writer.WriteLine();
writer.WriteLine(" @Override");
writer.WriteLine(" public void update(" + info.primitiveName + " value) {");
writer.WriteLine(" setResult({0});", isEq ? "false" : "true");
writer.WriteLine(" }");
writer.WriteLine(" };");
writer.WriteLine(" } else {");
writer.WriteLine(" " + info.primitiveName + " target = (" + info.className + ") (Object) pred.getValue();");
writer.WriteLine();
writer.WriteLine(" valueInspector = new ValueInspector() {");
writer.WriteLine(" @Override");
writer.WriteLine(" public void updateNull() {");
writer.WriteLine(" setResult({0});", isEq ? "false" : "true");
writer.WriteLine(" }");
writer.WriteLine();
writer.WriteLine(" @Override");
writer.WriteLine(" public void update(" + info.primitiveName + " value) {");
if (info.useComparable)
{
writer.WriteLine(" setResult(" + compareEquality("value", "target", isEq) + ");");
}
else
{
writer.WriteLine(" setResult(" + (isEq ? "value == target" : "value != target") + ");");
}
writer.WriteLine(" }");
writer.WriteLine(" };");
writer.WriteLine(" }");
writer.WriteLine(" }");
writer.WriteLine();
}
private void addInequalityCase(StreamWriter writer, TypeInfo info, string op)
{
if (!info.supportsInequality)
{
writer.WriteLine(" if (type == typeof(" + info.className + ")) {");
writer.WriteLine(" throw new ArgumentException(\"Operator " + op + " not supported for " + info.className + "\");");
writer.WriteLine(" }");
writer.WriteLine();
return;
}
writer.WriteLine(" if (type == typeof(" + info.className + ")) {");
writer.WriteLine(" " + info.primitiveName + " target = (" + info.className + ") (Object) pred.getValue();");
writer.WriteLine();
writer.WriteLine(" valueInspector = new ValueInspector() {");
writer.WriteLine(" @Override");
writer.WriteLine(" public void updateNull() {");
writer.WriteLine(" setResult(false);");
writer.WriteLine(" }");
writer.WriteLine();
writer.WriteLine(" @Override");
writer.WriteLine(" public void update(" + info.primitiveName + " value) {");
if (info.useComparable)
{
writer.WriteLine(" setResult(value.CompareTo(target) " + op + " 0);");
}
else {
writer.WriteLine(" setResult(value " + op + " target);");
}
writer.WriteLine(" }");
writer.WriteLine(" };");
writer.WriteLine(" }");
writer.WriteLine();
}
private void addUdpBegin(StreamWriter writer)
{
writer.WriteLine(" ColumnPath columnPath = pred.getColumn().getColumnPath();");
writer.WriteLine(" System.Type type = pred.getColumn().getColumnType();");
writer.WriteLine();
writer.WriteLine(" ValueInspector valueInspector = null;");
writer.WriteLine();
writer.WriteLine(" U udp = pred.getUserDefinedPredicate();");
writer.WriteLine();
}
private void addUdpCase(StreamWriter writer, TypeInfo info, bool invert)
{
writer.WriteLine(" if (type == typeof(" + info.className + ")) {");
writer.WriteLine(" valueInspector = new ValueInspector() {");
writer.WriteLine(" @Override");
writer.WriteLine(" public void updateNull() {");
writer.WriteLine(" setResult(" + (invert ? "!" : "") + "udp.keep(null));");
writer.WriteLine(" }");
writer.WriteLine();
writer.WriteLine(" @SuppressWarnings(\"unchecked\")");
writer.WriteLine(" @Override");
writer.WriteLine(" public void update(" + info.primitiveName + " value) {");
writer.WriteLine(" setResult(" + (invert ? "!" : "") + "udp.keep((T) (Object) value));");
writer.WriteLine(" }");
writer.WriteLine(" };");
writer.WriteLine(" }");
writer.WriteLine();
}
private string compareEquality(string var, string target, bool eq)
{
return var + ".compareTo(" + target + ")" + (eq ? " == 0 " : " != 0");
}
}
}
| |
using NUnit.Framework;
using System;
using FilenameBuddy;
using System.IO;
using Shouldly;
namespace FilenameBuddyTests
{
[TestFixture()]
public class Test
{
[SetUp]
public void Setup()
{
Filename.SetCurrentDirectory(Directory.GetCurrentDirectory() + @"\Content\");
}
/// <summary>
/// get the current working directory
/// </summary>
/// <returns>The location.</returns>
string progLocation()
{
return Filename.ReplaceSlashes(Directory.GetCurrentDirectory() + @"\Content\");
}
[Test()]
public void StaticConstructor()
{
//get teh program location
Assert.AreEqual(Directory.GetCurrentDirectory() + "\\", Filename.ProgramLocation);
}
[Test()]
public void DefaultConstructor()
{
//default constructor = no filename
Filename dude = new Filename();
Assert.IsTrue(string.IsNullOrEmpty(dude.File));
}
[Test()]
public void Constructor()
{
//set the filename in teh constructor
Filename dude = new Filename("test");
dude.File.ShouldBe(progLocation() + @"test");
}
[Test()]
public void SetFilename()
{
//set the name and get it back
Filename dude = new Filename();
dude.File = "test";
Assert.AreEqual("test", dude.File);
}
[Test()]
public void SetAbsFilenameGetRelFilename()
{
//set the name and get it back
Filename dude = new Filename();
dude.File = progLocation() + @"Buttnuts\test.txt";
Assert.AreEqual(@"Buttnuts\test.txt", dude.GetRelFilename());
}
[Test()]
public void SetRelFilename()
{
Filename dude = new Filename();
dude.SetRelFilename("test");
dude.File.ShouldBe(progLocation() + @"test");
}
[Test()]
public void SetRelFilename1()
{
Filename dude = new Filename();
dude.SetRelFilename(@"Buttnuts\test.txt");
dude.File.ShouldBe(progLocation() + @"Buttnuts\test.txt");
}
[Test()]
public void GetPath()
{
Filename dude = new Filename();
dude.SetRelFilename("test");
Assert.AreEqual(progLocation(), dude.GetPath());
}
[Test()]
public void GetPathWithExt()
{
Filename dude = new Filename();
dude.SetRelFilename("test.txt");
Assert.AreEqual(progLocation(), dude.GetPath());
}
[Test()]
public void GetPathWithSub()
{
Filename dude = new Filename();
dude.SetRelFilename("test.txt");
Assert.AreEqual(progLocation(), dude.GetPath());
}
[Test()]
public void GetRelPath()
{
Filename dude = new Filename();
dude.SetRelFilename(@"Buttnuts\test.txt");
Assert.AreEqual(@"Buttnuts\", dude.GetRelPath());
}
[Test()]
public void GetRelPath1()
{
Filename dude = new Filename();
dude.SetRelFilename(@"Buttnuts\assnuts\test.txt");
Assert.AreEqual(@"Buttnuts\assnuts\", dude.GetRelPath());
}
[Test()]
public void GetFilename()
{
Filename dude = new Filename();
dude.SetRelFilename(@"Content\Buttnuts\assnuts\test.txt");
Assert.AreEqual(@"test.txt", dude.GetFile());
}
[Test()]
public void GetFilename1()
{
Filename dude = new Filename();
dude.SetRelFilename(@"Content\Buttnuts\assnuts\test");
Assert.AreEqual(@"test", dude.GetFile());
}
[Test()]
public void GetFileExt()
{
Filename dude = new Filename();
dude.SetRelFilename(@"Content\Buttnuts\assnuts\test.txt");
Assert.AreEqual(@".txt", dude.GetFileExt());
}
[Test()]
public void GetFileExt1()
{
Filename dude = new Filename();
dude.SetRelFilename(@"Content\Buttnuts\assnuts\test");
Assert.AreEqual(@"", dude.GetFileExt());
}
[Test()]
public void GetFileNoExt()
{
Filename dude = new Filename();
dude.SetRelFilename(@"Content\Buttnuts\assnuts\test.txt");
Assert.AreEqual(@"test", dude.GetFileNoExt());
}
[Test()]
public void GetFileNoExtBreakIt()
{
Filename dude = new Filename();
dude.SetRelFilename(@"Content\Buttnuts\assnuts\test");
Assert.AreEqual(@"test", dude.GetFileNoExt());
}
[Test()]
public void GetPathFileNoExt()
{
Filename dude = new Filename();
string testFile = @"Buttnuts\assnuts\test.txt";
dude.SetRelFilename(testFile);
Assert.AreEqual(progLocation() + @"Buttnuts\assnuts\test", dude.GetPathFileNoExt());
}
[Test()]
public void GetRelPathFileNoExt()
{
Filename dude = new Filename();
string testFile = @"Buttnuts\assnuts\test.txt";
dude.SetRelFilename(testFile);
Assert.AreEqual(@"Buttnuts\assnuts\test", dude.GetRelPathFileNoExt());
}
[Test()]
public void GetRelFilename()
{
Filename dude = new Filename();
string testFile = @"Buttnuts\assnuts\test.txt";
dude.SetRelFilename(testFile);
Assert.AreEqual(@"Buttnuts\assnuts\test.txt", dude.GetRelFilename());
}
[Test()]
public void SetCurrentDirectory()
{
Filename.SetCurrentDirectory(@"c:assnuts\shitass\Content\poopstains");
Filename dude = new Filename();
string testFile = @"Buttnuts\assnuts\test.txt";
dude.SetRelFilename(testFile);
dude.File.ShouldBe(Filename.ReplaceSlashes(@"c:assnuts/shitass/Content/Buttnuts/assnuts/test.txt"));
}
[Test()]
public void GetRelFilename1()
{
Filename dude = new Filename();
string testFile = @"test.txt";
dude.SetRelFilename(testFile);
Assert.AreEqual(@"test.txt", dude.GetRelFilename());
}
[Test()]
public void GetRelFilename2()
{
Filename dude = new Filename();
string testFile = @"test.txt";
dude.SetRelFilename(testFile);
Assert.AreEqual(@"test.txt", dude.GetRelFilename());
}
[Test()]
public void FilenameNoExt()
{
Filename dude = new Filename();
string testFile = @"test.txt";
dude.SetRelFilename(testFile);
Assert.AreEqual(@"test", dude.GetFileNoExt());
}
[Test()]
public void FilenameNoExt1()
{
Filename dude = new Filename();
string testFile = @"windows.xna\test.txt";
dude.SetRelFilename(testFile);
Assert.AreEqual(@"test", dude.GetFileNoExt());
}
[Test()]
public void GetExtension()
{
Filename dude = new Filename();
string testFile = @"windows.xna\test.longextension";
dude.SetRelFilename(testFile);
Assert.AreEqual(@".longextension", dude.GetFileExt());
}
[Test]
public void Comparison()
{
var dude1 = new Filename("dude");
var dude2 = new Filename("dude");
Assert.IsTrue(dude1.Compare(dude2));
}
[Test]
public void Comparison_false()
{
var dude1 = new Filename("dude");
var dude2 = new Filename("cat");
Assert.IsFalse(dude1.Compare(dude2));
}
[Test]
public void HasFilename1()
{
var dude = new Filename();
dude.HasFilename.ShouldBeFalse();
}
[Test]
public void HasFilename2()
{
var dude = new Filename("dude");
dude.HasFilename.ShouldBeTrue();
}
[Test]
public void HasFilename3()
{
var dude = new Filename();
dude.File = "dude";
dude.HasFilename.ShouldBeTrue();
}
[Test]
public void HasFilename4()
{
var dude1 = new Filename("dude");
var dude2 = new Filename(dude1);
dude2.HasFilename.ShouldBeTrue();
}
[Test]
public void HasFilename5()
{
var dude1 = new Filename();
var dude2 = new Filename(dude1);
dude2.HasFilename.ShouldBeFalse();
}
[Test]
public void HasFilename6()
{
var dude1 = new Filename();
dude1.SetRelFilename("dude");
dude1.HasFilename.ShouldBeTrue();
}
[Test]
public void SetFromRelativeFilename()
{
Filename originalLocation = new Filename();
string testFile = @"Buttnuts\assnuts\test.txt";
originalLocation.SetRelFilename(testFile);
var secondFilename = new Filename(originalLocation, "catpants\\cat.png");
secondFilename.GetRelFilename().ShouldBe(@"Buttnuts\assnuts\catpants\cat.png");
}
[TestCase(@"test1\test.txt", @"test2.txt", @"test1\test2.txt")]
[TestCase(@"test1\test.txt", @"test3\test2.txt", @"test1\test3\test2.txt")]
[TestCase(@"test1\test2\test3.txt", @"..\test4\test5.txt", @"test1\test4\test5.txt")]
public void SetFilenameRelativeToPath(string original, string target, string expectedResult)
{
var originalFilename = new Filename(original);
var targetFilename = new Filename();
targetFilename.SetFilenameRelativeToPath(originalFilename, target);
targetFilename.GetRelFilename().ShouldBe(expectedResult);
}
[TestCase(@"test1\test.txt", @"test1\test2.txt", @"test2.txt")]
[TestCase(@"test1\test.txt", @"test1\test3\test2.txt", @"test3\test2.txt")]
[TestCase(@"test1\test2\test3.txt", @"test1\test4\test5.txt", @"..\test4\test5.txt")]
public void GetFilenameRelativeToPath(string original, string target, string expectedResult)
{
var originalFilename = new Filename(original);
var targetFilename = new Filename(target);
targetFilename.GetFilenameRelativeToPath(originalFilename).ShouldBe(expectedResult);
}
[Test]
public void SetFilenameRelativeToPath_fullPAth()
{
var originalFilename = new Filename(@"test1\test.txt");
var targetFilename = new Filename();
targetFilename.SetFilenameRelativeToPath(originalFilename, @"test2.txt");
var expectedResult = $@"{Filename.ProgramLocation}Content\test1\test2.txt";
targetFilename.File.ShouldBe(expectedResult);
}
[Test]
public void ChangeExtension()
{
var originalFilename = new Filename { File = @"C:\test1\test.xml" };
originalFilename.ChangeExtension("json");
originalFilename.File.ShouldBe(@"C:\test1\test.json");
}
}
}
| |
namespace android.net
{
[global::MonoJavaBridge.JavaClass()]
public partial class NetworkInfo : java.lang.Object, android.os.Parcelable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static NetworkInfo()
{
InitJNI();
}
protected NetworkInfo(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public sealed partial class DetailedState : java.lang.Enum
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static DetailedState()
{
InitJNI();
}
internal DetailedState(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _values5198;
public static global::android.net.NetworkInfo.DetailedState[] values()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.net.NetworkInfo.DetailedState>(@__env.CallStaticObjectMethod(android.net.NetworkInfo.DetailedState.staticClass, global::android.net.NetworkInfo.DetailedState._values5198)) as android.net.NetworkInfo.DetailedState[];
}
internal static global::MonoJavaBridge.MethodId _valueOf5199;
public static global::android.net.NetworkInfo.DetailedState valueOf(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.net.NetworkInfo.DetailedState.staticClass, global::android.net.NetworkInfo.DetailedState._valueOf5199, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.NetworkInfo.DetailedState;
}
internal static global::MonoJavaBridge.FieldId _AUTHENTICATING5200;
public static global::android.net.NetworkInfo.DetailedState AUTHENTICATING
{
get
{
return default(global::android.net.NetworkInfo.DetailedState);
}
}
internal static global::MonoJavaBridge.FieldId _CONNECTED5201;
public static global::android.net.NetworkInfo.DetailedState CONNECTED
{
get
{
return default(global::android.net.NetworkInfo.DetailedState);
}
}
internal static global::MonoJavaBridge.FieldId _CONNECTING5202;
public static global::android.net.NetworkInfo.DetailedState CONNECTING
{
get
{
return default(global::android.net.NetworkInfo.DetailedState);
}
}
internal static global::MonoJavaBridge.FieldId _DISCONNECTED5203;
public static global::android.net.NetworkInfo.DetailedState DISCONNECTED
{
get
{
return default(global::android.net.NetworkInfo.DetailedState);
}
}
internal static global::MonoJavaBridge.FieldId _DISCONNECTING5204;
public static global::android.net.NetworkInfo.DetailedState DISCONNECTING
{
get
{
return default(global::android.net.NetworkInfo.DetailedState);
}
}
internal static global::MonoJavaBridge.FieldId _FAILED5205;
public static global::android.net.NetworkInfo.DetailedState FAILED
{
get
{
return default(global::android.net.NetworkInfo.DetailedState);
}
}
internal static global::MonoJavaBridge.FieldId _IDLE5206;
public static global::android.net.NetworkInfo.DetailedState IDLE
{
get
{
return default(global::android.net.NetworkInfo.DetailedState);
}
}
internal static global::MonoJavaBridge.FieldId _OBTAINING_IPADDR5207;
public static global::android.net.NetworkInfo.DetailedState OBTAINING_IPADDR
{
get
{
return default(global::android.net.NetworkInfo.DetailedState);
}
}
internal static global::MonoJavaBridge.FieldId _SCANNING5208;
public static global::android.net.NetworkInfo.DetailedState SCANNING
{
get
{
return default(global::android.net.NetworkInfo.DetailedState);
}
}
internal static global::MonoJavaBridge.FieldId _SUSPENDED5209;
public static global::android.net.NetworkInfo.DetailedState SUSPENDED
{
get
{
return default(global::android.net.NetworkInfo.DetailedState);
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.net.NetworkInfo.DetailedState.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/net/NetworkInfo$DetailedState"));
global::android.net.NetworkInfo.DetailedState._values5198 = @__env.GetStaticMethodIDNoThrow(global::android.net.NetworkInfo.DetailedState.staticClass, "values", "()[Landroid/net/NetworkInfo/DetailedState;");
global::android.net.NetworkInfo.DetailedState._valueOf5199 = @__env.GetStaticMethodIDNoThrow(global::android.net.NetworkInfo.DetailedState.staticClass, "valueOf", "(Ljava/lang/String;)Landroid/net/NetworkInfo$DetailedState;");
}
}
[global::MonoJavaBridge.JavaClass()]
public sealed partial class State : java.lang.Enum
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static State()
{
InitJNI();
}
internal State(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _values5210;
public static global::android.net.NetworkInfo.State[] values()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.net.NetworkInfo.State>(@__env.CallStaticObjectMethod(android.net.NetworkInfo.State.staticClass, global::android.net.NetworkInfo.State._values5210)) as android.net.NetworkInfo.State[];
}
internal static global::MonoJavaBridge.MethodId _valueOf5211;
public static global::android.net.NetworkInfo.State valueOf(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.net.NetworkInfo.State.staticClass, global::android.net.NetworkInfo.State._valueOf5211, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.NetworkInfo.State;
}
internal static global::MonoJavaBridge.FieldId _CONNECTED5212;
public static global::android.net.NetworkInfo.State CONNECTED
{
get
{
return default(global::android.net.NetworkInfo.State);
}
}
internal static global::MonoJavaBridge.FieldId _CONNECTING5213;
public static global::android.net.NetworkInfo.State CONNECTING
{
get
{
return default(global::android.net.NetworkInfo.State);
}
}
internal static global::MonoJavaBridge.FieldId _DISCONNECTED5214;
public static global::android.net.NetworkInfo.State DISCONNECTED
{
get
{
return default(global::android.net.NetworkInfo.State);
}
}
internal static global::MonoJavaBridge.FieldId _DISCONNECTING5215;
public static global::android.net.NetworkInfo.State DISCONNECTING
{
get
{
return default(global::android.net.NetworkInfo.State);
}
}
internal static global::MonoJavaBridge.FieldId _SUSPENDED5216;
public static global::android.net.NetworkInfo.State SUSPENDED
{
get
{
return default(global::android.net.NetworkInfo.State);
}
}
internal static global::MonoJavaBridge.FieldId _UNKNOWN5217;
public static global::android.net.NetworkInfo.State UNKNOWN
{
get
{
return default(global::android.net.NetworkInfo.State);
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.net.NetworkInfo.State.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/net/NetworkInfo$State"));
global::android.net.NetworkInfo.State._values5210 = @__env.GetStaticMethodIDNoThrow(global::android.net.NetworkInfo.State.staticClass, "values", "()[Landroid/net/NetworkInfo/State;");
global::android.net.NetworkInfo.State._valueOf5211 = @__env.GetStaticMethodIDNoThrow(global::android.net.NetworkInfo.State.staticClass, "valueOf", "(Ljava/lang/String;)Landroid/net/NetworkInfo$State;");
}
}
internal static global::MonoJavaBridge.MethodId _toString5218;
public override global::java.lang.String toString()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.NetworkInfo._toString5218)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.NetworkInfo.staticClass, global::android.net.NetworkInfo._toString5218)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _getState5219;
public virtual global::android.net.NetworkInfo.State getState()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.NetworkInfo._getState5219)) as android.net.NetworkInfo.State;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.NetworkInfo.staticClass, global::android.net.NetworkInfo._getState5219)) as android.net.NetworkInfo.State;
}
internal static global::MonoJavaBridge.MethodId _getType5220;
public virtual int getType()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.net.NetworkInfo._getType5220);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.net.NetworkInfo.staticClass, global::android.net.NetworkInfo._getType5220);
}
internal static global::MonoJavaBridge.MethodId _getTypeName5221;
public virtual global::java.lang.String getTypeName()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.NetworkInfo._getTypeName5221)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.NetworkInfo.staticClass, global::android.net.NetworkInfo._getTypeName5221)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _isAvailable5222;
public virtual bool isAvailable()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.net.NetworkInfo._isAvailable5222);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.net.NetworkInfo.staticClass, global::android.net.NetworkInfo._isAvailable5222);
}
internal static global::MonoJavaBridge.MethodId _writeToParcel5223;
public virtual void writeToParcel(android.os.Parcel arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.net.NetworkInfo._writeToParcel5223, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.net.NetworkInfo.staticClass, global::android.net.NetworkInfo._writeToParcel5223, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _describeContents5224;
public virtual int describeContents()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.net.NetworkInfo._describeContents5224);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.net.NetworkInfo.staticClass, global::android.net.NetworkInfo._describeContents5224);
}
internal static global::MonoJavaBridge.MethodId _getReason5225;
public virtual global::java.lang.String getReason()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.NetworkInfo._getReason5225)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.NetworkInfo.staticClass, global::android.net.NetworkInfo._getReason5225)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _isConnected5226;
public virtual bool isConnected()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.net.NetworkInfo._isConnected5226);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.net.NetworkInfo.staticClass, global::android.net.NetworkInfo._isConnected5226);
}
internal static global::MonoJavaBridge.MethodId _isFailover5227;
public virtual bool isFailover()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.net.NetworkInfo._isFailover5227);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.net.NetworkInfo.staticClass, global::android.net.NetworkInfo._isFailover5227);
}
internal static global::MonoJavaBridge.MethodId _getSubtype5228;
public virtual int getSubtype()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.net.NetworkInfo._getSubtype5228);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.net.NetworkInfo.staticClass, global::android.net.NetworkInfo._getSubtype5228);
}
internal static global::MonoJavaBridge.MethodId _getSubtypeName5229;
public virtual global::java.lang.String getSubtypeName()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.NetworkInfo._getSubtypeName5229)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.NetworkInfo.staticClass, global::android.net.NetworkInfo._getSubtypeName5229)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _isConnectedOrConnecting5230;
public virtual bool isConnectedOrConnecting()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.net.NetworkInfo._isConnectedOrConnecting5230);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.net.NetworkInfo.staticClass, global::android.net.NetworkInfo._isConnectedOrConnecting5230);
}
internal static global::MonoJavaBridge.MethodId _isRoaming5231;
public virtual bool isRoaming()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.net.NetworkInfo._isRoaming5231);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.net.NetworkInfo.staticClass, global::android.net.NetworkInfo._isRoaming5231);
}
internal static global::MonoJavaBridge.MethodId _getDetailedState5232;
public virtual global::android.net.NetworkInfo.DetailedState getDetailedState()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.NetworkInfo._getDetailedState5232)) as android.net.NetworkInfo.DetailedState;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.NetworkInfo.staticClass, global::android.net.NetworkInfo._getDetailedState5232)) as android.net.NetworkInfo.DetailedState;
}
internal static global::MonoJavaBridge.MethodId _getExtraInfo5233;
public virtual global::java.lang.String getExtraInfo()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.NetworkInfo._getExtraInfo5233)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.NetworkInfo.staticClass, global::android.net.NetworkInfo._getExtraInfo5233)) as java.lang.String;
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.net.NetworkInfo.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/net/NetworkInfo"));
global::android.net.NetworkInfo._toString5218 = @__env.GetMethodIDNoThrow(global::android.net.NetworkInfo.staticClass, "toString", "()Ljava/lang/String;");
global::android.net.NetworkInfo._getState5219 = @__env.GetMethodIDNoThrow(global::android.net.NetworkInfo.staticClass, "getState", "()Landroid/net/NetworkInfo$State;");
global::android.net.NetworkInfo._getType5220 = @__env.GetMethodIDNoThrow(global::android.net.NetworkInfo.staticClass, "getType", "()I");
global::android.net.NetworkInfo._getTypeName5221 = @__env.GetMethodIDNoThrow(global::android.net.NetworkInfo.staticClass, "getTypeName", "()Ljava/lang/String;");
global::android.net.NetworkInfo._isAvailable5222 = @__env.GetMethodIDNoThrow(global::android.net.NetworkInfo.staticClass, "isAvailable", "()Z");
global::android.net.NetworkInfo._writeToParcel5223 = @__env.GetMethodIDNoThrow(global::android.net.NetworkInfo.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V");
global::android.net.NetworkInfo._describeContents5224 = @__env.GetMethodIDNoThrow(global::android.net.NetworkInfo.staticClass, "describeContents", "()I");
global::android.net.NetworkInfo._getReason5225 = @__env.GetMethodIDNoThrow(global::android.net.NetworkInfo.staticClass, "getReason", "()Ljava/lang/String;");
global::android.net.NetworkInfo._isConnected5226 = @__env.GetMethodIDNoThrow(global::android.net.NetworkInfo.staticClass, "isConnected", "()Z");
global::android.net.NetworkInfo._isFailover5227 = @__env.GetMethodIDNoThrow(global::android.net.NetworkInfo.staticClass, "isFailover", "()Z");
global::android.net.NetworkInfo._getSubtype5228 = @__env.GetMethodIDNoThrow(global::android.net.NetworkInfo.staticClass, "getSubtype", "()I");
global::android.net.NetworkInfo._getSubtypeName5229 = @__env.GetMethodIDNoThrow(global::android.net.NetworkInfo.staticClass, "getSubtypeName", "()Ljava/lang/String;");
global::android.net.NetworkInfo._isConnectedOrConnecting5230 = @__env.GetMethodIDNoThrow(global::android.net.NetworkInfo.staticClass, "isConnectedOrConnecting", "()Z");
global::android.net.NetworkInfo._isRoaming5231 = @__env.GetMethodIDNoThrow(global::android.net.NetworkInfo.staticClass, "isRoaming", "()Z");
global::android.net.NetworkInfo._getDetailedState5232 = @__env.GetMethodIDNoThrow(global::android.net.NetworkInfo.staticClass, "getDetailedState", "()Landroid/net/NetworkInfo$DetailedState;");
global::android.net.NetworkInfo._getExtraInfo5233 = @__env.GetMethodIDNoThrow(global::android.net.NetworkInfo.staticClass, "getExtraInfo", "()Ljava/lang/String;");
}
}
}
| |
// 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.
/*============================================================
**
**
**
** Purpose: Convenient wrapper for an array, an offset, and
** a count. Ideally used in streams & collections.
** Net Classes will consume an array of these.
**
**
===========================================================*/
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System
{
// Note: users should make sure they copy the fields out of an ArraySegment onto their stack
// then validate that the fields describe valid bounds within the array. This must be done
// because assignments to value types are not atomic, and also because one thread reading
// three fields from an ArraySegment may not see the same ArraySegment from one call to another
// (ie, users could assign a new value to the old location).
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct ArraySegment<T> : IList<T>, IReadOnlyList<T>
{
// Do not replace the array allocation with Array.Empty. We don't want to have the overhead of
// instantiating another generic type in addition to ArraySegment<T> for new type parameters.
public static ArraySegment<T> Empty { get; } = new ArraySegment<T>(new T[0]);
private readonly T[] _array; // Do not rename (binary serialization)
private readonly int _offset; // Do not rename (binary serialization)
private readonly int _count; // Do not rename (binary serialization)
public ArraySegment(T[] array)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
Contract.EndContractBlock();
_array = array;
_offset = 0;
_count = array.Length;
}
public ArraySegment(T[] array, int offset, int count)
{
// Validate arguments, check is minimal instructions with reduced branching for inlinable fast-path
// Negative values discovered though conversion to high values when converted to unsigned
// Failure should be rare and location determination and message is delegated to failure functions
if (array == null || (uint)offset > (uint)array.Length || (uint)count > (uint)(array.Length - offset))
ThrowHelper.ThrowArraySegmentCtorValidationFailedExceptions(array, offset, count);
Contract.EndContractBlock();
_array = array;
_offset = offset;
_count = count;
}
public T[] Array => _array;
public int Offset => _offset;
public int Count => _count;
public T this[int index]
{
get
{
if ((uint)index >= (uint)_count)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
}
return _array[_offset + index];
}
set
{
if ((uint)index >= (uint)_count)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
}
_array[_offset + index] = value;
}
}
public Enumerator GetEnumerator()
{
ThrowInvalidOperationIfDefault();
return new Enumerator(this);
}
public override int GetHashCode()
{
if (_array == null)
{
return 0;
}
int hash = 5381;
hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _offset);
hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _count);
// The array hash is expected to be an evenly-distributed mixture of bits,
// so rather than adding the cost of another rotation we just xor it.
hash ^= _array.GetHashCode();
return hash;
}
public void CopyTo(T[] destination) => CopyTo(destination, 0);
public void CopyTo(T[] destination, int destinationIndex)
{
ThrowInvalidOperationIfDefault();
System.Array.Copy(_array, _offset, destination, destinationIndex, _count);
}
public void CopyTo(ArraySegment<T> destination)
{
ThrowInvalidOperationIfDefault();
destination.ThrowInvalidOperationIfDefault();
if (_count > destination._count)
{
ThrowHelper.ThrowArgumentException_DestinationTooShort();
}
System.Array.Copy(_array, _offset, destination._array, destination._offset, _count);
}
public override bool Equals(Object obj)
{
if (obj is ArraySegment<T>)
return Equals((ArraySegment<T>)obj);
else
return false;
}
public bool Equals(ArraySegment<T> obj)
{
return obj._array == _array && obj._offset == _offset && obj._count == _count;
}
public ArraySegment<T> Slice(int index)
{
ThrowInvalidOperationIfDefault();
if ((uint)index > (uint)_count)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
}
return new ArraySegment<T>(_array, _offset + index, _count - index);
}
public ArraySegment<T> Slice(int index, int count)
{
ThrowInvalidOperationIfDefault();
if ((uint)index > (uint)_count || (uint)count > (uint)(_count - index))
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
}
return new ArraySegment<T>(_array, _offset + index, count);
}
public T[] ToArray()
{
ThrowInvalidOperationIfDefault();
if (_count == 0)
{
return Empty._array;
}
var array = new T[_count];
System.Array.Copy(_array, _offset, array, 0, _count);
return array;
}
public static bool operator ==(ArraySegment<T> a, ArraySegment<T> b)
{
return a.Equals(b);
}
public static bool operator !=(ArraySegment<T> a, ArraySegment<T> b)
{
return !(a == b);
}
public static implicit operator ArraySegment<T>(T[] array) => new ArraySegment<T>(array);
#region IList<T>
T IList<T>.this[int index]
{
get
{
ThrowInvalidOperationIfDefault();
if (index < 0 || index >= _count)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
Contract.EndContractBlock();
return _array[_offset + index];
}
set
{
ThrowInvalidOperationIfDefault();
if (index < 0 || index >= _count)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
Contract.EndContractBlock();
_array[_offset + index] = value;
}
}
int IList<T>.IndexOf(T item)
{
ThrowInvalidOperationIfDefault();
int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
Debug.Assert(index == -1 ||
(index >= _offset && index < _offset + _count));
return index >= 0 ? index - _offset : -1;
}
void IList<T>.Insert(int index, T item)
{
ThrowHelper.ThrowNotSupportedException();
}
void IList<T>.RemoveAt(int index)
{
ThrowHelper.ThrowNotSupportedException();
}
#endregion
#region IReadOnlyList<T>
T IReadOnlyList<T>.this[int index]
{
get
{
ThrowInvalidOperationIfDefault();
if (index < 0 || index >= _count)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
Contract.EndContractBlock();
return _array[_offset + index];
}
}
#endregion IReadOnlyList<T>
#region ICollection<T>
bool ICollection<T>.IsReadOnly
{
get
{
// the indexer setter does not throw an exception although IsReadOnly is true.
// This is to match the behavior of arrays.
return true;
}
}
void ICollection<T>.Add(T item)
{
ThrowHelper.ThrowNotSupportedException();
}
void ICollection<T>.Clear()
{
ThrowHelper.ThrowNotSupportedException();
}
bool ICollection<T>.Contains(T item)
{
ThrowInvalidOperationIfDefault();
int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
Debug.Assert(index == -1 ||
(index >= _offset && index < _offset + _count));
return index >= 0;
}
bool ICollection<T>.Remove(T item)
{
ThrowHelper.ThrowNotSupportedException();
return default(bool);
}
#endregion
#region IEnumerable<T>
IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
private void ThrowInvalidOperationIfDefault()
{
if (_array == null)
{
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray);
}
}
public struct Enumerator : IEnumerator<T>
{
private readonly T[] _array;
private readonly int _start;
private readonly int _end; // cache Offset + Count, since it's a little slow
private int _current;
internal Enumerator(ArraySegment<T> arraySegment)
{
Contract.Requires(arraySegment.Array != null);
Contract.Requires(arraySegment.Offset >= 0);
Contract.Requires(arraySegment.Count >= 0);
Contract.Requires(arraySegment.Offset + arraySegment.Count <= arraySegment.Array.Length);
_array = arraySegment.Array;
_start = arraySegment.Offset;
_end = arraySegment.Offset + arraySegment.Count;
_current = arraySegment.Offset - 1;
}
public bool MoveNext()
{
if (_current < _end)
{
_current++;
return (_current < _end);
}
return false;
}
public T Current
{
get
{
if (_current < _start)
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
if (_current >= _end)
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
return _array[_current];
}
}
object IEnumerator.Current => Current;
void IEnumerator.Reset()
{
_current = _start - 1;
}
public void Dispose()
{
}
}
}
}
| |
// Copyright 2011, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Author: api.anash@gmail.com (Anash P. Oommen)
using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.Common.Logging;
using Google.Api.Ads.Common.Util;
using Google.Api.Ads.Common.Util.Reports;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Net;
using System.Web;
using System.Xml;
namespace Google.Api.Ads.AdWords.Util.Reports {
/// <summary>
/// Defines report utility functions for the client library.
/// </summary>
public class ReportUtilities : AdsReportUtilities {
/// <summary>
/// Default report version.
/// </summary>
private const string DEFAULT_REPORT_VERSION = "v201506";
/// <summary>
/// Sets the reporting API version to use.
/// </summary>
private string reportVersion = DEFAULT_REPORT_VERSION;
/// <summary>
/// The report download url format for ad-hoc reports.
/// </summary>
private const string QUERY_REPORT_URL_FORMAT = "{0}/api/adwords/reportdownload/{1}?" +
"__fmt={2}";
/// <summary>
/// The report download url format for ad-hoc reports.
/// </summary>
private const string ADHOC_REPORT_URL_FORMAT = "{0}/api/adwords/reportdownload/{1}";
/// <summary>
/// The list of headers to mask in the logs.
/// </summary>
private readonly HashSet<string> HEADERS_TO_MASK = new HashSet<string> {
"developerToken", "Authorization"
};
/// <summary>
/// The AWQL query for downloading this report.
/// </summary>
private string query;
/// <summary>
/// The format in which the report is downloaded.
/// </summary>
private string format;
/// <summary>
/// The report definition for downloading this report.
/// </summary>
private IReportDefinition reportDefinition;
/// <summary>
/// True, if the user wants to use AWQL for downloading reports, false if
/// the user wants to use reportDefinition instead.
/// </summary>
private bool usesQuery = false;
/// <summary>
/// Initializes a new instance of the <see cref="ReportUtilities" /> class.
/// </summary>
/// <param name="user">AdWords user to be used along with this
/// utilities object.</param>
/// <param name="query">The AWQL for downloading reports.</param>
/// <param name="format">The report download format.</param>
public ReportUtilities(AdWordsUser user, string query, string format)
: this(user, DEFAULT_REPORT_VERSION, query, format) { }
/// <summary>
/// Initializes a new instance of the <see cref="ReportUtilities"/> class.
/// </summary>
/// <param name="user">AdWords user to be used along with this
/// utilities object.</param>
/// <param name="reportDefinition">The report definition.</param>
public ReportUtilities(AdWordsUser user, IReportDefinition reportDefinition)
: this(user, DEFAULT_REPORT_VERSION, reportDefinition) { }
/// <summary>
/// Initializes a new instance of the <see cref="ReportUtilities" /> class.
/// </summary>
/// <param name="user">AdWords user to be used along with this
/// utilities object.</param>
/// <param name="query">The AWQL for downloading reports.</param>
/// <param name="format">The report download format.</param>
/// <param name="reportVersion">The report version.</param>
public ReportUtilities(AdWordsUser user, string reportVersion, string query, string format)
: base(user) {
this.reportVersion = reportVersion;
this.query = query;
this.format = format;
this.usesQuery = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="ReportUtilities"/> class.
/// </summary>
/// <param name="user">AdWords user to be used along with this
/// utilities object.</param>
/// <param name="reportDefinition">The report definition.</param>
/// <param name="reportVersion">The report version.</param>
public ReportUtilities(AdWordsUser user, string reportVersion, IReportDefinition reportDefinition)
: base(user) {
this.reportVersion = reportVersion;
this.reportDefinition = reportDefinition;
this.usesQuery = false;
}
/// <summary>
/// Gets the report response.
/// </summary>
/// <returns>
/// The report response.
/// </returns>
protected override ReportResponse GetReport() {
AdWordsAppConfig config = (AdWordsAppConfig) User.Config;
string postBody;
string downloadUrl;
if (usesQuery) {
downloadUrl = string.Format(QUERY_REPORT_URL_FORMAT, config.AdWordsApiServer,
reportVersion, format);
postBody = string.Format("__rdquery={0}", HttpUtility.UrlEncode(query));
} else {
downloadUrl = string.Format(ADHOC_REPORT_URL_FORMAT, config.AdWordsApiServer,
reportVersion);
postBody = "__rdxml=" + HttpUtility.UrlEncode(ConvertDefinitionToXml(
reportDefinition));
}
return DownloadReport(downloadUrl, postBody);
}
/// <summary>
/// Downloads a report to stream.
/// </summary>
/// <param name="downloadUrl">The download url.</param>
/// <param name="postBody">The POST body.</param>
private ReportResponse DownloadReport(string downloadUrl, string postBody) {
AdWordsErrorHandler errorHandler = new AdWordsErrorHandler(this.User as AdWordsUser);
while (true) {
WebResponse response = null;
HttpWebRequest request = BuildRequest(downloadUrl, postBody);
LogEntry logEntry = new LogEntry(User.Config, new DefaultDateTimeProvider());
logEntry.LogRequest(request, postBody, HEADERS_TO_MASK);
try {
response = request.GetResponse();
logEntry.LogResponse(response, false, "Response truncated.");
logEntry.Flush();
return new ReportResponse(response);
} catch (WebException e) {
string contents = "";
Exception reportsException = null;
using (response = e.Response) {
try {
contents = MediaUtilities.GetStreamContentsAsString(
response.GetResponseStream());
} catch {
contents = e.Message;
}
logEntry.LogResponse(response, true, contents);
logEntry.Flush();
reportsException = ParseException(e, contents);
if (AdWordsErrorHandler.IsOAuthTokenExpiredError(reportsException)) {
reportsException = new AdWordsCredentialsExpiredException(
request.Headers["Authorization"]);
}
}
if (errorHandler.ShouldRetry(reportsException)) {
errorHandler.PrepareForRetry(reportsException);
} else {
throw reportsException;
}
}
}
}
/// <summary>
/// Builds an HTTP request for downloading reports.
/// </summary>
/// <param name="downloadUrl">The download url.</param>
/// <param name="postBody">The POST body.</param>
/// <returns>A webrequest to download reports.</returns>
private HttpWebRequest BuildRequest(string downloadUrl, string postBody) {
AdWordsAppConfig config = this.User.Config as AdWordsAppConfig;
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(downloadUrl);
request.Method = "POST";
request.Proxy = config.Proxy;
request.Timeout = config.Timeout;
request.UserAgent = config.GetUserAgent();
request.Headers.Add("clientCustomerId: " + config.ClientCustomerId);
request.ContentType = "application/x-www-form-urlencoded";
if (config.EnableGzipCompression) {
(request as HttpWebRequest).AutomaticDecompression = DecompressionMethods.GZip
| DecompressionMethods.Deflate;
} else {
(request as HttpWebRequest).AutomaticDecompression = DecompressionMethods.None;
}
if (this.User.OAuthProvider != null) {
request.Headers["Authorization"] = this.User.OAuthProvider.GetAuthHeader();
} else {
throw new AdWordsApiException(null, AdWordsErrorMessages.OAuthProviderCannotBeNull);
}
request.Headers.Add("developerToken: " + config.DeveloperToken);
// The client library will use only apiMode = true.
request.Headers.Add("apiMode", "true");
request.Headers.Add("skipReportHeader", config.SkipReportHeader.ToString().ToLower());
request.Headers.Add("skipReportSummary", config.SkipReportSummary.ToString().ToLower());
request.Headers.Add("skipColumnHeader", config.SkipColumnHeader.ToString().ToLower());
// Send the includeZeroImpressions header only if the user explicitly
// requested it through the config object.
if (config.IncludeZeroImpressions.HasValue) {
request.Headers.Add("includeZeroImpressions", config.IncludeZeroImpressions.ToString().
ToLower());
}
using (StreamWriter writer = new StreamWriter(request.GetRequestStream())) {
writer.Write(postBody);
}
return request;
}
/// <summary>
/// Parses the error response into an exception.
/// </summary>
/// <param name="errorsXml">The errors XML.</param>
/// <param name="e">The original exception.</param>
/// <returns>An AdWords Reports exception that represents the error.</returns>
private AdWordsReportsException ParseException(Exception e, string contents) {
List<ReportDownloadError> errorList = new List<ReportDownloadError>();
try {
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(contents);
XmlNodeList errorNodes = xDoc.DocumentElement.SelectNodes("ApiError");
foreach (XmlElement errorNode in errorNodes) {
ReportDownloadError downloadError = new ReportDownloadError();
downloadError.ErrorType = errorNode.SelectSingleNode("type").InnerText;
downloadError.FieldPath = errorNode.SelectSingleNode("fieldPath").InnerText;
downloadError.Trigger = errorNode.SelectSingleNode("trigger").InnerText;
errorList.Add(downloadError);
}
} catch {
}
AdWordsReportsException ex = new AdWordsReportsException(
"Report download errors occurred.", e);
ex.Errors = errorList.ToArray();
return ex;
}
/// <summary>
/// Converts the report definition to XML format.
/// </summary>
/// <param name="definition">The report definition.</param>
/// <returns>The report definition serialized as an XML string.</returns>
private string ConvertDefinitionToXml(IReportDefinition definition) {
string xml = SerializationUtilities.SerializeAsXmlText(definition).Replace(
"ReportDefinition", "reportDefinition");
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList xmlNodes = doc.SelectNodes("descendant::*");
foreach (XmlElement node in xmlNodes) {
node.RemoveAllAttributes();
}
return doc.OuterXml;
}
}
}
| |
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using CorDebugInterop;
using nanoFramework.Tools.Debugger;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace nanoFramework.Tools.VisualStudio.Extension
{
public class CorDebugEval : ICorDebugEval, ICorDebugEval2
{
const int SCRATCH_PAD_INDEX_NOT_INITIALIZED = -1;
bool _fActive;
CorDebugThread _threadReal;
CorDebugThread _threadVirtual;
CorDebugAppDomain _appDomain;
int _iScratchPad;
CorDebugValue _resultValue;
EvalResult _resultType;
bool _fException;
public enum EvalResult
{
NotFinished,
Complete,
Abort,
Exception,
}
public CorDebugEval (CorDebugThread thread)
{
_appDomain = thread.Chain.ActiveFrame.AppDomain;
_threadReal = thread;
_resultType = EvalResult.NotFinished;
ResetScratchPadLocation ();
}
public CorDebugThread ThreadVirtual
{
get { return _threadVirtual; }
}
public CorDebugThread ThreadReal
{
get { return _threadReal; }
}
public Engine Engine
{
get { return Process.Engine; }
}
public CorDebugProcess Process
{
get { return _threadReal.Process; }
}
public CorDebugAppDomain AppDomain
{
get { return _appDomain; }
}
private CorDebugValue GetResultValue ()
{
if (_resultValue == null)
{
_resultValue = Process.ScratchPad.GetValue (_iScratchPad, _appDomain);
}
return _resultValue;
}
private int GetScratchPadLocation ()
{
if (_iScratchPad == SCRATCH_PAD_INDEX_NOT_INITIALIZED)
{
_iScratchPad = Process.ScratchPad.ReserveScratchBlock ();
}
return _iScratchPad;
}
private void ResetScratchPadLocation()
{
_iScratchPad = SCRATCH_PAD_INDEX_NOT_INITIALIZED;
_resultValue = null;
}
public void StoppedOnUnhandledException()
{
/*
* store the fact that this eval ended with an exception
* the exception will be stored in the scratch pad by nanoCLR
* but the event to cpde should wait to be queued until the eval
* thread completes. At that time, the information is lost as to
* the fact that the result was an exception (rather than the function returning
* an object of type exception. Hence, this flag.
*/
_fException = true;
}
public void EndEval (EvalResult resultType, bool fSynchronousEval)
{
try
{
//This is used to avoid deadlock. Suspend commands synchronizes on this.Process
Process.SuspendCommands(true);
Debug.Assert(Utility.FImplies(fSynchronousEval, !_fActive));
if (fSynchronousEval || _fActive) //what to do if the eval isn't active anymore??
{
bool fKillThread = false;
if (_threadVirtual != null)
{
if (_threadReal.GetLastCorDebugThread() != _threadVirtual)
throw new ArgumentException();
_threadReal.RemoveVirtualThread(_threadVirtual);
}
//Stack frames don't appear if they are not refreshed
if (fSynchronousEval)
{
for (CorDebugThread thread = _threadReal; thread != null; thread = thread.NextThread)
{
thread.RefreshChain();
}
}
if(_fException)
{
resultType = EvalResult.Exception;
}
//Check to see if we are able to EndEval -- is this the last virtual thread?
_fActive = false;
_resultType = resultType;
switch (resultType)
{
case EvalResult.Complete:
Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackEval(_threadReal, this, ManagedCallbacks.ManagedCallbackEval.EventType.EvalComplete));
break;
case EvalResult.Exception:
Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackEval(_threadReal, this, ManagedCallbacks.ManagedCallbackEval.EventType.EvalException));
break;
case EvalResult.Abort:
fKillThread = true;
/* WARNING!!!!
* If we do not give VS a EvalComplete message within 3 seconds of them calling ICorDebugEval::Abort then VS will attempt a RudeAbort
* and will display a scary error message about a serious internal debugger error and ignore all future debugging requests, among other bad things.
*/
Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackEval(_threadReal, this, ManagedCallbacks.ManagedCallbackEval.EventType.EvalComplete));
break;
}
if (fKillThread && _threadVirtual != null)
{
Engine.KillThread(_threadVirtual.ID);
}
if (resultType == EvalResult.Abort)
{
Process.PauseExecution();
}
}
}
finally
{
Process.SuspendCommands(false);
}
}
private uint GetTypeDef_Index(CorElementType elementType, ICorDebugClass pElementClass)
{
uint tdIndex;
if (pElementClass != null)
{
tdIndex = ((CorDebugClass)pElementClass).TypeDef_Index;
}
else
{
CorDebugProcess.BuiltinType builtInType = Process.ResolveBuiltInType(elementType);
tdIndex = builtInType.GetClass(_appDomain).TypeDef_Index;
}
return tdIndex;
}
#region ICorDebugEval Members
int ICorDebugEval.IsActive (out int pbActive)
{
pbActive = Boolean.BoolToInt (_fActive);
return COM_HResults.S_OK;
}
int ICorDebugEval.GetThread( out ICorDebugThread ppThread )
{
ppThread = _threadReal;
return COM_HResults.S_OK;
}
int ICorDebugEval.GetResult( out ICorDebugValue ppResult )
{
switch (_resultType)
{
case EvalResult.Exception:
case EvalResult.Complete:
ppResult = GetResultValue ();
break;
default:
ppResult = null;
throw new ArgumentException ();
}
return COM_HResults.S_OK;
}
int ICorDebugEval.NewArray(CorElementType elementType, ICorDebugClass pElementClass, uint rank, ref uint dims, ref uint lowBounds)
{
if(rank != 1) return COM_HResults.E_FAIL;
Process.SetCurrentAppDomain(AppDomain);
uint tdIndex = GetTypeDef_Index(elementType, pElementClass);
Engine.AllocateArray(GetScratchPadLocation(), tdIndex, 1, (int)dims);
EndEval (EvalResult.Complete, true);
return COM_HResults.S_OK;
}
int ICorDebugEval.CallFunction( ICorDebugFunction pFunction, uint nArgs, ICorDebugValue[] ppArgs )
{
try
{
//CreateThread will cause a thread create event to occur. This is a virtual thread, so
//we need to suspend processing of nanoCLR commands until we have created the thread ourselves
//and the processing of a new virtual thread will be ignored.
Process.SuspendCommands (true);
//need to flush the breakpoints in case new breakpoints were waiting until process was resumed.
Process.UpdateBreakpoints ();
Debug.Assert (nArgs == ppArgs.Length);
Debug.Assert (Process.IsExecutionPaused);
CorDebugFunction function = (CorDebugFunction)pFunction;
uint md = function.MethodDef_Index;
if(function.IsVirtual && function.IsInstance)
{
Debug.Assert(nArgs > 0);
md = Engine.GetVirtualMethod(function.MethodDef_Index, ((CorDebugValue)ppArgs[0]).RuntimeValue);
}
Process.SetCurrentAppDomain(AppDomain);
//Send the selected thread ID to the device so calls that use Thread.CurrentThread work as the user expects.
uint pid = Engine.CreateThread(md, GetScratchPadLocation(), _threadReal.ID);
if (pid == uint.MaxValue)
{
throw new ArgumentException("nanoCLR cannot call this function. Possible reasons include: ByRef arguments not supported");
}
//If anything below fails, we need to clean up by killing the thread
if (nArgs > 0)
{
List<RuntimeValue> stackFrameValues = Engine.GetStackFrameValueAll(pid, 0, function.NumArg, Engine.StackValueKind.Argument);
for (int iArg = 0; iArg < nArgs; iArg++)
{
CorDebugValue valueSource = (CorDebugValue)ppArgs[iArg];
CorDebugValue valueDestination = CorDebugValue.CreateValue (stackFrameValues[iArg], _appDomain);
if (valueDestination.RuntimeValue.Assign(valueSource.RuntimeValue) == null)
{
throw new ArgumentException("nanoCLR cannot set argument " + iArg);
}
}
}
_threadVirtual = new CorDebugThread (Process, pid, this);
_threadReal.AttachVirtualThread (_threadVirtual);
Debug.Assert (!_fActive);
_fActive = true;
//It is possible that a hard breakpoint is hit, the first line of the function
//to evaluate. If that is the case, than breakpoints need to be drained so the
//breakpoint event is fired, to avoid a race condition, where cpde resumes
//execution to start the function eval before it gets the breakpoint event
//This is primarily due to the difference in behaviour of the nanoCLR and the desktop.
//In the desktop, the hard breakpoint will not get hit until execution is resumed.
//The nanoCLR can hit the breakpoint during the Thread_Create call.
Process.DrainBreakpoints();
}
finally
{
Process.SuspendCommands (false);
}
return COM_HResults.S_OK;
}
int ICorDebugEval.NewString( string @string )
{
Process.SetCurrentAppDomain(AppDomain);
//changing strings is dependant on this method working....
Engine.AllocateString(GetScratchPadLocation(), @string);
EndEval (EvalResult.Complete, true);
return COM_HResults.S_OK;
}
int ICorDebugEval.NewObjectNoConstructor( ICorDebugClass pClass )
{
Process.SetCurrentAppDomain(AppDomain);
Engine.AllocateObject(GetScratchPadLocation (), ((CorDebugClass)pClass).TypeDef_Index);
EndEval (EvalResult.Complete, true);
return COM_HResults.S_OK;
}
int ICorDebugEval.CreateValue(CorElementType elementType, ICorDebugClass pElementClass, out ICorDebugValue ppValue)
{
uint tdIndex = GetTypeDef_Index(elementType, pElementClass);
Debug.Assert(Utility.FImplies(pElementClass != null, elementType == CorElementType.ELEMENT_TYPE_VALUETYPE));
Process.SetCurrentAppDomain(AppDomain);
Engine.AllocateObject(GetScratchPadLocation (), tdIndex);
ppValue = GetResultValue ();
ResetScratchPadLocation ();
return COM_HResults.S_OK;
}
int ICorDebugEval.NewObject( ICorDebugFunction pConstructor, uint nArgs, ICorDebugValue[] ppArgs )
{
Debug.Assert (nArgs == ppArgs.Length);
CorDebugFunction f = (CorDebugFunction)pConstructor;
CorDebugClass c = f.Class;
Process.SetCurrentAppDomain(AppDomain);
Engine.AllocateObject(GetScratchPadLocation (), c.TypeDef_Index);
ICorDebugValue[] args = new ICorDebugValue[nArgs + 1];
args[0] = GetResultValue ();
ppArgs.CopyTo (args, 1);
((ICorDebugEval)this).CallFunction (pConstructor, (uint)args.Length, args);
return COM_HResults.S_OK;
}
int ICorDebugEval.Abort ()
{
EndEval (EvalResult.Abort, false);
return COM_HResults.S_OK;
}
#endregion
#region ICorDebugEval2 Members
int ICorDebugEval2.CallParameterizedFunction(ICorDebugFunction pFunction, uint nTypeArgs, ICorDebugType[] ppTypeArgs, uint nArgs, ICorDebugValue[] ppArgs)
{
return ((ICorDebugEval)this).CallFunction(pFunction, nArgs, ppArgs);
}
int ICorDebugEval2.CreateValueForType(ICorDebugType pType, out ICorDebugValue ppValue)
{
CorElementType type;
ICorDebugClass cls;
pType.GetType( out type );
pType.GetClass( out cls );
return ((ICorDebugEval)this).CreateValue(type, cls, out ppValue);
}
int ICorDebugEval2.NewParameterizedObject(ICorDebugFunction pConstructor, uint nTypeArgs, ICorDebugType[] ppTypeArgs, uint nArgs, ICorDebugValue[] ppArgs)
{
return ((ICorDebugEval)this).NewObject(pConstructor, nArgs, ppArgs);
}
int ICorDebugEval2.NewParameterizedObjectNoConstructor(ICorDebugClass pClass, uint nTypeArgs, ICorDebugType[] ppTypeArgs)
{
return ((ICorDebugEval)this).NewObjectNoConstructor(pClass);
}
int ICorDebugEval2.NewParameterizedArray(ICorDebugType pElementType, uint rank, ref uint dims, ref uint lowBounds)
{
CorElementType type;
ICorDebugClass cls;
pElementType.GetType(out type);
pElementType.GetClass(out cls);
return ((ICorDebugEval)this).NewArray(type, cls, rank, dims, lowBounds);
}
int ICorDebugEval2.NewStringWithLength(string @string, uint uiLength)
{
string strVal = @string.Substring(0, (int)uiLength);
return ((ICorDebugEval)this).NewString(strVal);
}
int ICorDebugEval2.RudeAbort()
{
return ((ICorDebugEval)this).Abort();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using ApiContractGenerator.MetadataReferenceResolvers;
using ApiContractGenerator.Model;
using ApiContractGenerator.Model.TypeReferences;
using ApiContractGenerator.Source;
namespace ApiContractGenerator
{
public sealed partial class IgnoredNamespaceFilter : IMetadataSource
{
private readonly IMetadataSource source;
private readonly IEnumerable<string> ignoredNamespaces;
private readonly IMetadataReferenceResolver metadataReferenceResolver;
public IgnoredNamespaceFilter(IMetadataSource source, IEnumerable<string> ignoredNamespaces, IMetadataReferenceResolver metadataReferenceResolver)
{
this.source = source ?? throw new ArgumentNullException(nameof(source));
this.ignoredNamespaces = ignoredNamespaces ?? throw new ArgumentNullException(nameof(ignoredNamespaces));
this.metadataReferenceResolver = metadataReferenceResolver ?? throw new ArgumentNullException(nameof(metadataReferenceResolver));
}
private IReadOnlyList<IMetadataNamespace> namespaces;
public IReadOnlyList<IMetadataNamespace> Namespaces
{
get => namespaces ?? (namespaces =
ReferencedIgnoredMetadataVisitor.CalculateNonignoredTransitiveClosure(source, ignoredNamespaces, metadataReferenceResolver));
}
public string AssemblyName => source.AssemblyName;
public byte[] PublicKey => source.PublicKey;
private sealed class ReferencedIgnoredMetadataVisitor
{
private readonly IReadOnlyDictionary<string, PartiallyIgnoredNamespaceBuilder> ignoredNamespaces;
private readonly IMetadataReferenceResolver metadataReferenceResolver;
private ReferencedIgnoredMetadataVisitor(IReadOnlyDictionary<string, PartiallyIgnoredNamespaceBuilder> ignoredNamespaces, IMetadataReferenceResolver metadataReferenceResolver)
{
this.ignoredNamespaces = ignoredNamespaces;
this.metadataReferenceResolver = metadataReferenceResolver;
}
public static IReadOnlyList<IMetadataNamespace> CalculateNonignoredTransitiveClosure(IMetadataSource source, IEnumerable<string> ignoredNamespaces, IMetadataReferenceResolver metadataReferenceResolver)
{
var regexBuilder = (StringBuilder)null;
foreach (var ignoredNamespace in ignoredNamespaces)
{
if (regexBuilder == null)
regexBuilder = new StringBuilder(@"\A(?:");
else
regexBuilder.Append('|');
regexBuilder.Append(Regex.Escape(ignoredNamespace));
}
if (regexBuilder == null) return source.Namespaces;
var namespaceIgnoreRegex = new Regex(regexBuilder.Append(@")(\Z|\.)").ToString(), RegexOptions.IgnoreCase);
var ignoredNamespaceLookup = new Dictionary<string, PartiallyIgnoredNamespaceBuilder>();
var includedNamespaces = new List<IMetadataNamespace>(source.Namespaces.Count);
foreach (var ns in source.Namespaces)
{
if (namespaceIgnoreRegex.IsMatch(ns.Name))
ignoredNamespaceLookup.Add(ns.Name, new PartiallyIgnoredNamespaceBuilder(ns));
else
includedNamespaces.Add(ns);
}
if (ignoredNamespaceLookup.Count != 0)
{
var visitor = new ReferencedIgnoredMetadataVisitor(ignoredNamespaceLookup, metadataReferenceResolver);
foreach (var ns in includedNamespaces)
{
var prefix = string.IsNullOrEmpty(ns.Name) ? null : TextNode.Root(ns.Name) + ".";
foreach (var type in ns.Types)
visitor.VisitNonignoredType(prefix + type.Name, type);
}
foreach (var ns in visitor.ignoredNamespaces.Values)
if (ns.Types.Count != 0)
includedNamespaces.Add(ns);
}
return includedNamespaces;
}
private bool ParameterIsNamedType(MetadataTypeReference type)
{
switch (type)
{
case TopLevelTypeReference _:
case NestedTypeReference _:
return true;
case GenericInstantiationTypeReference instantiation:
return ParameterIsNamedType(instantiation.TypeDefinition);
default:
return false;
}
}
private void VisitNonignoredType(TextNode typeName, IMetadataType type)
{
// Types should not be brought in via interface implementations;
// if interface implementations are the only thing bringing it in, that requires naming the ignored type.
// Generic type and method constraints don't need to be considered;
// they'll be picked up in an output position already by VisitTypeReference.
foreach (var field in type.Fields)
VisitTypeReference((typeName + ".") + field.Name, field.FieldType);
var @delegate = type as IMetadataDelegate;
if (@delegate != null)
{
// Delegate parameters don't require naming the ignored type in order to receive values from them.
// when passing the delegate as a parameter.
foreach (var parameter in @delegate.Parameters)
VisitTypeReference((typeName + " parameter ") + parameter.Name, parameter.ParameterType);
// Delegate returns don't require naming the ignored type in order to receive values from them
// when invoking them.
VisitTypeReference(typeName + " return type", @delegate.ReturnType);
}
foreach (var method in type.Methods) // Covers constructors, operators, properties and events
{
if (@delegate != null && (
method.Name == "Invoke"
|| method.Name == "BeginInvoke"
|| method.Name == "EndInvoke"))
{
continue;
}
var methodName = (typeName + ".") + method.Name;
foreach (var parameter in method.Parameters)
{
if (parameter.IsOut // Out var
|| (ParameterIsNamedType(parameter.ParameterType)
&& (!metadataReferenceResolver.TryGetIsDelegateType(parameter.ParameterType, out var isDelegate) // Better safe than sorry
|| isDelegate))) // Delegate parameter types can be syntactically inferred, so ignored types could be used without naming them
{
// For delegates we could be even smarter and skip if it has no byval parameters. Future enhancement.
VisitTypeReference((methodName + " parameter ") + parameter.Name, parameter.ParameterType);
}
// Otherwise, types should not be brought in via method parameters;
// if method parameters are the only thing bringing it in, that requires naming the ignored type.
}
VisitTypeReference(methodName + " return type", method.ReturnType);
}
if (type.BaseType != null) VisitTypeReference(typeName + " base type", type.BaseType);
foreach (var nestedType in type.NestedTypes)
VisitNonignoredType((typeName + ".") + nestedType.Name, nestedType);
}
private void VisitTypeReference(TextNode referencePath, MetadataTypeReference type)
{
for (;;)
{
switch (type)
{
case TopLevelTypeReference topLevel:
VisitTypeName(referencePath, topLevel.Namespace, topLevel.Name, Array.Empty<string>());
return;
case NestedTypeReference nested:
for (var nestedNames = new List<string>(); ;)
{
nestedNames.Add(nested.Name);
if (nested.DeclaringType is NestedTypeReference next)
{
nested = next;
}
else
{
var topLevel = (TopLevelTypeReference)nested.DeclaringType;
nestedNames.Reverse();
VisitTypeName(referencePath, topLevel.Namespace, topLevel.Name, nestedNames);
return;
}
}
case GenericInstantiationTypeReference genericInstantiation:
foreach (var argument in genericInstantiation.GenericTypeArguments)
VisitTypeReference(referencePath, argument);
type = genericInstantiation.TypeDefinition;
continue;
case ArrayTypeReference array:
type = array.ElementType;
continue;
case ByRefTypeReference byref:
type = byref.ElementType;
continue;
case PointerTypeReference pointer:
type = pointer.ElementType;
continue;
case GenericParameterTypeReference genericParameter:
foreach (var constraint in genericParameter.TypeParameter.TypeConstraints)
VisitTypeReference(referencePath + " generic constraint", constraint);
return;
case PrimitiveTypeReference _:
return;
default:
throw new NotImplementedException();
}
}
}
private void VisitTypeName(TextNode referencePath, string @namespace, string topLevelName, IReadOnlyList<string> nestedNames)
{
if (ignoredNamespaces.TryGetValue(@namespace, out var builder)
&& builder.TryUnignore(referencePath, topLevelName, nestedNames, out var unignoredType))
{
var typeName = !string.IsNullOrEmpty(@namespace)
? (TextNode.Root(@namespace) + ".") + topLevelName
: TextNode.Root(topLevelName);
foreach (var name in nestedNames)
typeName = (typeName + ".") + name;
VisitNonignoredType(typeName, unignoredType);
}
}
private sealed class PartiallyIgnoredNamespaceBuilder : IMetadataNamespace
{
private readonly IMetadataNamespace originalNamespace;
private readonly List<PartiallyIgnoredTypeBuilder> typeBuilders = new List<PartiallyIgnoredTypeBuilder>();
public PartiallyIgnoredNamespaceBuilder(IMetadataNamespace originalNamespace)
{
this.originalNamespace = originalNamespace;
}
public string Name => originalNamespace.Name;
public IReadOnlyList<IMetadataType> Types => typeBuilders;
/// <summary>
/// Returns <see langword="false"/> if the type is not found or if it has already been unignored.
/// </summary>
public bool TryUnignore(TextNode referencePath, string topLevelName, IReadOnlyList<string> nestedNames, out IMetadataType unignoredType)
{
var current = originalNamespace.Types.FirstOrDefault(_ => _.Name == topLevelName);
if (current != null)
{
if (nestedNames.Count == 0)
{
var builder = typeBuilders.FirstOrDefault(_ => _.Name == topLevelName);
if (builder == null)
typeBuilders.Add(builder = PartiallyIgnoredTypeBuilder.Create(current));
if (!builder.TryUnignore(referencePath))
{
unignoredType = null;
return false;
}
unignoredType = current;
return true;
}
else
{
var parentTypes = new List<IMetadataType>(nestedNames.Count);
foreach (var name in nestedNames)
{
parentTypes.Add(current);
current = current.NestedTypes.FirstOrDefault(_ => _.Name == name);
if (current == null)
{
unignoredType = null;
return false;
}
}
var builder = typeBuilders.FirstOrDefault(_ => _.Name == topLevelName);
if (builder == null)
typeBuilders.Add(builder = PartiallyIgnoredTypeBuilder.Create(parentTypes[0]));
if (builder.TryUnignoreNested(referencePath, parentTypes, 0, current))
{
unignoredType = current;
return true;
}
}
}
unignoredType = null;
return false;
}
}
private abstract class PartiallyIgnoredTypeBuilder : IMetadataType
{
private readonly IMetadataType original;
private readonly List<PartiallyIgnoredTypeBuilder> nestedTypeBuilders = new List<PartiallyIgnoredTypeBuilder>();
private readonly List<TextNode> referencePaths = new List<TextNode>();
private bool asDeclaringNameOnly = true;
private PartiallyIgnoredTypeBuilder(IMetadataType original)
{
this.original = original;
}
public static PartiallyIgnoredTypeBuilder Create(IMetadataType original)
{
switch (original)
{
case IMetadataClass @class:
return new PartiallyIgnoredClassBuilder(@class);
case IMetadataStruct @struct:
return new PartiallyIgnoredStructBuilder(@struct);
case IMetadataInterface @interface:
return new PartiallyIgnoredInterfaceBuilder(@interface);
case IMetadataEnum @enum:
return new PartiallyIgnoredEnumBuilder(@enum);
case IMetadataDelegate @delegate:
return new PartiallyIgnoredDelegateBuilder(@delegate);
default:
throw new NotImplementedException();
}
}
private sealed class PartiallyIgnoredClassBuilder : PartiallyIgnoredTypeBuilder, IMetadataClass
{
public PartiallyIgnoredClassBuilder(IMetadataClass original) : base(original)
{
}
public bool IsStatic => ((IMetadataClass)original).IsStatic;
public bool IsAbstract => ((IMetadataClass)original).IsAbstract;
public bool IsSealed => ((IMetadataClass)original).IsSealed;
}
private sealed class PartiallyIgnoredStructBuilder : PartiallyIgnoredTypeBuilder, IMetadataStruct
{
public PartiallyIgnoredStructBuilder(IMetadataStruct original) : base(original)
{
}
}
private sealed class PartiallyIgnoredInterfaceBuilder : PartiallyIgnoredTypeBuilder, IMetadataInterface
{
public PartiallyIgnoredInterfaceBuilder(IMetadataInterface original) : base(original)
{
}
}
private sealed class PartiallyIgnoredEnumBuilder : PartiallyIgnoredTypeBuilder, IMetadataEnum
{
public PartiallyIgnoredEnumBuilder(IMetadataEnum original) : base(original)
{
}
public MetadataTypeReference UnderlyingType => ((IMetadataEnum)original).UnderlyingType;
}
private sealed class PartiallyIgnoredDelegateBuilder : PartiallyIgnoredTypeBuilder, IMetadataDelegate
{
public PartiallyIgnoredDelegateBuilder(IMetadataDelegate original) : base(original)
{
}
public MetadataTypeReference ReturnType => ((IMetadataDelegate)original).ReturnType;
public IReadOnlyList<IMetadataAttribute> ReturnValueAttributes => ((IMetadataDelegate)original).ReturnValueAttributes;
public IReadOnlyList<IMetadataParameter> Parameters => ((IMetadataDelegate)original).Parameters;
}
public string Comment
{
get
{
if (asDeclaringNameOnly) return null;
var comment = new StringBuilder();
if (!string.IsNullOrWhiteSpace(original.Comment)) comment.AppendLine(original.Comment);
comment.Append("Warning; type cannot be ignored because it is referenced by:");
foreach (var path in referencePaths)
{
comment.AppendLine();
comment.Append(" - ");
foreach (var segment in TextNode.ToArray(path))
comment.Append(segment);
}
return comment.ToString();
}
}
public bool TryUnignore(TextNode referencePath)
{
referencePaths.Add(referencePath ?? throw new ArgumentNullException(nameof(referencePath)));
if (!asDeclaringNameOnly) return false;
asDeclaringNameOnly = false;
return true;
}
public bool TryUnignoreNested(TextNode referencePath, IReadOnlyList<IMetadataType> parentTypes, int parentIndex, IMetadataType typeToUnignore)
{
var nextParentIndex = parentIndex + 1;
if (nextParentIndex != parentTypes.Count)
{
var nextParent = parentTypes[nextParentIndex];
var builder = nestedTypeBuilders.FirstOrDefault(_ => _.Name == nextParent.Name);
if (builder == null)
nestedTypeBuilders.Add(builder = Create(nextParent));
return builder.TryUnignoreNested(referencePath, parentTypes, nextParentIndex, typeToUnignore);
}
else
{
var builder = nestedTypeBuilders.FirstOrDefault(_ => _.Name == typeToUnignore.Name);
if (builder == null)
nestedTypeBuilders.Add(builder = Create(typeToUnignore));
return builder.TryUnignore(referencePath);
}
}
public IReadOnlyList<IMetadataType> NestedTypes => nestedTypeBuilders;
public string Name => original.Name;
public MetadataVisibility Visibility => original.Visibility;
public IReadOnlyList<IMetadataGenericTypeParameter> GenericTypeParameters => original.GenericTypeParameters;
public IReadOnlyList<IMetadataAttribute> Attributes
{
get => asDeclaringNameOnly
? Array.Empty<IMetadataAttribute>()
: original.Attributes;
}
public MetadataTypeReference BaseType
{
get => asDeclaringNameOnly
? null
: original.BaseType;
}
public IReadOnlyList<MetadataTypeReference> InterfaceImplementations
{
get => asDeclaringNameOnly
? Array.Empty<MetadataTypeReference>()
: original.InterfaceImplementations;
}
private bool CouldBeInheritedByNonignoredType => original is IMetadataClass @class && !@class.IsStatic && !@class.IsSealed;
public IReadOnlyList<IMetadataField> Fields
{
get => asDeclaringNameOnly ? Array.Empty<IMetadataField>() :
CouldBeInheritedByNonignoredType ? original.Fields :
original.Fields.Where(_ => _.IsStatic == false).ToList();
}
public IReadOnlyList<IMetadataProperty> Properties
{
get => asDeclaringNameOnly ? Array.Empty<IMetadataProperty>() :
CouldBeInheritedByNonignoredType ? original.Properties :
original.Properties.Where(_ => _.GetAccessor?.IsStatic == false || _.SetAccessor?.IsStatic == false).ToList();
}
public IReadOnlyList<IMetadataEvent> Events
{
get => asDeclaringNameOnly ? Array.Empty<IMetadataEvent>() :
CouldBeInheritedByNonignoredType ? original.Events :
original.Events.Where(_ => _.AddAccessor?.IsStatic == false || _.RemoveAccessor?.IsStatic == false || _.RaiseAccessor?.IsStatic == false).ToList();
}
public IReadOnlyList<IMetadataMethod> Methods
{
get => asDeclaringNameOnly ? (IReadOnlyList<IMetadataMethod>)Array.Empty<IMetadataMethod>() :
CouldBeInheritedByNonignoredType ? original.Methods.Where(_ => _.Name != ".ctor").ToList() :
original.Methods.Where(_ => _.IsStatic == false && _.Name != ".ctor").ToList();
}
}
}
}
}
| |
// 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 Internal.Cryptography;
using Internal.Cryptography.Pal;
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Security;
using System.Text;
namespace System.Security.Cryptography.X509Certificates
{
public class X509Certificate2 : X509Certificate
{
private volatile byte[] _lazyRawData;
private volatile Oid _lazySignatureAlgorithm;
private volatile int _lazyVersion;
private volatile X500DistinguishedName _lazySubjectName;
private volatile X500DistinguishedName _lazyIssuerName;
private volatile PublicKey _lazyPublicKey;
private volatile AsymmetricAlgorithm _lazyPrivateKey;
private volatile X509ExtensionCollection _lazyExtensions;
public override void Reset()
{
_lazyRawData = null;
_lazySignatureAlgorithm = null;
_lazyVersion = 0;
_lazySubjectName = null;
_lazyIssuerName = null;
_lazyPublicKey = null;
_lazyPrivateKey = null;
_lazyExtensions = null;
base.Reset();
}
public X509Certificate2()
: base()
{
}
public X509Certificate2(byte[] rawData)
: base(rawData)
{
}
public X509Certificate2(byte[] rawData, string password)
: base(rawData, password)
{
}
[System.CLSCompliantAttribute(false)]
public X509Certificate2(byte[] rawData, SecureString password)
: base(rawData, password)
{
}
public X509Certificate2(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
: base(rawData, password, keyStorageFlags)
{
}
[System.CLSCompliantAttribute(false)]
public X509Certificate2(byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
: base(rawData, password, keyStorageFlags)
{
}
public X509Certificate2(IntPtr handle)
: base(handle)
{
}
internal X509Certificate2(ICertificatePal pal)
: base(pal)
{
}
public X509Certificate2(string fileName)
: base(fileName)
{
}
public X509Certificate2(string fileName, string password)
: base(fileName, password)
{
}
[System.CLSCompliantAttribute(false)]
public X509Certificate2(string fileName, SecureString password)
: base(fileName, password)
{
}
public X509Certificate2(string fileName, string password, X509KeyStorageFlags keyStorageFlags)
: base(fileName, password, keyStorageFlags)
{
}
[System.CLSCompliantAttribute(false)]
public X509Certificate2(string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
: base(fileName, password, keyStorageFlags)
{
}
public X509Certificate2(X509Certificate certificate)
: base(certificate)
{
}
protected X509Certificate2(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
public bool Archived
{
get
{
ThrowIfInvalid();
return Pal.Archived;
}
set
{
ThrowIfInvalid();
Pal.Archived = value;
}
}
public X509ExtensionCollection Extensions
{
get
{
ThrowIfInvalid();
X509ExtensionCollection extensions = _lazyExtensions;
if (extensions == null)
{
extensions = new X509ExtensionCollection();
foreach (X509Extension extension in Pal.Extensions)
{
X509Extension customExtension = CreateCustomExtensionIfAny(extension.Oid);
if (customExtension == null)
{
extensions.Add(extension);
}
else
{
customExtension.CopyFrom(extension);
extensions.Add(customExtension);
}
}
_lazyExtensions = extensions;
}
return extensions;
}
}
public string FriendlyName
{
get
{
ThrowIfInvalid();
return Pal.FriendlyName;
}
set
{
ThrowIfInvalid();
Pal.FriendlyName = value;
}
}
public bool HasPrivateKey
{
get
{
ThrowIfInvalid();
return Pal.HasPrivateKey;
}
}
public AsymmetricAlgorithm PrivateKey
{
get
{
ThrowIfInvalid();
if (!HasPrivateKey)
return null;
if (_lazyPrivateKey == null)
{
switch (GetKeyAlgorithm())
{
case Oids.RsaRsa:
_lazyPrivateKey = Pal.GetRSAPrivateKey();
break;
case Oids.DsaDsa:
_lazyPrivateKey = Pal.GetDSAPrivateKey();
break;
default:
// This includes ECDSA, because an Oids.Ecc key can be
// many different algorithm kinds, not necessarily with mutual exclusion.
//
// Plus, .NET Framework only supports RSA and DSA in this property.
throw new NotSupportedException(SR.NotSupported_KeyAlgorithm);
}
}
return _lazyPrivateKey;
}
set
{
throw new PlatformNotSupportedException();
}
}
public X500DistinguishedName IssuerName
{
get
{
ThrowIfInvalid();
X500DistinguishedName issuerName = _lazyIssuerName;
if (issuerName == null)
issuerName = _lazyIssuerName = Pal.IssuerName;
return issuerName;
}
}
public DateTime NotAfter
{
get { return GetNotAfter(); }
}
public DateTime NotBefore
{
get { return GetNotBefore(); }
}
public PublicKey PublicKey
{
get
{
ThrowIfInvalid();
PublicKey publicKey = _lazyPublicKey;
if (publicKey == null)
{
string keyAlgorithmOid = GetKeyAlgorithm();
byte[] parameters = GetKeyAlgorithmParameters();
byte[] keyValue = GetPublicKey();
Oid oid = new Oid(keyAlgorithmOid);
publicKey = _lazyPublicKey = new PublicKey(oid, new AsnEncodedData(oid, parameters), new AsnEncodedData(oid, keyValue));
}
return publicKey;
}
}
public byte[] RawData
{
get
{
ThrowIfInvalid();
byte[] rawData = _lazyRawData;
if (rawData == null)
{
rawData = _lazyRawData = Pal.RawData;
}
return rawData.CloneByteArray();
}
}
public string SerialNumber
{
get
{
byte[] serialNumber = GetSerialNumber();
Array.Reverse(serialNumber);
return serialNumber.ToHexStringUpper();
}
}
public Oid SignatureAlgorithm
{
get
{
ThrowIfInvalid();
Oid signatureAlgorithm = _lazySignatureAlgorithm;
if (signatureAlgorithm == null)
{
string oidValue = Pal.SignatureAlgorithm;
signatureAlgorithm = _lazySignatureAlgorithm = Oid.FromOidValue(oidValue, OidGroup.SignatureAlgorithm);
}
return signatureAlgorithm;
}
}
public X500DistinguishedName SubjectName
{
get
{
ThrowIfInvalid();
X500DistinguishedName subjectName = _lazySubjectName;
if (subjectName == null)
subjectName = _lazySubjectName = Pal.SubjectName;
return subjectName;
}
}
public string Thumbprint
{
get
{
byte[] thumbPrint = GetCertHash();
return thumbPrint.ToHexStringUpper();
}
}
public int Version
{
get
{
ThrowIfInvalid();
int version = _lazyVersion;
if (version == 0)
version = _lazyVersion = Pal.Version;
return version;
}
}
public static X509ContentType GetCertContentType(byte[] rawData)
{
if (rawData == null || rawData.Length == 0)
throw new ArgumentException(SR.Arg_EmptyOrNullArray, nameof(rawData));
return X509Pal.Instance.GetCertContentType(rawData);
}
public static X509ContentType GetCertContentType(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// Desktop compat: The desktop CLR expands the filename to a full path for the purpose of performing a CAS permission check. While CAS is not present here,
// we still need to call GetFullPath() so we get the same exception behavior if the fileName is bad.
string fullPath = Path.GetFullPath(fileName);
return X509Pal.Instance.GetCertContentType(fileName);
}
public string GetNameInfo(X509NameType nameType, bool forIssuer)
{
return Pal.GetNameInfo(nameType, forIssuer);
}
public override string ToString()
{
return base.ToString(fVerbose: true);
}
public override string ToString(bool verbose)
{
if (verbose == false || Pal == null)
return ToString();
StringBuilder sb = new StringBuilder();
// Version
sb.AppendLine("[Version]");
sb.Append(" V");
sb.Append(Version);
// Subject
sb.AppendLine();
sb.AppendLine();
sb.AppendLine("[Subject]");
sb.Append(" ");
sb.Append(SubjectName.Name);
string simpleName = GetNameInfo(X509NameType.SimpleName, false);
if (simpleName.Length > 0)
{
sb.AppendLine();
sb.Append(" ");
sb.Append("Simple Name: ");
sb.Append(simpleName);
}
string emailName = GetNameInfo(X509NameType.EmailName, false);
if (emailName.Length > 0)
{
sb.AppendLine();
sb.Append(" ");
sb.Append("Email Name: ");
sb.Append(emailName);
}
string upnName = GetNameInfo(X509NameType.UpnName, false);
if (upnName.Length > 0)
{
sb.AppendLine();
sb.Append(" ");
sb.Append("UPN Name: ");
sb.Append(upnName);
}
string dnsName = GetNameInfo(X509NameType.DnsName, false);
if (dnsName.Length > 0)
{
sb.AppendLine();
sb.Append(" ");
sb.Append("DNS Name: ");
sb.Append(dnsName);
}
// Issuer
sb.AppendLine();
sb.AppendLine();
sb.AppendLine("[Issuer]");
sb.Append(" ");
sb.Append(IssuerName.Name);
simpleName = GetNameInfo(X509NameType.SimpleName, true);
if (simpleName.Length > 0)
{
sb.AppendLine();
sb.Append(" ");
sb.Append("Simple Name: ");
sb.Append(simpleName);
}
emailName = GetNameInfo(X509NameType.EmailName, true);
if (emailName.Length > 0)
{
sb.AppendLine();
sb.Append(" ");
sb.Append("Email Name: ");
sb.Append(emailName);
}
upnName = GetNameInfo(X509NameType.UpnName, true);
if (upnName.Length > 0)
{
sb.AppendLine();
sb.Append(" ");
sb.Append("UPN Name: ");
sb.Append(upnName);
}
dnsName = GetNameInfo(X509NameType.DnsName, true);
if (dnsName.Length > 0)
{
sb.AppendLine();
sb.Append(" ");
sb.Append("DNS Name: ");
sb.Append(dnsName);
}
// Serial Number
sb.AppendLine();
sb.AppendLine();
sb.AppendLine("[Serial Number]");
sb.Append(" ");
sb.AppendLine(SerialNumber);
// NotBefore
sb.AppendLine();
sb.AppendLine("[Not Before]");
sb.Append(" ");
sb.AppendLine(FormatDate(NotBefore));
// NotAfter
sb.AppendLine();
sb.AppendLine("[Not After]");
sb.Append(" ");
sb.AppendLine(FormatDate(NotAfter));
// Thumbprint
sb.AppendLine();
sb.AppendLine("[Thumbprint]");
sb.Append(" ");
sb.AppendLine(Thumbprint);
// Signature Algorithm
sb.AppendLine();
sb.AppendLine("[Signature Algorithm]");
sb.Append(" ");
sb.Append(SignatureAlgorithm.FriendlyName);
sb.Append('(');
sb.Append(SignatureAlgorithm.Value);
sb.AppendLine(")");
// Public Key
sb.AppendLine();
sb.Append("[Public Key]");
// It could throw if it's some user-defined CryptoServiceProvider
try
{
PublicKey pubKey = PublicKey;
sb.AppendLine();
sb.Append(" ");
sb.Append("Algorithm: ");
sb.Append(pubKey.Oid.FriendlyName);
// So far, we only support RSACryptoServiceProvider & DSACryptoServiceProvider Keys
try
{
sb.AppendLine();
sb.Append(" ");
sb.Append("Length: ");
using (RSA pubRsa = this.GetRSAPublicKey())
{
if (pubRsa != null)
{
sb.Append(pubRsa.KeySize);
}
}
}
catch (NotSupportedException)
{
}
sb.AppendLine();
sb.Append(" ");
sb.Append("Key Blob: ");
sb.AppendLine(pubKey.EncodedKeyValue.Format(true));
sb.Append(" ");
sb.Append("Parameters: ");
sb.Append(pubKey.EncodedParameters.Format(true));
}
catch (CryptographicException)
{
}
// Private key
Pal.AppendPrivateKeyInfo(sb);
// Extensions
X509ExtensionCollection extensions = Extensions;
if (extensions.Count > 0)
{
sb.AppendLine();
sb.AppendLine();
sb.Append("[Extensions]");
foreach (X509Extension extension in extensions)
{
try
{
sb.AppendLine();
sb.Append("* ");
sb.Append(extension.Oid.FriendlyName);
sb.Append('(');
sb.Append(extension.Oid.Value);
sb.Append("):");
sb.AppendLine();
sb.Append(" ");
sb.Append(extension.Format(true));
}
catch (CryptographicException)
{
}
}
}
sb.AppendLine();
return sb.ToString();
}
public override void Import(byte[] rawData)
{
base.Import(rawData);
}
public override void Import(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
{
base.Import(rawData, password, keyStorageFlags);
}
[System.CLSCompliantAttribute(false)]
public override void Import(byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
{
base.Import(rawData, password, keyStorageFlags);
}
public override void Import(string fileName)
{
base.Import(fileName);
}
public override void Import(string fileName, string password, X509KeyStorageFlags keyStorageFlags)
{
base.Import(fileName, password, keyStorageFlags);
}
[System.CLSCompliantAttribute(false)]
public override void Import(string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
{
base.Import(fileName, password, keyStorageFlags);
}
public bool Verify()
{
ThrowIfInvalid();
using (var chain = new X509Chain())
{
// Use the default vales of chain.ChainPolicy including:
// RevocationMode = X509RevocationMode.Online
// RevocationFlag = X509RevocationFlag.ExcludeRoot
// VerificationFlags = X509VerificationFlags.NoFlag
// VerificationTime = DateTime.Now
// UrlRetrievalTimeout = new TimeSpan(0, 0, 0)
bool verified = chain.Build(this, throwOnException: false);
return verified;
}
}
private static X509Extension CreateCustomExtensionIfAny(Oid oid)
{
string oidValue = oid.Value;
switch (oidValue)
{
case Oids.BasicConstraints:
return X509Pal.Instance.SupportsLegacyBasicConstraintsExtension ?
new X509BasicConstraintsExtension() :
null;
case Oids.BasicConstraints2:
return new X509BasicConstraintsExtension();
case Oids.KeyUsage:
return new X509KeyUsageExtension();
case Oids.EnhancedKeyUsage:
return new X509EnhancedKeyUsageExtension();
case Oids.SubjectKeyIdentifier:
return new X509SubjectKeyIdentifierExtension();
default:
return null;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace GLTF
{
/// <summary>
/// Abstract class that stores a reference to the root GLTF object and an id
/// of an object of type T inside it.
/// </summary>
/// <typeparam name="T">The value type returned by the GLTFId reference.</typeparam>
public abstract class GLTFId<T>
{
public int Id;
public GLTFRoot Root;
public abstract T Value { get; }
public void Serialize(JsonWriter writer)
{
writer.WriteValue(Id);
}
}
public class AccessorId : GLTFId<Accessor>
{
public override Accessor Value
{
get { return Root.Accessors[Id]; }
}
public static AccessorId Deserialize(GLTFRoot root, JsonReader reader)
{
return new AccessorId
{
Id = reader.ReadAsInt32().Value,
Root = root
};
}
}
public class BufferId : GLTFId<Buffer>
{
public override Buffer Value
{
get { return Root.Buffers[Id]; }
}
public static BufferId Deserialize(GLTFRoot root, JsonReader reader)
{
return new BufferId
{
Id = reader.ReadAsInt32().Value,
Root = root
};
}
}
public class BufferViewId : GLTFId<BufferView>
{
public override BufferView Value
{
get { return Root.BufferViews[Id]; }
}
public static BufferViewId Deserialize(GLTFRoot root, JsonReader reader)
{
return new BufferViewId
{
Id = reader.ReadAsInt32().Value,
Root = root
};
}
}
public class CameraId : GLTFId<GLTFCamera>
{
public override GLTFCamera Value
{
get { return Root.Cameras[Id]; }
}
public static CameraId Deserialize(GLTFRoot root, JsonReader reader)
{
return new CameraId
{
Id = reader.ReadAsInt32().Value,
Root = root
};
}
}
public class ImageId : GLTFId<Image>
{
public override Image Value
{
get { return Root.Images[Id]; }
}
public static ImageId Deserialize(GLTFRoot root, JsonReader reader)
{
return new ImageId
{
Id = reader.ReadAsInt32().Value,
Root = root
};
}
}
public class MaterialId : GLTFId<Material>
{
public override Material Value
{
get { return Root.Materials[Id]; }
}
public static MaterialId Deserialize(GLTFRoot root, JsonReader reader)
{
return new MaterialId
{
Id = reader.ReadAsInt32().Value,
Root = root
};
}
}
public class MeshId : GLTFId<Mesh>
{
public override Mesh Value
{
get { return Root.Meshes[Id]; }
}
public static MeshId Deserialize(GLTFRoot root, JsonReader reader)
{
return new MeshId
{
Id = reader.ReadAsInt32().Value,
Root = root
};
}
}
public class NodeId : GLTFId<Node>
{
public override Node Value
{
get { return Root.Nodes[Id]; }
}
public static NodeId Deserialize(GLTFRoot root, JsonReader reader)
{
return new NodeId
{
Id = reader.ReadAsInt32().Value,
Root = root
};
}
public static List<NodeId> ReadList(GLTFRoot root, JsonReader reader)
{
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
{
throw new Exception("Invalid array.");
}
var list = new List<NodeId>();
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
var node = new NodeId
{
Id = int.Parse(reader.Value.ToString()),
Root = root
};
list.Add(node);
}
return list;
}
}
public class SamplerId : GLTFId<Sampler>
{
public override Sampler Value
{
get { return Root.Samplers[Id]; }
}
public static SamplerId Deserialize(GLTFRoot root, JsonReader reader)
{
return new SamplerId
{
Id = reader.ReadAsInt32().Value,
Root = root
};
}
}
public class SceneId : GLTFId<Scene>
{
public override Scene Value
{
get { return Root.Scenes[Id]; }
}
public static SceneId Deserialize(GLTFRoot root, JsonReader reader)
{
return new SceneId
{
Id = reader.ReadAsInt32().Value,
Root = root
};
}
}
public class SkinId : GLTFId<Skin>
{
public override Skin Value
{
get { return Root.Skins[Id]; }
}
public static SkinId Deserialize(GLTFRoot root, JsonReader reader)
{
return new SkinId
{
Id = reader.ReadAsInt32().Value,
Root = root
};
}
}
public class TextureId : GLTFId<Texture>
{
public override Texture Value
{
get { return Root.Textures[Id]; }
}
public static TextureId Deserialize(GLTFRoot root, JsonReader reader)
{
return new TextureId
{
Id = reader.ReadAsInt32().Value,
Root = root
};
}
}
}
| |
/*
* Copyright 2002-2015 Drew Noakes
*
* Modified by Yakov Danilov <yakodani@gmail.com> for Imazen LLC (Ported from Java to C#)
* 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.
*
* More information about this project is available at:
*
* https://drewnoakes.com/code/exif/
* https://github.com/drewnoakes/metadata-extractor
*/
using Com.Drew.Metadata;
using JetBrains.Annotations;
using Sharpen;
namespace Com.Drew.Metadata.Exif.Makernotes
{
/// <summary>
/// Provides human-readable string representations of tag values stored in a
/// <see cref="CanonMakernoteDirectory"/>
/// .
/// </summary>
/// <author>Drew Noakes https://drewnoakes.com</author>
public class CanonMakernoteDescriptor : TagDescriptor<CanonMakernoteDirectory>
{
public CanonMakernoteDescriptor([NotNull] CanonMakernoteDirectory directory)
: base(directory)
{
}
[CanBeNull]
public override string GetDescription(int tagType)
{
switch (tagType)
{
case CanonMakernoteDirectory.TagCanonSerialNumber:
{
return GetSerialNumberDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagFlashActivity:
{
return GetFlashActivityDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagFocusType:
{
return GetFocusTypeDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagDigitalZoom:
{
return GetDigitalZoomDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagQuality:
{
return GetQualityDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagMacroMode:
{
return GetMacroModeDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagSelfTimerDelay:
{
return GetSelfTimerDelayDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagFlashMode:
{
return GetFlashModeDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagContinuousDriveMode:
{
return GetContinuousDriveModeDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagFocusMode1:
{
return GetFocusMode1Description();
}
case CanonMakernoteDirectory.CameraSettings.TagImageSize:
{
return GetImageSizeDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagEasyShootingMode:
{
return GetEasyShootingModeDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagContrast:
{
return GetContrastDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagSaturation:
{
return GetSaturationDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagSharpness:
{
return GetSharpnessDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagIso:
{
return GetIsoDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagMeteringMode:
{
return GetMeteringModeDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagAfPointSelected:
{
return GetAfPointSelectedDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagExposureMode:
{
return GetExposureModeDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagLongFocalLength:
{
return GetLongFocalLengthDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagShortFocalLength:
{
return GetShortFocalLengthDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagFocalUnitsPerMm:
{
return GetFocalUnitsPerMillimetreDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagFlashDetails:
{
return GetFlashDetailsDescription();
}
case CanonMakernoteDirectory.CameraSettings.TagFocusMode2:
{
return GetFocusMode2Description();
}
case CanonMakernoteDirectory.FocalLength.TagWhiteBalance:
{
return GetWhiteBalanceDescription();
}
case CanonMakernoteDirectory.FocalLength.TagAfPointUsed:
{
return GetAfPointUsedDescription();
}
case CanonMakernoteDirectory.FocalLength.TagFlashBias:
{
return GetFlashBiasDescription();
}
default:
{
// It turns out that these values are dependent upon the camera model and therefore the below code was
// incorrect for some Canon models. This needs to be revisited.
// case TAG_CANON_CUSTOM_FUNCTION_LONG_EXPOSURE_NOISE_REDUCTION:
// return getLongExposureNoiseReductionDescription();
// case TAG_CANON_CUSTOM_FUNCTION_SHUTTER_AUTO_EXPOSURE_LOCK_BUTTONS:
// return getShutterAutoExposureLockButtonDescription();
// case TAG_CANON_CUSTOM_FUNCTION_MIRROR_LOCKUP:
// return getMirrorLockupDescription();
// case TAG_CANON_CUSTOM_FUNCTION_TV_AV_AND_EXPOSURE_LEVEL:
// return getTvAndAvExposureLevelDescription();
// case TAG_CANON_CUSTOM_FUNCTION_AF_ASSIST_LIGHT:
// return getAutoFocusAssistLightDescription();
// case TAG_CANON_CUSTOM_FUNCTION_SHUTTER_SPEED_IN_AV_MODE:
// return getShutterSpeedInAvModeDescription();
// case TAG_CANON_CUSTOM_FUNCTION_BRACKETING:
// return getAutoExposureBracketingSequenceAndAutoCancellationDescription();
// case TAG_CANON_CUSTOM_FUNCTION_SHUTTER_CURTAIN_SYNC:
// return getShutterCurtainSyncDescription();
// case TAG_CANON_CUSTOM_FUNCTION_AF_STOP:
// return getLensAutoFocusStopButtonDescription();
// case TAG_CANON_CUSTOM_FUNCTION_FILL_FLASH_REDUCTION:
// return getFillFlashReductionDescription();
// case TAG_CANON_CUSTOM_FUNCTION_MENU_BUTTON_RETURN:
// return getMenuButtonReturnPositionDescription();
// case TAG_CANON_CUSTOM_FUNCTION_SET_BUTTON_FUNCTION:
// return getSetButtonFunctionWhenShootingDescription();
// case TAG_CANON_CUSTOM_FUNCTION_SENSOR_CLEANING:
// return getSensorCleaningDescription();
return base.GetDescription(tagType);
}
}
}
[CanBeNull]
public virtual string GetSerialNumberDescription()
{
int? value = _directory.GetInteger(CanonMakernoteDirectory.TagCanonSerialNumber);
if (value == null)
{
return null;
}
return Sharpen.Extensions.StringFormat("%04X%05d", ((int)value >> 8) & unchecked((int)(0xFF)), (int)value & unchecked((int)(0xFF)));
}
/*
@Nullable
public String getLongExposureNoiseReductionDescription()
{
Integer value = _directory.getInteger(TAG_CANON_CUSTOM_FUNCTION_LONG_EXPOSURE_NOISE_REDUCTION);
if (value==null)
return null;
switch (value) {
case 0: return "Off";
case 1: return "On";
default: return "Unknown (" + value + ")";
}
}
@Nullable
public String getShutterAutoExposureLockButtonDescription()
{
Integer value = _directory.getInteger(TAG_CANON_CUSTOM_FUNCTION_SHUTTER_AUTO_EXPOSURE_LOCK_BUTTONS);
if (value==null)
return null;
switch (value) {
case 0: return "AF/AE lock";
case 1: return "AE lock/AF";
case 2: return "AF/AF lock";
case 3: return "AE+release/AE+AF";
default: return "Unknown (" + value + ")";
}
}
@Nullable
public String getMirrorLockupDescription()
{
Integer value = _directory.getInteger(TAG_CANON_CUSTOM_FUNCTION_MIRROR_LOCKUP);
if (value==null)
return null;
switch (value) {
case 0: return "Disabled";
case 1: return "Enabled";
default: return "Unknown (" + value + ")";
}
}
@Nullable
public String getTvAndAvExposureLevelDescription()
{
Integer value = _directory.getInteger(TAG_CANON_CUSTOM_FUNCTION_TV_AV_AND_EXPOSURE_LEVEL);
if (value==null)
return null;
switch (value) {
case 0: return "1/2 stop";
case 1: return "1/3 stop";
default: return "Unknown (" + value + ")";
}
}
@Nullable
public String getAutoFocusAssistLightDescription()
{
Integer value = _directory.getInteger(TAG_CANON_CUSTOM_FUNCTION_AF_ASSIST_LIGHT);
if (value==null)
return null;
switch (value) {
case 0: return "On (Auto)";
case 1: return "Off";
default: return "Unknown (" + value + ")";
}
}
@Nullable
public String getShutterSpeedInAvModeDescription()
{
Integer value = _directory.getInteger(TAG_CANON_CUSTOM_FUNCTION_SHUTTER_SPEED_IN_AV_MODE);
if (value==null)
return null;
switch (value) {
case 0: return "Automatic";
case 1: return "1/200 (fixed)";
default: return "Unknown (" + value + ")";
}
}
@Nullable
public String getAutoExposureBracketingSequenceAndAutoCancellationDescription()
{
Integer value = _directory.getInteger(TAG_CANON_CUSTOM_FUNCTION_BRACKETING);
if (value==null)
return null;
switch (value) {
case 0: return "0,-,+ / Enabled";
case 1: return "0,-,+ / Disabled";
case 2: return "-,0,+ / Enabled";
case 3: return "-,0,+ / Disabled";
default: return "Unknown (" + value + ")";
}
}
@Nullable
public String getShutterCurtainSyncDescription()
{
Integer value = _directory.getInteger(TAG_CANON_CUSTOM_FUNCTION_SHUTTER_CURTAIN_SYNC);
if (value==null)
return null;
switch (value) {
case 0: return "1st Curtain Sync";
case 1: return "2nd Curtain Sync";
default: return "Unknown (" + value + ")";
}
}
@Nullable
public String getLensAutoFocusStopButtonDescription()
{
Integer value = _directory.getInteger(TAG_CANON_CUSTOM_FUNCTION_AF_STOP);
if (value==null)
return null;
switch (value) {
case 0: return "AF stop";
case 1: return "Operate AF";
case 2: return "Lock AE and start timer";
default: return "Unknown (" + value + ")";
}
}
@Nullable
public String getFillFlashReductionDescription()
{
Integer value = _directory.getInteger(TAG_CANON_CUSTOM_FUNCTION_FILL_FLASH_REDUCTION);
if (value==null)
return null;
switch (value) {
case 0: return "Enabled";
case 1: return "Disabled";
default: return "Unknown (" + value + ")";
}
}
@Nullable
public String getMenuButtonReturnPositionDescription()
{
Integer value = _directory.getInteger(TAG_CANON_CUSTOM_FUNCTION_MENU_BUTTON_RETURN);
if (value==null)
return null;
switch (value) {
case 0: return "Top";
case 1: return "Previous (volatile)";
case 2: return "Previous";
default: return "Unknown (" + value + ")";
}
}
@Nullable
public String getSetButtonFunctionWhenShootingDescription()
{
Integer value = _directory.getInteger(TAG_CANON_CUSTOM_FUNCTION_SET_BUTTON_FUNCTION);
if (value==null)
return null;
switch (value) {
case 0: return "Not Assigned";
case 1: return "Change Quality";
case 2: return "Change ISO Speed";
case 3: return "Select Parameters";
default: return "Unknown (" + value + ")";
}
}
@Nullable
public String getSensorCleaningDescription()
{
Integer value = _directory.getInteger(TAG_CANON_CUSTOM_FUNCTION_SENSOR_CLEANING);
if (value==null)
return null;
switch (value) {
case 0: return "Disabled";
case 1: return "Enabled";
default: return "Unknown (" + value + ")";
}
}
*/
[CanBeNull]
public virtual string GetFlashBiasDescription()
{
int? value = _directory.GetInteger(CanonMakernoteDirectory.FocalLength.TagFlashBias);
if (value == null)
{
return null;
}
bool isNegative = false;
if (value > unchecked((int)(0xF000)))
{
isNegative = true;
value = unchecked((int)(0xFFFF)) - (int)value;
value++;
}
// this tag is interesting in that the values returned are:
// 0, 0.375, 0.5, 0.626, 1
// not
// 0, 0.33, 0.5, 0.66, 1
return ((isNegative) ? "-" : string.Empty) + Sharpen.Extensions.ConvertToString(value / 32f) + " EV";
}
[CanBeNull]
public virtual string GetAfPointUsedDescription()
{
int? value = _directory.GetInteger(CanonMakernoteDirectory.FocalLength.TagAfPointUsed);
if (value == null)
{
return null;
}
if (((int)value & unchecked((int)(0x7))) == 0)
{
return "Right";
}
else
{
if (((int)value & unchecked((int)(0x7))) == 1)
{
return "Centre";
}
else
{
if (((int)value & unchecked((int)(0x7))) == 2)
{
return "Left";
}
else
{
return "Unknown (" + value + ")";
}
}
}
}
[CanBeNull]
public virtual string GetWhiteBalanceDescription()
{
return GetIndexedDescription(CanonMakernoteDirectory.FocalLength.TagWhiteBalance, "Auto", "Sunny", "Cloudy", "Tungsten", "Florescent", "Flash", "Custom");
}
[CanBeNull]
public virtual string GetFocusMode2Description()
{
return GetIndexedDescription(CanonMakernoteDirectory.CameraSettings.TagFocusMode2, "Single", "Continuous");
}
[CanBeNull]
public virtual string GetFlashDetailsDescription()
{
int? value = _directory.GetInteger(CanonMakernoteDirectory.CameraSettings.TagFlashDetails);
if (value == null)
{
return null;
}
if ((((int)value >> 14) & 1) > 0)
{
return "External E-TTL";
}
if ((((int)value >> 13) & 1) > 0)
{
return "Internal flash";
}
if ((((int)value >> 11) & 1) > 0)
{
return "FP sync used";
}
if ((((int)value >> 4) & 1) > 0)
{
return "FP sync enabled";
}
return "Unknown (" + value + ")";
}
[CanBeNull]
public virtual string GetFocalUnitsPerMillimetreDescription()
{
int? value = _directory.GetInteger(CanonMakernoteDirectory.CameraSettings.TagFocalUnitsPerMm);
if (value == null)
{
return null;
}
if (value != 0)
{
return Sharpen.Extensions.ConvertToString((int)value);
}
else
{
return string.Empty;
}
}
[CanBeNull]
public virtual string GetShortFocalLengthDescription()
{
int? value = _directory.GetInteger(CanonMakernoteDirectory.CameraSettings.TagShortFocalLength);
if (value == null)
{
return null;
}
string units = GetFocalUnitsPerMillimetreDescription();
return Sharpen.Extensions.ConvertToString((int)value) + " " + units;
}
[CanBeNull]
public virtual string GetLongFocalLengthDescription()
{
int? value = _directory.GetInteger(CanonMakernoteDirectory.CameraSettings.TagLongFocalLength);
if (value == null)
{
return null;
}
string units = GetFocalUnitsPerMillimetreDescription();
return Sharpen.Extensions.ConvertToString((int)value) + " " + units;
}
[CanBeNull]
public virtual string GetExposureModeDescription()
{
return GetIndexedDescription(CanonMakernoteDirectory.CameraSettings.TagExposureMode, "Easy shooting", "Program", "Tv-priority", "Av-priority", "Manual", "A-DEP");
}
[CanBeNull]
public virtual string GetAfPointSelectedDescription()
{
return GetIndexedDescription(CanonMakernoteDirectory.CameraSettings.TagAfPointSelected, unchecked((int)(0x3000)), "None (MF)", "Auto selected", "Right", "Centre", "Left");
}
[CanBeNull]
public virtual string GetMeteringModeDescription()
{
return GetIndexedDescription(CanonMakernoteDirectory.CameraSettings.TagMeteringMode, 3, "Evaluative", "Partial", "Centre weighted");
}
[CanBeNull]
public virtual string GetIsoDescription()
{
int? value = _directory.GetInteger(CanonMakernoteDirectory.CameraSettings.TagIso);
if (value == null)
{
return null;
}
// Canon PowerShot S3 is special
int canonMask = unchecked((int)(0x4000));
if (((int)value & canonMask) > 0)
{
return string.Empty + ((int)value & ~canonMask);
}
switch (value)
{
case 0:
{
return "Not specified (see ISOSpeedRatings tag)";
}
case 15:
{
return "Auto";
}
case 16:
{
return "50";
}
case 17:
{
return "100";
}
case 18:
{
return "200";
}
case 19:
{
return "400";
}
default:
{
return "Unknown (" + value + ")";
}
}
}
[CanBeNull]
public virtual string GetSharpnessDescription()
{
int? value = _directory.GetInteger(CanonMakernoteDirectory.CameraSettings.TagSharpness);
if (value == null)
{
return null;
}
switch (value)
{
case unchecked((int)(0xFFFF)):
{
return "Low";
}
case unchecked((int)(0x000)):
{
return "Normal";
}
case unchecked((int)(0x001)):
{
return "High";
}
default:
{
return "Unknown (" + value + ")";
}
}
}
[CanBeNull]
public virtual string GetSaturationDescription()
{
int? value = _directory.GetInteger(CanonMakernoteDirectory.CameraSettings.TagSaturation);
if (value == null)
{
return null;
}
switch (value)
{
case unchecked((int)(0xFFFF)):
{
return "Low";
}
case unchecked((int)(0x000)):
{
return "Normal";
}
case unchecked((int)(0x001)):
{
return "High";
}
default:
{
return "Unknown (" + value + ")";
}
}
}
[CanBeNull]
public virtual string GetContrastDescription()
{
int? value = _directory.GetInteger(CanonMakernoteDirectory.CameraSettings.TagContrast);
if (value == null)
{
return null;
}
switch (value)
{
case unchecked((int)(0xFFFF)):
{
return "Low";
}
case unchecked((int)(0x000)):
{
return "Normal";
}
case unchecked((int)(0x001)):
{
return "High";
}
default:
{
return "Unknown (" + value + ")";
}
}
}
[CanBeNull]
public virtual string GetEasyShootingModeDescription()
{
return GetIndexedDescription(CanonMakernoteDirectory.CameraSettings.TagEasyShootingMode, "Full auto", "Manual", "Landscape", "Fast shutter", "Slow shutter", "Night", "B&W", "Sepia", "Portrait", "Sports", "Macro / Closeup", "Pan focus");
}
[CanBeNull]
public virtual string GetImageSizeDescription()
{
return GetIndexedDescription(CanonMakernoteDirectory.CameraSettings.TagImageSize, "Large", "Medium", "Small");
}
[CanBeNull]
public virtual string GetFocusMode1Description()
{
return GetIndexedDescription(CanonMakernoteDirectory.CameraSettings.TagFocusMode1, "One-shot", "AI Servo", "AI Focus", "Manual Focus", "Single", "Continuous", "Manual Focus");
}
// TODO should check field 32 here (FOCUS_MODE_2)
[CanBeNull]
public virtual string GetContinuousDriveModeDescription()
{
int? value = _directory.GetInteger(CanonMakernoteDirectory.CameraSettings.TagContinuousDriveMode);
if (value == null)
{
return null;
}
switch (value)
{
case 0:
{
int? delay = _directory.GetInteger(CanonMakernoteDirectory.CameraSettings.TagSelfTimerDelay);
if (delay != null)
{
return delay == 0 ? "Single shot" : "Single shot with self-timer";
}
goto case 1;
}
case 1:
{
return "Continuous";
}
}
return "Unknown (" + value + ")";
}
[CanBeNull]
public virtual string GetFlashModeDescription()
{
int? value = _directory.GetInteger(CanonMakernoteDirectory.CameraSettings.TagFlashMode);
if (value == null)
{
return null;
}
switch (value)
{
case 0:
{
return "No flash fired";
}
case 1:
{
return "Auto";
}
case 2:
{
return "On";
}
case 3:
{
return "Red-eye reduction";
}
case 4:
{
return "Slow-synchro";
}
case 5:
{
return "Auto and red-eye reduction";
}
case 6:
{
return "On and red-eye reduction";
}
case 16:
{
// note: this value not set on Canon D30
return "External flash";
}
default:
{
return "Unknown (" + value + ")";
}
}
}
[CanBeNull]
public virtual string GetSelfTimerDelayDescription()
{
int? value = _directory.GetInteger(CanonMakernoteDirectory.CameraSettings.TagSelfTimerDelay);
if (value == null)
{
return null;
}
if (value == 0)
{
return "Self timer not used";
}
else
{
// TODO find an image that tests this calculation
return Sharpen.Extensions.ConvertToString((double)value * 0.1d) + " sec";
}
}
[CanBeNull]
public virtual string GetMacroModeDescription()
{
return GetIndexedDescription(CanonMakernoteDirectory.CameraSettings.TagMacroMode, 1, "Macro", "Normal");
}
[CanBeNull]
public virtual string GetQualityDescription()
{
return GetIndexedDescription(CanonMakernoteDirectory.CameraSettings.TagQuality, 2, "Normal", "Fine", null, "Superfine");
}
[CanBeNull]
public virtual string GetDigitalZoomDescription()
{
return GetIndexedDescription(CanonMakernoteDirectory.CameraSettings.TagDigitalZoom, "No digital zoom", "2x", "4x");
}
[CanBeNull]
public virtual string GetFocusTypeDescription()
{
int? value = _directory.GetInteger(CanonMakernoteDirectory.CameraSettings.TagFocusType);
if (value == null)
{
return null;
}
switch (value)
{
case 0:
{
return "Manual";
}
case 1:
{
return "Auto";
}
case 3:
{
return "Close-up (Macro)";
}
case 8:
{
return "Locked (Pan Mode)";
}
default:
{
return "Unknown (" + value + ")";
}
}
}
[CanBeNull]
public virtual string GetFlashActivityDescription()
{
return GetIndexedDescription(CanonMakernoteDirectory.CameraSettings.TagFlashActivity, "Flash did not fire", "Flash fired");
}
}
}
| |
// 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.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics.X86;
using System.Runtime.Intrinsics;
namespace IntelHardwareIntrinsicTest
{
class Program
{
const int Pass = 100;
const int Fail = 0;
static unsafe int Main(string[] args)
{
int testResult = Pass;
if (Avx.IsSupported)
{
using (TestTable<float> floatTable = new TestTable<float>(new float[8] { 1, -5, 100, 0, 1, -5, 100, 0 }, new float[8] { 22, -5, -50, 0, 22, -1, -50, 0 }, new float[8]))
using (TestTable<double> doubleTable = new TestTable<double>(new double[4] { 1, -5, 100, 0 }, new double[4] { 1, 1, 50, 0 }, new double[4]))
{
var vf1 = Unsafe.Read<Vector128<float>>(floatTable.inArray1Ptr);
var vf2 = Unsafe.Read<Vector128<float>>(floatTable.inArray2Ptr);
var vf3 = Avx.CompareScalar(vf1, vf2, FloatComparisonMode.EqualOrderedNonSignaling);
Unsafe.Write(floatTable.outArrayPtr, vf3);
var vd1 = Unsafe.Read<Vector128<double>>(doubleTable.inArray1Ptr);
var vd2 = Unsafe.Read<Vector128<double>>(doubleTable.inArray2Ptr);
var vd3 = Avx.CompareScalar(vd1, vd2, FloatComparisonMode.EqualOrderedNonSignaling);
Unsafe.Write(doubleTable.outArrayPtr, vd3);
if (BitConverter.SingleToInt32Bits(floatTable.outArray[0]) != (floatTable.inArray1[0] == floatTable.inArray2[0] ? -1 : 0))
{
Console.WriteLine("Avx CompareScalar failed on float:");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
return Fail;
}
for (int i = 1; i < 4; i++)
{
if (floatTable.outArray[i] != floatTable.inArray1[i])
{
Console.WriteLine("Avx CompareScalar failed on float:");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
return Fail;
}
}
if (BitConverter.DoubleToInt64Bits(doubleTable.outArray[0]) != (doubleTable.inArray1[0] == doubleTable.inArray2[0] ? -1 : 0))
{
Console.WriteLine("Avx CompareScalar failed on double:");
foreach (var item in doubleTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
return Fail;
}
for (int i = 1; i < 2; i++)
{
if (doubleTable.outArray[i] != doubleTable.inArray1[i])
{
Console.WriteLine("Avx CompareScalar failed on double:");
foreach (var item in doubleTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
return Fail;
}
}
try
{
var ve = Avx.CompareScalar(vf1, vf2, (FloatComparisonMode)32);
Unsafe.Write(floatTable.outArrayPtr, ve);
Console.WriteLine("Avx CompareScalar failed on float with out-of-range argument:");
return Fail;
}
catch (ArgumentOutOfRangeException e)
{
testResult = Pass;
}
try
{
var ve = Avx.CompareScalar(vd1, vd2, (FloatComparisonMode)32);
Unsafe.Write(floatTable.outArrayPtr, ve);
Console.WriteLine("Avx CompareScalar failed on double with out-of-range argument:");
return Fail;
}
catch (ArgumentOutOfRangeException e)
{
testResult = Pass;
}
try
{
var ve = typeof(Avx).GetMethod(nameof(Avx.CompareScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(FloatComparisonMode) })
.Invoke(null, new object[] {vf1, vf2, (FloatComparisonMode)32});
Console.WriteLine("Indirect-calling Avx CompareScalar failed on float with out-of-range argument:");
return Fail;
}
catch (System.Reflection.TargetInvocationException e)
{
if (e.InnerException is ArgumentOutOfRangeException)
{
testResult = Pass;
}
else
{
Console.WriteLine("Indirect-calling Avx CompareScalar failed on float with out-of-range argument:");
return Fail;
}
}
try
{
var ve = typeof(Avx).GetMethod(nameof(Avx.CompareScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(FloatComparisonMode) })
.Invoke(null, new object[] {vd1, vd2, (FloatComparisonMode)32});
Console.WriteLine("Indirect-calling Avx CompareScalar failed on double with out-of-range argument:");
return Fail;
}
catch (System.Reflection.TargetInvocationException e)
{
if (e.InnerException is ArgumentOutOfRangeException)
{
testResult = Pass;
}
else
{
Console.WriteLine("Indirect-calling Avx CompareScalar failed on double with out-of-range argument:");
return Fail;
}
}
}
}
return testResult;
}
public unsafe struct TestTable<T> : IDisposable where T : struct
{
public T[] inArray1;
public T[] inArray2;
public T[] outArray;
public void* inArray1Ptr => inHandle1.AddrOfPinnedObject().ToPointer();
public void* inArray2Ptr => inHandle2.AddrOfPinnedObject().ToPointer();
public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer();
GCHandle inHandle1;
GCHandle inHandle2;
GCHandle outHandle;
public TestTable(T[] a, T[] b, T[] c)
{
this.inArray1 = a;
this.inArray2 = b;
this.outArray = c;
inHandle1 = GCHandle.Alloc(inArray1, GCHandleType.Pinned);
inHandle2 = GCHandle.Alloc(inArray2, GCHandleType.Pinned);
outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned);
}
public bool CheckResult(Func<T, T, T, bool> check)
{
for (int i = 0; i < inArray1.Length; i++)
{
if (!check(inArray1[i], inArray2[i], outArray[i]))
{
return false;
}
}
return true;
}
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ScrollBarRenderer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System;
using System.Drawing;
using System.Windows.Forms.VisualStyles;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Win32;
/// <include file='doc\ScrollBarRenderer.uex' path='docs/doc[@for="ScrollBarRenderer"]/*' />
/// <devdoc>
/// <para>
/// This is a rendering class for the ScrollBar control.
/// </para>
/// </devdoc>
public sealed class ScrollBarRenderer {
//Make this per-thread, so that different threads can safely use these methods.
[ThreadStatic]
private static VisualStyleRenderer visualStyleRenderer = null;
//cannot instantiate
private ScrollBarRenderer() {
}
/// <include file='doc\ScrollBarRenderer.uex' path='docs/doc[@for="ScrollBarRenderer.IsSupported"]/*' />
/// <devdoc>
/// <para>
/// Returns true if this class is supported for the current OS and user/application settings,
/// otherwise returns false.
/// </para>
/// </devdoc>
public static bool IsSupported {
get {
return VisualStyleRenderer.IsSupported; // no downlevel support
}
}
/// <include file='doc\ScrollBarRenderer.uex' path='docs/doc[@for="ScrollBarRenderer.DrawArrowButton"]/*' />
/// <devdoc>
/// <para>
/// Renders a ScrollBar arrow button.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static void DrawArrowButton(Graphics g, Rectangle bounds, ScrollBarArrowButtonState state) {
InitializeRenderer(VisualStyleElement.ScrollBar.ArrowButton.LeftNormal, (int)state);
visualStyleRenderer.DrawBackground(g, bounds);
}
/// <include file='doc\ScrollBarRenderer.uex' path='docs/doc[@for="ScrollBarRenderer.DrawHorizontalThumb"]/*' />
/// <devdoc>
/// <para>
/// Renders a horizontal ScrollBar thumb.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static void DrawHorizontalThumb(Graphics g, Rectangle bounds, ScrollBarState state) {
InitializeRenderer(VisualStyleElement.ScrollBar.ThumbButtonHorizontal.Normal, (int)state);
visualStyleRenderer.DrawBackground(g, bounds);
}
/// <include file='doc\ScrollBarRenderer.uex' path='docs/doc[@for="ScrollBarRenderer.DrawVerticalThumb"]/*' />
/// <devdoc>
/// <para>
/// Renders a vertical ScrollBar thumb.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static void DrawVerticalThumb(Graphics g, Rectangle bounds, ScrollBarState state) {
InitializeRenderer(VisualStyleElement.ScrollBar.ThumbButtonVertical.Normal, (int)state);
visualStyleRenderer.DrawBackground(g, bounds);
}
/// <include file='doc\ScrollBarRenderer.uex' path='docs/doc[@for="ScrollBarRenderer.DrawHorizontalThumbGrip"]/*' />
/// <devdoc>
/// <para>
/// Renders a horizontal ScrollBar thumb grip.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static void DrawHorizontalThumbGrip(Graphics g, Rectangle bounds, ScrollBarState state) {
InitializeRenderer(VisualStyleElement.ScrollBar.GripperHorizontal.Normal, (int)state);
visualStyleRenderer.DrawBackground(g, bounds);
}
/// <include file='doc\ScrollBarRenderer.uex' path='docs/doc[@for="ScrollBarRenderer.DrawVerticalThumbGrip"]/*' />
/// <devdoc>
/// <para>
/// Renders a vertical ScrollBar thumb grip.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static void DrawVerticalThumbGrip(Graphics g, Rectangle bounds, ScrollBarState state) {
InitializeRenderer(VisualStyleElement.ScrollBar.GripperVertical.Normal, (int)state);
visualStyleRenderer.DrawBackground(g, bounds);
}
/// <include file='doc\ScrollBarRenderer.uex' path='docs/doc[@for="ScrollBarRenderer.DrawRightHorizontalTrack"]/*' />
/// <devdoc>
/// <para>
/// Renders a horizontal ScrollBar thumb.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static void DrawRightHorizontalTrack(Graphics g, Rectangle bounds, ScrollBarState state) {
InitializeRenderer(VisualStyleElement.ScrollBar.RightTrackHorizontal.Normal, (int)state);
visualStyleRenderer.DrawBackground(g, bounds);
}
/// <include file='doc\ScrollBarRenderer.uex' path='docs/doc[@for="ScrollBarRenderer.DrawLeftHorizontalTrack"]/*' />
/// <devdoc>
/// <para>
/// Renders a horizontal ScrollBar thumb.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static void DrawLeftHorizontalTrack(Graphics g, Rectangle bounds, ScrollBarState state) {
InitializeRenderer(VisualStyleElement.ScrollBar.LeftTrackHorizontal.Normal, (int)state);
visualStyleRenderer.DrawBackground(g, bounds);
}
/// <include file='doc\ScrollBarRenderer.uex' path='docs/doc[@for="ScrollBarRenderer.DrawUpperVerticalTrack"]/*' />
/// <devdoc>
/// <para>
/// Renders a vertical ScrollBar thumb in the center of the given bounds.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static void DrawUpperVerticalTrack(Graphics g, Rectangle bounds, ScrollBarState state) {
InitializeRenderer(VisualStyleElement.ScrollBar.UpperTrackVertical.Normal, (int)state);
visualStyleRenderer.DrawBackground(g, bounds);
}
/// <include file='doc\ScrollBarRenderer.uex' path='docs/doc[@for="ScrollBarRenderer.DrawLowerVerticalTrack"]/*' />
/// <devdoc>
/// <para>
/// Renders a vertical ScrollBar thumb in the center of the given bounds.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static void DrawLowerVerticalTrack(Graphics g, Rectangle bounds, ScrollBarState state) {
InitializeRenderer(VisualStyleElement.ScrollBar.LowerTrackVertical.Normal, (int)state);
visualStyleRenderer.DrawBackground(g, bounds);
}
/// <include file='doc\ScrollBarRenderer.uex' path='docs/doc[@for="ScrollBarRenderer.DrawSizeBox"]/*' />
/// <devdoc>
/// <para>
/// Renders a ScrollBar size box in the center of the given bounds.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static void DrawSizeBox(Graphics g, Rectangle bounds, ScrollBarSizeBoxState state) {
InitializeRenderer(VisualStyleElement.ScrollBar.SizeBox.LeftAlign, (int)state);
visualStyleRenderer.DrawBackground(g, bounds);
}
/// <include file='doc\ScrollBarRenderer.uex' path='docs/doc[@for="ScrollBarRenderer.GetThumbGripSize"]/*' />
/// <devdoc>
/// <para>
/// Returns the size of the ScrollBar thumb grip.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static Size GetThumbGripSize(Graphics g, ScrollBarState state) {
InitializeRenderer(VisualStyleElement.ScrollBar.GripperHorizontal.Normal, (int)state);
return visualStyleRenderer.GetPartSize(g, ThemeSizeType.True);
}
/// <include file='doc\ScrollBarRenderer.uex' path='docs/doc[@for="ScrollBarRenderer.GetSizeBoxSize"]/*' />
/// <devdoc>
/// <para>
/// Returns the size of the ScrollBar size box.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static Size GetSizeBoxSize(Graphics g, ScrollBarState state) {
InitializeRenderer(VisualStyleElement.ScrollBar.SizeBox.LeftAlign, (int)state);
return visualStyleRenderer.GetPartSize(g, ThemeSizeType.True);
}
private static void InitializeRenderer(VisualStyleElement element, int state) {
if (visualStyleRenderer == null) {
visualStyleRenderer = new VisualStyleRenderer(element.ClassName, element.Part, state);
}
else {
visualStyleRenderer.SetParameters(element.ClassName, element.Part, state);
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.DDF
{
using System;
using System.Text;
using NPOI.Util;
using System.IO;
/// <summary>
/// The escher client anchor specifies which rows and cells the shape is bound to as well as
/// the offsets within those cells. Each cell is 1024 units wide by 256 units long regardless
/// of the actual size of the cell. The EscherClientAnchorRecord only applies to the top-most
/// shapes. Shapes contained in groups are bound using the EscherChildAnchorRecords.
/// @author Glen Stampoultzis
/// </summary>
public class EscherClientAnchorRecord : EscherRecord
{
public const short RECORD_ID = unchecked((short)0xF010);
public const String RECORD_DESCRIPTION = "MsofbtClientAnchor";
/**
* bit[0] - fMove (1 bit): A bit that specifies whether the shape will be kept intact when the cells are moved.
* bit[1] - fSize (1 bit): A bit that specifies whether the shape will be kept intact when the cells are resized. If fMove is 1, the value MUST be 1.
* bit[2-4] - reserved, MUST be 0 and MUST be ignored
* bit[5-15]- Undefined and MUST be ignored.
*
* it can take values: 0, 2, 3
*/
private short field_1_flag;
private short field_2_col1;
private short field_3_dx1;
private short field_4_row1;
private short field_5_dy1;
private short field_6_col2;
private short field_7_dx2;
private short field_8_row2;
private short field_9_dy2;
private byte[] remainingData;
private bool shortRecord = false;
/// <summary>
/// This method deSerializes the record from a byte array.
/// </summary>
/// <param name="data">The byte array containing the escher record information</param>
/// <param name="offset">The starting offset into data</param>
/// <param name="recordFactory">May be null since this is not a container record.</param>
/// <returns>The number of bytes Read from the byte array.</returns>
public override int FillFields(byte[] data, int offset, IEscherRecordFactory recordFactory)
{
int bytesRemaining = ReadHeader(data, offset);
int pos = offset + 8;
int size = 0;
// Always find 4 two byte entries. Sometimes find 9
if (bytesRemaining == 4) // Word format only 4 bytes
{
// Not sure exactly what the format is quite yet, likely a reference to a PLC
}
else
{
field_1_flag = LittleEndian.GetShort(data, pos + size); size += 2;
field_2_col1 = LittleEndian.GetShort(data, pos + size); size += 2;
field_3_dx1 = LittleEndian.GetShort(data, pos + size); size += 2;
field_4_row1 = LittleEndian.GetShort(data, pos + size); size += 2;
if (bytesRemaining >= 18)
{
field_5_dy1 = LittleEndian.GetShort(data, pos + size); size += 2;
field_6_col2 = LittleEndian.GetShort(data, pos + size); size += 2;
field_7_dx2 = LittleEndian.GetShort(data, pos + size); size += 2;
field_8_row2 = LittleEndian.GetShort(data, pos + size); size += 2;
field_9_dy2 = LittleEndian.GetShort(data, pos + size); size += 2;
shortRecord = false;
}
else
{
shortRecord = true;
}
}
bytesRemaining -= size;
remainingData = new byte[bytesRemaining];
Array.Copy(data, pos + size, remainingData, 0, bytesRemaining);
return 8 + size + bytesRemaining;
}
/// <summary>
/// This method Serializes this escher record into a byte array.
/// </summary>
/// <param name="offset">The offset into data to start writing the record data to.</param>
/// <param name="data">The byte array to Serialize to.</param>
/// <param name="listener">a listener for begin and end serialization events.</param>
/// <returns>The number of bytes written.</returns>
public override int Serialize(int offset, byte[] data, EscherSerializationListener listener)
{
listener.BeforeRecordSerialize(offset, RecordId, this);
if (remainingData == null) remainingData = new byte[0];
LittleEndian.PutShort(data, offset, Options);
LittleEndian.PutShort(data, offset + 2, RecordId);
int remainingBytes = remainingData.Length + (shortRecord ? 8 : 18);
LittleEndian.PutInt(data, offset + 4, remainingBytes);
LittleEndian.PutShort(data, offset + 8, field_1_flag);
LittleEndian.PutShort(data, offset + 10, field_2_col1);
LittleEndian.PutShort(data, offset + 12, field_3_dx1);
LittleEndian.PutShort(data, offset + 14, field_4_row1);
if (!shortRecord)
{
LittleEndian.PutShort(data, offset + 16, field_5_dy1);
LittleEndian.PutShort(data, offset + 18, field_6_col2);
LittleEndian.PutShort(data, offset + 20, field_7_dx2);
LittleEndian.PutShort(data, offset + 22, field_8_row2);
LittleEndian.PutShort(data, offset + 24, field_9_dy2);
}
Array.Copy(remainingData, 0, data, offset + (shortRecord ? 16 : 26), remainingData.Length);
int pos = offset + 8 + (shortRecord ? 8 : 18) + remainingData.Length;
listener.AfterRecordSerialize(pos, RecordId, pos - offset, this);
return pos - offset;
}
/// <summary>
/// Returns the number of bytes that are required to Serialize this record.
/// </summary>
/// <value>Number of bytes</value>
public override int RecordSize
{
get { return 8 + (shortRecord ? 8 : 18) + (remainingData == null ? 0 : remainingData.Length); }
}
/// <summary>
/// The record id for this record.
/// </summary>
/// <value></value>
public override short RecordId
{
get { return RECORD_ID; }
}
/// <summary>
/// The short name for this record
/// </summary>
/// <value></value>
public override String RecordName
{
get { return "ClientAnchor"; }
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override String ToString()
{
String nl = Environment.NewLine;
String extraData;
using (MemoryStream b = new MemoryStream())
{
try
{
HexDump.Dump(this.remainingData, 0, b, 0);
//extraData = b.ToString();
extraData = Encoding.UTF8.GetString(b.ToArray());
}
catch (Exception)
{
extraData = "error\n";
}
return GetType().Name + ":" + nl +
" RecordId: 0x" + HexDump.ToHex(RECORD_ID) + nl +
" Version: 0x" + HexDump.ToHex(Version) + nl +
" Instance: 0x" + HexDump.ToHex(Instance) + nl +
" Flag: " + field_1_flag + nl +
" Col1: " + field_2_col1 + nl +
" DX1: " + field_3_dx1 + nl +
" Row1: " + field_4_row1 + nl +
" DY1: " + field_5_dy1 + nl +
" Col2: " + field_6_col2 + nl +
" DX2: " + field_7_dx2 + nl +
" Row2: " + field_8_row2 + nl +
" DY2: " + field_9_dy2 + nl +
" Extra Data:" + nl + extraData;
}
}
public override String ToXml(String tab)
{
String extraData;
using (MemoryStream b = new MemoryStream())
{
try
{
HexDump.Dump(this.remainingData, 0, b, 0);
extraData = HexDump.ToHex(b.ToArray());
}
catch (Exception)
{
extraData = "error\n";
}
if (extraData.Contains("No Data"))
{
extraData = "No Data";
}
StringBuilder builder = new StringBuilder();
builder.Append(tab)
.Append(FormatXmlRecordHeader(GetType().Name, HexDump.ToHex(RecordId),
HexDump.ToHex(Version), HexDump.ToHex(Instance)))
.Append(tab).Append("\t").Append("<Flag>").Append(field_1_flag).Append("</Flag>\n")
.Append(tab).Append("\t").Append("<Col1>").Append(field_2_col1).Append("</Col1>\n")
.Append(tab).Append("\t").Append("<DX1>").Append(field_3_dx1).Append("</DX1>\n")
.Append(tab).Append("\t").Append("<Row1>").Append(field_4_row1).Append("</Row1>\n")
.Append(tab).Append("\t").Append("<DY1>").Append(field_5_dy1).Append("</DY1>\n")
.Append(tab).Append("\t").Append("<Col2>").Append(field_6_col2).Append("</Col2>\n")
.Append(tab).Append("\t").Append("<DX2>").Append(field_7_dx2).Append("</DX2>\n")
.Append(tab).Append("\t").Append("<Row2>").Append(field_8_row2).Append("</Row2>\n")
.Append(tab).Append("\t").Append("<DY2>").Append(field_9_dy2).Append("</DY2>\n")
.Append(tab).Append("\t").Append("<ExtraData>").Append(extraData).Append("</ExtraData>\n");
builder.Append(tab).Append("</").Append(GetType().Name).Append(">\n");
return builder.ToString();
}
}
/// <summary>
/// Gets or sets the flag.
/// </summary>
/// <value>0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells.</value>
public short Flag
{
get { return field_1_flag; }
set { field_1_flag = value; }
}
/// <summary>
/// Gets or sets The column number for the top-left position. 0 based.
/// </summary>
/// <value>The col1.</value>
public short Col1
{
get { return field_2_col1; }
set { field_2_col1 = value; }
}
/// <summary>
/// Gets or sets The x offset within the top-left cell. Range is from 0 to 1023.
/// </summary>
/// <value>The DX1.</value>
public short Dx1
{
get { return field_3_dx1; }
set { field_3_dx1 = value; }
}
/// <summary>
/// Gets or sets The row number for the top-left corner of the shape.
/// </summary>
/// <value>The row1.</value>
public short Row1
{
get { return field_4_row1; }
set { this.field_4_row1 = value; }
}
/// <summary>
/// Gets or sets The y offset within the top-left corner of the current shape.
/// </summary>
/// <value>The dy1.</value>
public short Dy1
{
get { return field_5_dy1; }
set
{
shortRecord = false;
this.field_5_dy1 = value;
}
}
/// <summary>
/// Gets or sets The column of the bottom right corner of this shape.
/// </summary>
/// <value>The col2.</value>
public short Col2
{
get { return field_6_col2; }
set
{
shortRecord = false;
this.field_6_col2 = value;
}
}
/// <summary>
/// Gets or sets The x offset withing the cell for the bottom-right corner of this shape.
/// </summary>
/// <value>The DX2.</value>
public short Dx2
{
get { return field_7_dx2; }
set
{
shortRecord = false;
this.field_7_dx2 = value;
}
}
/// <summary>
/// Gets or sets The row number for the bottom-right corner of the current shape.
/// </summary>
/// <value>The row2.</value>
public short Row2
{
get { return field_8_row2; }
set
{
shortRecord = false;
this.field_8_row2 = value;
}
}
/// <summary>
/// Gets or sets The y offset withing the cell for the bottom-right corner of this shape.
/// </summary>
/// <value>The dy2.</value>
public short Dy2
{
get { return field_9_dy2; }
set { field_9_dy2 = value; }
}
/// <summary>
/// Gets or sets the remaining data.
/// </summary>
/// <value>The remaining data.</value>
public byte[] RemainingData
{
get { return remainingData; }
set { remainingData = value; }
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Linq;
using Python.Runtime.Native;
namespace Python.Runtime
{
/// <summary>
/// Performs data conversions between managed types and Python types.
/// </summary>
[SuppressUnmanagedCodeSecurity]
internal class Converter
{
private Converter()
{
}
private static NumberFormatInfo nfi;
private static Type objectType;
private static Type stringType;
private static Type singleType;
private static Type doubleType;
private static Type decimalType;
private static Type int16Type;
private static Type int32Type;
private static Type int64Type;
private static Type flagsType;
private static Type boolType;
private static Type typeType;
private static IntPtr dateTimeCtor;
private static IntPtr timeSpanCtor;
private static IntPtr tzInfoCtor;
private static IntPtr pyTupleNoKind;
private static IntPtr pyTupleKind;
private static StrPtr yearPtr;
private static StrPtr monthPtr;
private static StrPtr dayPtr;
private static StrPtr hourPtr;
private static StrPtr minutePtr;
private static StrPtr secondPtr;
private static StrPtr microsecondPtr;
private static StrPtr tzinfoPtr;
private static StrPtr hoursPtr;
private static StrPtr minutesPtr;
static Converter()
{
nfi = NumberFormatInfo.InvariantInfo;
objectType = typeof(Object);
stringType = typeof(String);
int16Type = typeof(Int16);
int32Type = typeof(Int32);
int64Type = typeof(Int64);
singleType = typeof(Single);
doubleType = typeof(Double);
decimalType = typeof(Decimal);
flagsType = typeof(FlagsAttribute);
boolType = typeof(Boolean);
typeType = typeof(Type);
IntPtr dateTimeMod = Runtime.PyImport_ImportModule("datetime");
if (dateTimeMod == null) throw new PythonException();
dateTimeCtor = Runtime.PyObject_GetAttrString(dateTimeMod, "datetime");
if (dateTimeCtor == null) throw new PythonException();
timeSpanCtor = Runtime.PyObject_GetAttrString(dateTimeMod, "timedelta");
if (timeSpanCtor == null) throw new PythonException();
IntPtr tzInfoMod = PythonEngine.ModuleFromString("custom_tzinfo", @"
from datetime import timedelta, tzinfo
class GMT(tzinfo):
def __init__(self, hours, minutes):
self.hours = hours
self.minutes = minutes
def utcoffset(self, dt):
return timedelta(hours=self.hours, minutes=self.minutes)
def tzname(self, dt):
return f'GMT {self.hours:00}:{self.minutes:00}'
def dst (self, dt):
return timedelta(0)").Handle;
tzInfoCtor = Runtime.PyObject_GetAttrString(tzInfoMod, "GMT");
if (tzInfoCtor == null) throw new PythonException();
pyTupleNoKind = Runtime.PyTuple_New(7);
pyTupleKind = Runtime.PyTuple_New(8);
yearPtr = new StrPtr("year", Encoding.UTF8);
monthPtr = new StrPtr("month", Encoding.UTF8);
dayPtr = new StrPtr("day", Encoding.UTF8);
hourPtr = new StrPtr("hour", Encoding.UTF8);
minutePtr = new StrPtr("minute", Encoding.UTF8);
secondPtr = new StrPtr("second", Encoding.UTF8);
microsecondPtr = new StrPtr("microsecond", Encoding.UTF8);
tzinfoPtr = new StrPtr("tzinfo", Encoding.UTF8);
hoursPtr = new StrPtr("hours", Encoding.UTF8);
minutesPtr = new StrPtr("minutes", Encoding.UTF8);
}
/// <summary>
/// Given a builtin Python type, return the corresponding CLR type.
/// </summary>
internal static Type GetTypeByAlias(IntPtr op)
{
if (op == Runtime.PyStringType)
return stringType;
if (op == Runtime.PyUnicodeType)
return stringType;
if (op == Runtime.PyIntType)
return int32Type;
if (op == Runtime.PyLongType)
return int64Type;
if (op == Runtime.PyFloatType)
return doubleType;
if (op == Runtime.PyBoolType)
return boolType;
if (op == Runtime.PyDecimalType)
return decimalType;
return null;
}
internal static IntPtr GetPythonTypeByAlias(Type op)
{
if (op == stringType)
return Runtime.PyUnicodeType;
if (op == int16Type)
return Runtime.PyIntType;
if (op == int32Type)
return Runtime.PyIntType;
if (op == int64Type)
return Runtime.PyIntType;
if (op == doubleType)
return Runtime.PyFloatType;
if (op == singleType)
return Runtime.PyFloatType;
if (op == boolType)
return Runtime.PyBoolType;
if (op == decimalType)
return Runtime.PyDecimalType;
return IntPtr.Zero;
}
/// <summary>
/// Return a Python object for the given native object, converting
/// basic types (string, int, etc.) into equivalent Python objects.
/// This always returns a new reference. Note that the System.Decimal
/// type has no Python equivalent and converts to a managed instance.
/// </summary>
internal static IntPtr ToPython<T>(T value)
{
return ToPython(value, typeof(T));
}
private static readonly Func<object, bool> IsTransparentProxy = GetIsTransparentProxy();
private static bool Never(object _) => false;
private static Func<object, bool> GetIsTransparentProxy()
{
var remoting = typeof(int).Assembly.GetType("System.Runtime.Remoting.RemotingServices");
if (remoting is null) return Never;
var isProxy = remoting.GetMethod("IsTransparentProxy", new[] { typeof(object) });
if (isProxy is null) return Never;
return (Func<object, bool>)Delegate.CreateDelegate(
typeof(Func<object, bool>), isProxy,
throwOnBindFailure: true);
}
internal static IntPtr ToPython(object value, Type type)
{
if (value is PyObject)
{
IntPtr handle = ((PyObject)value).Handle;
Runtime.XIncref(handle);
return handle;
}
IntPtr result = IntPtr.Zero;
// Null always converts to None in Python.
if (value == null)
{
result = Runtime.PyNone;
Runtime.XIncref(result);
return result;
}
var valueType = value.GetType();
if (Type.GetTypeCode(type) == TypeCode.Object && valueType != typeof(object)) {
var encoded = PyObjectConversions.TryEncode(value, type);
if (encoded != null) {
result = encoded.Handle;
Runtime.XIncref(result);
return result;
}
}
if (valueType.IsGenericType && value is IList && !(value is INotifyPropertyChanged))
{
using (var resultlist = new PyList())
{
foreach (object o in (IEnumerable)value)
{
using (var p = new PyObject(ToPython(o, o?.GetType())))
{
resultlist.Append(p);
}
}
Runtime.XIncref(resultlist.Handle);
return resultlist.Handle;
}
}
// it the type is a python subclass of a managed type then return the
// underlying python object rather than construct a new wrapper object.
var pyderived = value as IPythonDerivedType;
if (null != pyderived)
{
if (!IsTransparentProxy(pyderived))
return ClassDerivedObject.ToPython(pyderived);
}
// hmm - from Python, we almost never care what the declared
// type is. we'd rather have the object bound to the actual
// implementing class.
type = value.GetType();
TypeCode tc = Type.GetTypeCode(type);
switch (tc)
{
case TypeCode.Object:
if (value is TimeSpan)
{
var timespan = (TimeSpan)value;
IntPtr timeSpanArgs = Runtime.PyTuple_New(1);
Runtime.PyTuple_SetItem(timeSpanArgs, 0, Runtime.PyFloat_FromDouble(timespan.TotalDays));
var returnTimeSpan = Runtime.PyObject_CallObject(timeSpanCtor, timeSpanArgs);
// clean up
Runtime.XDecref(timeSpanArgs);
return returnTimeSpan;
}
return CLRObject.GetInstHandle(value, type);
case TypeCode.String:
return Runtime.PyUnicode_FromString((string)value);
case TypeCode.Int32:
return Runtime.PyInt_FromInt32((int)value);
case TypeCode.Boolean:
if ((bool)value)
{
Runtime.XIncref(Runtime.PyTrue);
return Runtime.PyTrue;
}
Runtime.XIncref(Runtime.PyFalse);
return Runtime.PyFalse;
case TypeCode.Byte:
return Runtime.PyInt_FromInt32((int)((byte)value));
case TypeCode.Char:
return Runtime.PyUnicode_FromOrdinal((int)((char)value));
case TypeCode.Int16:
return Runtime.PyInt_FromInt32((int)((short)value));
case TypeCode.Int64:
return Runtime.PyLong_FromLongLong((long)value);
case TypeCode.Single:
// return Runtime.PyFloat_FromDouble((double)((float)value));
string ss = ((float)value).ToString(nfi);
IntPtr ps = Runtime.PyString_FromString(ss);
NewReference op = Runtime.PyFloat_FromString(new BorrowedReference(ps));;
Runtime.XDecref(ps);
return op.DangerousMoveToPointerOrNull();
case TypeCode.Double:
return Runtime.PyFloat_FromDouble((double)value);
case TypeCode.SByte:
return Runtime.PyInt_FromInt32((int)((sbyte)value));
case TypeCode.UInt16:
return Runtime.PyInt_FromInt32((int)((ushort)value));
case TypeCode.UInt32:
return Runtime.PyLong_FromUnsignedLong((uint)value);
case TypeCode.UInt64:
return Runtime.PyLong_FromUnsignedLongLong((ulong)value);
case TypeCode.Decimal:
// C# decimal to python decimal has a big impact on performance
// so we will use C# double and python float
return Runtime.PyFloat_FromDouble(decimal.ToDouble((decimal)value));
case TypeCode.DateTime:
var datetime = (DateTime)value;
var size = datetime.Kind == DateTimeKind.Unspecified ? 7 : 8;
var dateTimeArgs = datetime.Kind == DateTimeKind.Unspecified ? pyTupleNoKind : pyTupleKind;
Runtime.PyTuple_SetItem(dateTimeArgs, 0, Runtime.PyInt_FromInt32(datetime.Year));
Runtime.PyTuple_SetItem(dateTimeArgs, 1, Runtime.PyInt_FromInt32(datetime.Month));
Runtime.PyTuple_SetItem(dateTimeArgs, 2, Runtime.PyInt_FromInt32(datetime.Day));
Runtime.PyTuple_SetItem(dateTimeArgs, 3, Runtime.PyInt_FromInt32(datetime.Hour));
Runtime.PyTuple_SetItem(dateTimeArgs, 4, Runtime.PyInt_FromInt32(datetime.Minute));
Runtime.PyTuple_SetItem(dateTimeArgs, 5, Runtime.PyInt_FromInt32(datetime.Second));
// datetime.datetime 6th argument represents micro seconds
var totalSeconds = datetime.TimeOfDay.TotalSeconds;
var microSeconds = Convert.ToInt32((totalSeconds - Math.Truncate(totalSeconds)) * 1000000);
if (microSeconds == 1000000) microSeconds = 999999;
Runtime.PyTuple_SetItem(dateTimeArgs, 6, Runtime.PyInt_FromInt32(microSeconds));
if (size == 8)
{
Runtime.PyTuple_SetItem(dateTimeArgs, 7, TzInfo(datetime.Kind));
}
var returnDateTime = Runtime.PyObject_CallObject(dateTimeCtor, dateTimeArgs);
return returnDateTime;
default:
if (value is IEnumerable)
{
using (var resultlist = new PyList())
{
foreach (object o in (IEnumerable)value)
{
using (var p = new PyObject(ToPython(o, o?.GetType())))
{
resultlist.Append(p);
}
}
Runtime.XIncref(resultlist.Handle);
return resultlist.Handle;
}
}
result = CLRObject.GetInstHandle(value, type);
return result;
}
}
private static IntPtr TzInfo(DateTimeKind kind)
{
if (kind == DateTimeKind.Unspecified) return Runtime.PyNone;
var offset = kind == DateTimeKind.Local ? DateTimeOffset.Now.Offset : TimeSpan.Zero;
IntPtr tzInfoArgs = Runtime.PyTuple_New(2);
Runtime.PyTuple_SetItem(tzInfoArgs, 0, Runtime.PyFloat_FromDouble(offset.Hours));
Runtime.PyTuple_SetItem(tzInfoArgs, 1, Runtime.PyFloat_FromDouble(offset.Minutes));
var returnValue = Runtime.PyObject_CallObject(tzInfoCtor, tzInfoArgs);
Runtime.XDecref(tzInfoArgs);
return returnValue;
}
/// <summary>
/// In a few situations, we don't have any advisory type information
/// when we want to convert an object to Python.
/// </summary>
internal static IntPtr ToPythonImplicit(object value)
{
if (value == null)
{
IntPtr result = Runtime.PyNone;
Runtime.XIncref(result);
return result;
}
return ToPython(value, objectType);
}
internal static bool ToManaged(IntPtr value, Type type,
out object result, bool setError)
{
var usedImplicit = false;
return ToManaged(value, type, out result, setError, out usedImplicit);
}
/// <summary>
/// Return a managed object for the given Python object, taking funny
/// byref types into account.
/// </summary>
/// <param name="value">A Python object</param>
/// <param name="type">The desired managed type</param>
/// <param name="result">Receives the managed object</param>
/// <param name="setError">If true, call <c>Exceptions.SetError</c> with the reason for failure.</param>
/// <returns>True on success</returns>
internal static bool ToManaged(IntPtr value, Type type,
out object result, bool setError, out bool usedImplicit)
{
if (type.IsByRef)
{
type = type.GetElementType();
}
return Converter.ToManagedValue(value, type, out result, setError, out usedImplicit);
}
internal static bool ToManagedValue(BorrowedReference value, Type obType,
out object result, bool setError)
{
var usedImplicit = false;
return ToManagedValue(value.DangerousGetAddress(), obType, out result, setError, out usedImplicit);
}
internal static bool ToManagedValue(IntPtr value, Type obType,
out object result, bool setError, out bool usedImplicit)
{
usedImplicit = false;
if (obType == typeof(PyObject))
{
Runtime.XIncref(value); // PyObject() assumes ownership
result = new PyObject(value);
return true;
}
if (obType.IsGenericType && Runtime.PyObject_TYPE(value) == Runtime.PyListType)
{
var typeDefinition = obType.GetGenericTypeDefinition();
if (typeDefinition == typeof(List<>) || typeDefinition == typeof(IEnumerable<>))
{
return ToList(value, obType, out result, setError);
}
}
// Common case: if the Python value is a wrapped managed object
// instance, just return the wrapped object.
var mt = ManagedType.GetManagedObject(value);
result = null;
if (mt != null)
{
if (mt is CLRObject co)
{
object tmp = co.inst;
var type = tmp.GetType();
if (obType.IsInstanceOfType(tmp) || IsSubclassOfRawGeneric(obType, type))
{
result = tmp;
return true;
}
else
{
// check implicit conversions that receive tmp type and return obType
var conversionMethod = type.GetMethod("op_Implicit", new[] { type });
if (conversionMethod != null && conversionMethod.ReturnType == obType)
{
try{
result = conversionMethod.Invoke(null, new[] { tmp });
usedImplicit = true;
return true;
}
catch
{
// Failed to convert using implicit conversion, must catch the error to stop program from exploding on Linux
Exceptions.RaiseTypeError($"Failed to implicitly convert {type} to {obType}");
return false;
}
}
}
if (setError)
{
string typeString = tmp is null ? "null" : tmp.GetType().ToString();
Exceptions.SetError(Exceptions.TypeError, $"{typeString} value cannot be converted to {obType}");
}
return false;
}
if (mt is ClassBase cb)
{
if (!cb.type.Valid)
{
Exceptions.SetError(Exceptions.TypeError, cb.type.DeletedMessage);
return false;
}
result = cb.type.Value;
return true;
}
// shouldn't happen
return false;
}
if (value == Runtime.PyNone && !obType.IsValueType)
{
result = null;
return true;
}
if (obType.IsGenericType && obType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
if( value == Runtime.PyNone )
{
result = null;
return true;
}
// Set type to underlying type
obType = obType.GetGenericArguments()[0];
}
if (obType.ContainsGenericParameters)
{
if (setError)
{
Exceptions.SetError(Exceptions.TypeError, $"Cannot create an instance of the open generic type {obType}");
}
return false;
}
if (obType.IsArray)
{
return ToArray(value, obType, out result, setError);
}
if (obType.IsEnum)
{
return ToEnum(value, obType, out result, setError, out usedImplicit);
}
// Conversion to 'Object' is done based on some reasonable default
// conversions (Python string -> managed string, Python int -> Int32 etc.).
if (obType == objectType)
{
if (Runtime.IsStringType(value))
{
return ToPrimitive(value, stringType, out result, setError, out usedImplicit);
}
if (Runtime.PyBool_Check(value))
{
return ToPrimitive(value, boolType, out result, setError, out usedImplicit);
}
if (Runtime.PyInt_Check(value))
{
return ToPrimitive(value, int32Type, out result, setError, out usedImplicit);
}
if (Runtime.PyLong_Check(value))
{
return ToPrimitive(value, int64Type, out result, setError, out usedImplicit);
}
if (Runtime.PyFloat_Check(value))
{
return ToPrimitive(value, doubleType, out result, setError, out usedImplicit);
}
// give custom codecs a chance to take over conversion of sequences
IntPtr pyType = Runtime.PyObject_TYPE(value);
if (PyObjectConversions.TryDecode(value, pyType, obType, out result))
{
return true;
}
if (Runtime.PySequence_Check(value))
{
return ToArray(value, typeof(object[]), out result, setError);
}
Runtime.XIncref(value); // PyObject() assumes ownership
result = new PyObject(value);
return true;
}
// Conversion to 'Type' is done using the same mappings as above for objects.
if (obType == typeType)
{
if (value == Runtime.PyStringType)
{
result = stringType;
return true;
}
if (value == Runtime.PyBoolType)
{
result = boolType;
return true;
}
if (value == Runtime.PyIntType)
{
result = int32Type;
return true;
}
if (value == Runtime.PyLongType)
{
result = int64Type;
return true;
}
if (value == Runtime.PyFloatType)
{
result = doubleType;
return true;
}
if (value == Runtime.PyListType || value == Runtime.PyTupleType)
{
result = typeof(object[]);
return true;
}
if (setError)
{
Exceptions.SetError(Exceptions.TypeError, "value cannot be converted to Type");
}
return false;
}
var underlyingType = Nullable.GetUnderlyingType(obType);
if (underlyingType != null)
{
return ToManagedValue(value, underlyingType, out result, setError, out usedImplicit);
}
TypeCode typeCode = Type.GetTypeCode(obType);
if (typeCode == TypeCode.Object)
{
IntPtr pyType = Runtime.PyObject_TYPE(value);
if (PyObjectConversions.TryDecode(value, pyType, obType, out result))
{
return true;
}
}
if (ToPrimitive(value, obType, out result, setError, out usedImplicit))
{
return true;
}
var opImplicit = obType.GetMethod("op_Implicit", new[] { obType });
if (opImplicit != null)
{
if (ToManagedValue(value, opImplicit.ReturnType, out result, setError, out usedImplicit))
{
opImplicit = obType.GetMethod("op_Implicit", new[] { result.GetType() });
if (opImplicit != null)
{
try
{
result = opImplicit.Invoke(null, new[] { result });
}
catch
{
// Failed to convert using implicit conversion, must catch the error to stop program from exploding on Linux
Exceptions.RaiseTypeError($"Failed to implicitly convert {result.GetType()} to {obType}");
return false;
}
}
return opImplicit != null;
}
}
return false;
}
/// Determine if the comparing class is a subclass of a generic type
private static bool IsSubclassOfRawGeneric(Type generic, Type comparingClass) {
// Check this is a raw generic type first
if(!generic.IsGenericType || !generic.ContainsGenericParameters){
return false;
}
// Ensure we have the full generic type definition or it won't match
generic = generic.GetGenericTypeDefinition();
// Loop for searching for generic match in inheritance tree of comparing class
// If we have reach null we don't have a match
while (comparingClass != null) {
// Check the input for generic type definition, if doesn't exist just use the class
var comparingClassGeneric = comparingClass.IsGenericType ? comparingClass.GetGenericTypeDefinition() : null;
// If the same as generic, this is a subclass return true
if (generic == comparingClassGeneric) {
return true;
}
// Step up the inheritance tree
comparingClass = comparingClass.BaseType;
}
// The comparing class is not based on the generic
return false;
}
internal delegate bool TryConvertFromPythonDelegate(IntPtr pyObj, out object result);
/// <summary>
/// Convert a Python value to an instance of a primitive managed type.
/// </summary>
private static bool ToPrimitive(IntPtr value, Type obType, out object result, bool setError, out bool usedImplicit)
{
TypeCode tc = Type.GetTypeCode(obType);
result = null;
IntPtr op = IntPtr.Zero;
usedImplicit = false;
switch (tc)
{
case TypeCode.Object:
if (obType == typeof(TimeSpan))
{
op = Runtime.PyObject_Str(value);
TimeSpan ts;
var arr = Runtime.GetManagedString(op).Split(',');
string sts = arr.Length == 1 ? arr[0] : arr[1];
if (!TimeSpan.TryParse(sts, out ts))
{
goto type_error;
}
Runtime.XDecref(op);
int days = 0;
if (arr.Length > 1)
{
if (!int.TryParse(arr[0].Split(' ')[0].Trim(), out days))
{
goto type_error;
}
}
result = ts.Add(TimeSpan.FromDays(days));
return true;
}
else if (obType.IsGenericType && obType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))
{
if (Runtime.PyDict_Check(value))
{
var typeArguments = obType.GenericTypeArguments;
if (typeArguments.Length != 2)
{
goto type_error;
}
IntPtr key, dicValue, pos;
// references returned through key, dicValue are borrowed.
if (Runtime.PyDict_Next(value, out pos, out key, out dicValue) != 0)
{
if (!ToManaged(key, typeArguments[0], out var convertedKey, setError, out usedImplicit))
{
goto type_error;
}
if (!ToManaged(dicValue, typeArguments[1], out var convertedValue, setError, out usedImplicit))
{
goto type_error;
}
result = Activator.CreateInstance(obType, convertedKey, convertedValue);
return true;
}
// and empty dictionary we can't create a key value pair from it
goto type_error;
}
}
break;
case TypeCode.String:
string st = Runtime.GetManagedString(value);
if (st == null)
{
goto type_error;
}
result = st;
return true;
case TypeCode.Int32:
{
// Python3 always use PyLong API
op = Runtime.PyNumber_Long(value);
if (op == IntPtr.Zero && Exceptions.ErrorOccurred())
{
goto convert_error;
}
nint num = Runtime.PyLong_AsSignedSize_t(op);
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
if (num > Int32.MaxValue || num < Int32.MinValue)
{
goto overflow;
}
result = (int)num;
return true;
}
case TypeCode.Boolean:
result = Runtime.PyObject_IsTrue(value) != 0;
return true;
case TypeCode.Byte:
{
if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
{
if (Runtime.PyBytes_Size(value) == 1)
{
op = Runtime.PyBytes_AS_STRING(value);
result = (byte)Marshal.ReadByte(op);
return true;
}
goto type_error;
}
nint num = Runtime.PyLong_AsSignedSize_t(value);
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
if (num > Byte.MaxValue || num < Byte.MinValue)
{
goto overflow;
}
result = (byte)num;
return true;
}
case TypeCode.SByte:
{
if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
{
if (Runtime.PyBytes_Size(value) == 1)
{
op = Runtime.PyBytes_AS_STRING(value);
result = (byte)Marshal.ReadByte(op);
return true;
}
goto type_error;
}
nint num = Runtime.PyLong_AsSignedSize_t(value);
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
if (num > SByte.MaxValue || num < SByte.MinValue)
{
goto overflow;
}
result = (sbyte)num;
return true;
}
case TypeCode.Char:
{
if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
{
if (Runtime.PyBytes_Size(value) == 1)
{
op = Runtime.PyBytes_AS_STRING(value);
result = (byte)Marshal.ReadByte(op);
return true;
}
goto type_error;
}
else if (Runtime.PyObject_TypeCheck(value, Runtime.PyUnicodeType))
{
if (Runtime.PyUnicode_GetSize(value) == 1)
{
op = Runtime.PyUnicode_AsUnicode(value);
Char[] buff = new Char[1];
Marshal.Copy(op, buff, 0, 1);
result = buff[0];
return true;
}
goto type_error;
}
nint num = Runtime.PyLong_AsSignedSize_t(value);
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
if (num > Char.MaxValue || num < Char.MinValue)
{
goto overflow;
}
result = (char)num;
return true;
}
case TypeCode.Int16:
{
op = Runtime.PyNumber_Long(value);
if (op == IntPtr.Zero && Exceptions.ErrorOccurred())
{
goto convert_error;
}
nint num = Runtime.PyLong_AsSignedSize_t(op);
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
if (num > Int16.MaxValue || num < Int16.MinValue)
{
goto overflow;
}
result = (short)num;
return true;
}
case TypeCode.Int64:
{
if (Runtime.Is32Bit)
{
if (!Runtime.PyLong_Check(value))
{
goto type_error;
}
long num = Runtime.PyExplicitlyConvertToInt64(value);
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
result = num;
return true;
}
else
{
op = Runtime.PyNumber_Long(value);
if (op == IntPtr.Zero && Exceptions.ErrorOccurred())
{
goto convert_error;
}
nint num = Runtime.PyLong_AsSignedSize_t(op);
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
result = (long)num;
return true;
}
}
case TypeCode.UInt16:
{
op = Runtime.PyNumber_Long(value);
if (op == IntPtr.Zero && Exceptions.ErrorOccurred())
{
goto convert_error;
}
nint num = Runtime.PyLong_AsSignedSize_t(op);
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
if (num > UInt16.MaxValue || num < UInt16.MinValue)
{
goto overflow;
}
result = (ushort)num;
return true;
}
case TypeCode.UInt32:
{
op = Runtime.PyNumber_Long(value);
if (op == IntPtr.Zero && Exceptions.ErrorOccurred())
{
goto convert_error;
}
nuint num = Runtime.PyLong_AsUnsignedSize_t(op);
if (num == unchecked((nuint)(-1)) && Exceptions.ErrorOccurred())
{
goto convert_error;
}
if (num > UInt32.MaxValue)
{
goto overflow;
}
result = (uint)num;
return true;
}
case TypeCode.UInt64:
{
op = Runtime.PyNumber_Long(value);
if (op == IntPtr.Zero && Exceptions.ErrorOccurred())
{
goto convert_error;
}
ulong num = Runtime.PyLong_AsUnsignedLongLong(op);
if (num == ulong.MaxValue && Exceptions.ErrorOccurred())
{
goto convert_error;
}
result = num;
return true;
}
case TypeCode.Single:
{
double num = Runtime.PyFloat_AsDouble(value);
if (num == -1.0 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
if (num > Single.MaxValue || num < Single.MinValue)
{
if (!double.IsInfinity(num))
{
goto overflow;
}
}
result = (float)num;
return true;
}
case TypeCode.Double:
{
double num = Runtime.PyFloat_AsDouble(value);
if (num == -1.0 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
result = num;
return true;
}
case TypeCode.Decimal:
op = Runtime.PyObject_Str(value);
decimal m;
var sm = Runtime.GetManagedSpan(op, out var newReference);
if (!Decimal.TryParse(sm, NumberStyles.Number | NumberStyles.AllowExponent, nfi, out m))
{
newReference.Dispose();
Runtime.XDecref(op);
goto type_error;
}
newReference.Dispose();
Runtime.XDecref(op);
result = m;
return true;
case TypeCode.DateTime:
var year = Runtime.PyObject_GetAttrString(value, yearPtr);
if (year == IntPtr.Zero || year == Runtime.PyNone)
{
Runtime.XDecref(year);
Exceptions.Clear();
// fallback to string parsing for types such as numpy
op = Runtime.PyObject_Str(value);
var sdt = Runtime.GetManagedSpan(op, out var reference);
if (!DateTime.TryParse(sdt, out var dt))
{
reference.Dispose();
Runtime.XDecref(op);
goto type_error;
}
result = sdt.EndsWith("+00:00") ? dt.ToUniversalTime() : dt;
reference.Dispose();
Runtime.XDecref(op);
return true;
}
var month = Runtime.PyObject_GetAttrString(value, monthPtr);
var day = Runtime.PyObject_GetAttrString(value, dayPtr);
var hour = Runtime.PyObject_GetAttrString(value, hourPtr);
var minute = Runtime.PyObject_GetAttrString(value, minutePtr);
var second = Runtime.PyObject_GetAttrString(value, secondPtr);
var microsecond = Runtime.PyObject_GetAttrString(value, microsecondPtr);
var timeKind = DateTimeKind.Unspecified;
var tzinfo = Runtime.PyObject_GetAttrString(value, tzinfoPtr);
var hours = IntPtr.MaxValue;
var minutes = IntPtr.MaxValue;
if (tzinfo != IntPtr.Zero && tzinfo != Runtime.PyNone)
{
hours = Runtime.PyObject_GetAttrString(tzinfo, hoursPtr);
minutes = Runtime.PyObject_GetAttrString(tzinfo, minutesPtr);
if (Runtime.PyInt_AsLong(hours) == 0 && Runtime.PyInt_AsLong(minutes) == 0)
{
timeKind = DateTimeKind.Utc;
}
}
var convertedHour = 0;
var convertedMinute = 0;
var convertedSecond = 0;
var milliseconds = 0;
// could be python date type
if (hour != IntPtr.Zero && hour != Runtime.PyNone)
{
convertedHour = Runtime.PyInt_AsLong(hour);
convertedMinute = Runtime.PyInt_AsLong(minute);
convertedSecond = Runtime.PyInt_AsLong(second);
milliseconds = Runtime.PyInt_AsLong(microsecond) / 1000;
}
result = new DateTime(Runtime.PyInt_AsLong(year),
Runtime.PyInt_AsLong(month),
Runtime.PyInt_AsLong(day),
convertedHour,
convertedMinute,
convertedSecond,
millisecond: milliseconds,
timeKind);
Runtime.XDecref(year);
Runtime.XDecref(month);
Runtime.XDecref(day);
Runtime.XDecref(hour);
Runtime.XDecref(minute);
Runtime.XDecref(second);
Runtime.XDecref(microsecond);
if (tzinfo != IntPtr.Zero)
{
Runtime.XDecref(tzinfo);
if(tzinfo != Runtime.PyNone)
{
Runtime.XDecref(hours);
Runtime.XDecref(minutes);
}
}
return true;
default:
goto type_error;
}
convert_error:
if (op != value)
{
Runtime.XDecref(op);
}
if (!setError)
{
Exceptions.Clear();
}
return false;
type_error:
if (setError)
{
string tpName = Runtime.PyObject_GetTypeName(value);
Exceptions.SetError(Exceptions.TypeError, $"'{tpName}' value cannot be converted to {obType}");
}
return false;
overflow:
// C# level overflow error
if (op != value)
{
Runtime.XDecref(op);
}
if (setError)
{
Exceptions.SetError(Exceptions.OverflowError, "value too large to convert");
}
return false;
}
private static void SetConversionError(IntPtr value, Type target)
{
IntPtr ob = Runtime.PyObject_Repr(value);
string src = Runtime.GetManagedString(ob);
Runtime.XDecref(ob);
Exceptions.RaiseTypeError($"Cannot convert {src} to {target}");
}
/// <summary>
/// Convert a Python value to a correctly typed managed array instance.
/// The Python value must support the Python iterator protocol or and the
/// items in the sequence must be convertible to the target array type.
/// </summary>
private static bool ToArray(IntPtr value, Type obType, out object result, bool setError)
{
Type elementType = obType.GetElementType();
result = null;
IntPtr IterObject = Runtime.PyObject_GetIter(value);
if (IterObject == IntPtr.Zero || elementType.IsGenericType)
{
if (setError)
{
SetConversionError(value, obType);
}
else
{
// PyObject_GetIter will have set an error
Exceptions.Clear();
}
return false;
}
var list = MakeList(value, IterObject, obType, elementType, setError);
if (list == null)
{
return false;
}
Array items = Array.CreateInstance(elementType, list.Count);
list.CopyTo(items, 0);
result = items;
return true;
}
/// <summary>
/// Convert a Python value to a correctly typed managed list instance.
/// The Python value must support the Python sequence protocol and the
/// items in the sequence must be convertible to the target list type.
/// </summary>
private static bool ToList(IntPtr value, Type obType, out object result, bool setError)
{
var elementType = obType.GetGenericArguments()[0];
IntPtr IterObject = Runtime.PyObject_GetIter(value);
result = MakeList(value, IterObject, obType, elementType, setError);
return result != null;
}
/// <summary>
/// Helper function for ToArray and ToList that creates a IList out of iterable objects
/// </summary>
/// <param name="value"></param>
/// <param name="IterObject"></param>
/// <param name="obType"></param>
/// <param name="elementType"></param>
/// <param name="setError"></param>
/// <returns></returns>
private static IList MakeList(IntPtr value, IntPtr IterObject, Type obType, Type elementType, bool setError)
{
IList list;
try
{
// MakeGenericType can throw because elementType may not be a valid generic argument even though elementType[] is a valid array type.
// For example, if elementType is a pointer type.
// See https://docs.microsoft.com/en-us/dotnet/api/system.type.makegenerictype#System_Type_MakeGenericType_System_Type
var constructedListType = typeof(List<>).MakeGenericType(elementType);
bool IsSeqObj = Runtime.PySequence_Check(value);
if (IsSeqObj)
{
var len = Runtime.PySequence_Size(value);
list = (IList)Activator.CreateInstance(constructedListType, new Object[] { (int)len });
}
else
{
// CreateInstance can throw even if MakeGenericType succeeded.
// See https://docs.microsoft.com/en-us/dotnet/api/system.activator.createinstance#System_Activator_CreateInstance_System_Type_
list = (IList)Activator.CreateInstance(constructedListType);
}
}
catch (Exception e)
{
if (setError)
{
Exceptions.SetError(e);
SetConversionError(value, obType);
}
return null;
}
IntPtr item;
var usedImplicit = false;
while ((item = Runtime.PyIter_Next(IterObject)) != IntPtr.Zero)
{
object obj;
if (!Converter.ToManaged(item, elementType, out obj, setError, out usedImplicit))
{
Runtime.XDecref(item);
return null;
}
list.Add(obj);
Runtime.XDecref(item);
}
Runtime.XDecref(IterObject);
return list;
}
/// <summary>
/// Convert a Python value to a correctly typed managed enum instance.
/// </summary>
private static bool ToEnum(IntPtr value, Type obType, out object result, bool setError, out bool usedImplicit)
{
Type etype = Enum.GetUnderlyingType(obType);
result = null;
if (!ToPrimitive(value, etype, out result, setError, out usedImplicit))
{
return false;
}
if (Enum.IsDefined(obType, result))
{
result = Enum.ToObject(obType, result);
return true;
}
if (obType.GetCustomAttributes(flagsType, true).Length > 0)
{
result = Enum.ToObject(obType, result);
return true;
}
if (setError)
{
Exceptions.SetError(Exceptions.ValueError, "invalid enumeration value");
}
return false;
}
}
public static class ConverterExtension
{
public static PyObject ToPython(this object o)
{
return new PyObject(Converter.ToPython(o, o?.GetType()));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using 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>
/// VirtualNetworkPeeringsOperations operations.
/// </summary>
internal partial class VirtualNetworkPeeringsOperations : IServiceOperations<NetworkManagementClient>, IVirtualNetworkPeeringsOperations
{
/// <summary>
/// Initializes a new instance of the VirtualNetworkPeeringsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal VirtualNetworkPeeringsOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Deletes the specified virtual network peering.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the virtual network peering.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified virtual network peering.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the virtual network peering.
/// </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<VirtualNetworkPeering>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (virtualNetworkPeeringName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkPeeringName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("virtualNetworkPeeringName", virtualNetworkPeeringName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{virtualNetworkPeeringName}", System.Uri.EscapeDataString(virtualNetworkPeeringName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(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 (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<VirtualNetworkPeering>();
_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<VirtualNetworkPeering>(_responseContent, Client.DeserializationSettings);
}
catch (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>
/// Creates or updates a peering in the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the peering.
/// </param>
/// <param name='virtualNetworkPeeringParameters'>
/// Parameters supplied to the create or update virtual network peering
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<VirtualNetworkPeering>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<VirtualNetworkPeering> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all virtual network peerings in a virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </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<VirtualNetworkPeering>>> ListWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("apiVersion", apiVersion);
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("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(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 (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<VirtualNetworkPeering>>();
_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<VirtualNetworkPeering>>(_responseContent, Client.DeserializationSettings);
}
catch (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>
/// Deletes the specified virtual network peering.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the virtual network peering.
/// </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="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> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (virtualNetworkPeeringName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkPeeringName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("virtualNetworkPeeringName", virtualNetworkPeeringName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{virtualNetworkPeeringName}", System.Uri.EscapeDataString(virtualNetworkPeeringName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(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("DELETE");
_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 && (int)_statusCode != 204 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
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();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a peering in the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the peering.
/// </param>
/// <param name='virtualNetworkPeeringParameters'>
/// Parameters supplied to the create or update virtual network peering
/// 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<VirtualNetworkPeering>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (virtualNetworkPeeringName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkPeeringName");
}
if (virtualNetworkPeeringParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkPeeringParameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("virtualNetworkPeeringName", virtualNetworkPeeringName);
tracingParameters.Add("virtualNetworkPeeringParameters", virtualNetworkPeeringParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{virtualNetworkPeeringName}", System.Uri.EscapeDataString(virtualNetworkPeeringName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(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("PUT");
_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;
if(virtualNetworkPeeringParameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(virtualNetworkPeeringParameters, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// 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 && (int)_statusCode != 201)
{
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 (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<VirtualNetworkPeering>();
_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<VirtualNetworkPeering>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualNetworkPeering>(_responseContent, Client.DeserializationSettings);
}
catch (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>
/// Gets all virtual network peerings in a virtual network.
/// </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<VirtualNetworkPeering>>> 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 (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<VirtualNetworkPeering>>();
_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<VirtualNetworkPeering>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol
{
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// JobScheduleOperations operations.
/// </summary>
public partial interface IJobScheduleOperations
{
/// <summary>
/// Checks the specified job schedule exists.
/// </summary>
/// <param name='jobScheduleId'>
/// The id of the job schedule which you want to check.
/// </param>
/// <param name='jobScheduleExistsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<bool,JobScheduleExistsHeaders>> ExistsWithHttpMessagesAsync(string jobScheduleId, JobScheduleExistsOptions jobScheduleExistsOptions = default(JobScheduleExistsOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deletes a job schedule from the specified account.
/// </summary>
/// <param name='jobScheduleId'>
/// The id of the job schedule to delete.
/// </param>
/// <param name='jobScheduleDeleteOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobScheduleDeleteHeaders>> DeleteWithHttpMessagesAsync(string jobScheduleId, JobScheduleDeleteOptions jobScheduleDeleteOptions = default(JobScheduleDeleteOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets information about the specified job schedule.
/// </summary>
/// <param name='jobScheduleId'>
/// The id of the job schedule to get.
/// </param>
/// <param name='jobScheduleGetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CloudJobSchedule,JobScheduleGetHeaders>> GetWithHttpMessagesAsync(string jobScheduleId, JobScheduleGetOptions jobScheduleGetOptions = default(JobScheduleGetOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Updates the properties of the specified job schedule.
/// </summary>
/// <param name='jobScheduleId'>
/// The id of the job schedule to update.
/// </param>
/// <param name='jobSchedulePatchParameter'>
/// The parameters for the request.
/// </param>
/// <param name='jobSchedulePatchOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobSchedulePatchHeaders>> PatchWithHttpMessagesAsync(string jobScheduleId, JobSchedulePatchParameter jobSchedulePatchParameter, JobSchedulePatchOptions jobSchedulePatchOptions = default(JobSchedulePatchOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Updates the properties of the specified job schedule.
/// </summary>
/// <param name='jobScheduleId'>
/// The id of the job schedule to update.
/// </param>
/// <param name='jobScheduleUpdateParameter'>
/// The parameters for the request.
/// </param>
/// <param name='jobScheduleUpdateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobScheduleUpdateHeaders>> UpdateWithHttpMessagesAsync(string jobScheduleId, JobScheduleUpdateParameter jobScheduleUpdateParameter, JobScheduleUpdateOptions jobScheduleUpdateOptions = default(JobScheduleUpdateOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Disables a job schedule.
/// </summary>
/// <param name='jobScheduleId'>
/// The id of the job schedule to disable.
/// </param>
/// <param name='jobScheduleDisableOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobScheduleDisableHeaders>> DisableWithHttpMessagesAsync(string jobScheduleId, JobScheduleDisableOptions jobScheduleDisableOptions = default(JobScheduleDisableOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Enables a job schedule.
/// </summary>
/// <param name='jobScheduleId'>
/// The id of the job schedule to enable.
/// </param>
/// <param name='jobScheduleEnableOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobScheduleEnableHeaders>> EnableWithHttpMessagesAsync(string jobScheduleId, JobScheduleEnableOptions jobScheduleEnableOptions = default(JobScheduleEnableOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Terminates a job schedule.
/// </summary>
/// <param name='jobScheduleId'>
/// The id of the job schedule to terminates.
/// </param>
/// <param name='jobScheduleTerminateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobScheduleTerminateHeaders>> TerminateWithHttpMessagesAsync(string jobScheduleId, JobScheduleTerminateOptions jobScheduleTerminateOptions = default(JobScheduleTerminateOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Adds a job schedule to the specified account.
/// </summary>
/// <param name='cloudJobSchedule'>
/// The job schedule to be added.
/// </param>
/// <param name='jobScheduleAddOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobScheduleAddHeaders>> AddWithHttpMessagesAsync(JobScheduleAddParameter cloudJobSchedule, JobScheduleAddOptions jobScheduleAddOptions = default(JobScheduleAddOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all of the job schedules in the specified account.
/// </summary>
/// <param name='jobScheduleListOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CloudJobSchedule>,JobScheduleListHeaders>> ListWithHttpMessagesAsync(JobScheduleListOptions jobScheduleListOptions = default(JobScheduleListOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all of the job schedules in the specified account.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='jobScheduleListNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CloudJobSchedule>,JobScheduleListHeaders>> ListNextWithHttpMessagesAsync(string nextPageLink, JobScheduleListNextOptions jobScheduleListNextOptions = default(JobScheduleListNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
// 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.Diagnostics;
using Test.Utilities;
using Xunit;
namespace Microsoft.Maintainability.Analyzers.UnitTests
{
public class AvoidUninstantiatedInternalClassesTests : DiagnosticAnalyzerTestBase
{
[Fact]
public void CA1812_CSharp_Diagnostic_UninstantiatedInternalClass()
{
VerifyCSharp(
@"internal class C { }
",
GetCSharpResultAt(1, 16, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C"));
}
[Fact]
public void CA1812_Basic_Diagnostic_UninstantiatedInternalClass()
{
VerifyBasic(
@"Friend Class C
End Class",
GetBasicResultAt(1, 14, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C"));
}
[Fact]
public void CA1812_CSharp_NoDiagnostic_UninstantiatedInternalStruct()
{
VerifyCSharp(
@"internal struct CInternal { }");
}
[Fact]
public void CA1812_Basic_NoDiagnostic_UninstantiatedInternalStruct()
{
VerifyBasic(
@"Friend Structure CInternal
End Structure");
}
[Fact]
public void CA1812_CSharp_NoDiagnostic_UninstantiatedPublicClass()
{
VerifyCSharp(
@"public class C { }");
}
[Fact]
public void CA1812_Basic_NoDiagnostic_UninstantiatedPublicClass()
{
VerifyBasic(
@"Public Class C
End Class");
}
[Fact]
public void CA1812_CSharp_NoDiagnostic_InstantiatedInternalClass()
{
VerifyCSharp(
@"internal class C { }
public class D
{
private readonly C _c = new C();
}");
}
[Fact]
public void CA1812_Basic_NoDiagnostic_InstantiatedInternalClass()
{
VerifyBasic(
@"Friend Class C
End Class
Public Class D
Private _c As New C
End Class");
}
[Fact]
public void CA1812_CSharp_Diagnostic_UninstantiatedInternalClassNestedInPublicClass()
{
VerifyCSharp(
@"public class C
{
internal class D { }
}",
GetCSharpResultAt(3, 20, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C.D"));
}
[Fact]
public void CA1812_Basic_Diagnostic_UninstantiatedInternalClassNestedInPublicClass()
{
VerifyBasic(
@"Public Class C
Friend Class D
End Class
End Class",
GetBasicResultAt(2, 18, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C.D"));
}
[Fact]
public void CA1812_CSharp_NoDiagnostic_InstantiatedInternalClassNestedInPublicClass()
{
VerifyCSharp(
@"public class C
{
private readonly D _d = new D();
internal class D { }
}");
}
[Fact]
public void CA1812_Basic_NoDiagnostic_InstantiatedInternalClassNestedInPublicClass()
{
VerifyBasic(
@"Public Class C
Private ReadOnly _d = New D
Friend Class D
End Class
End Class");
}
[Fact]
public void CA1812_Basic_NoDiagnostic_InternalModule()
{
// No static classes in VB.
VerifyBasic(
@"Friend Module M
End Module");
}
[Fact]
public void CA1812_CSharp_NoDiagnostic_InternalAbstractClass()
{
VerifyCSharp(
@"internal abstract class A { }");
}
[Fact]
public void CA1812_Basic_NoDiagnostic_InternalAbstractClass()
{
VerifyBasic(
@"Friend MustInherit Class A
End Class");
}
[Fact]
public void CA1812_CSharp_NoDiagnostic_InternalDelegate()
{
VerifyCSharp(@"
namespace N
{
internal delegate void Del();
}");
}
[Fact]
public void CA1812_Basic_NoDiagnostic_InternalDelegate()
{
VerifyBasic(@"
Namespace N
Friend Delegate Sub Del()
End Namespace");
}
[Fact]
public void CA1812_CSharp_NoDiagnostic_InternalEnum()
{
VerifyCSharp(
@"namespace N
{
internal enum E {} // C# enums don't care if there are any members.
}");
}
[Fact]
public void CA1812_Basic_NoDiagnostic_InternalEnum()
{
VerifyBasic(
@"Namespace N
Friend Enum E
None ' VB enums require at least one member.
End Enum
End Namespace");
}
[Fact]
public void CA1812_CSharp_NoDiagnostic_AttributeClass()
{
VerifyCSharp(
@"using System;
internal class MyAttribute: Attribute {}
internal class MyOtherAttribute: MyAttribute {}");
}
[Fact]
public void CA1812_Basic_NoDiagnostic_AttributeClass()
{
VerifyBasic(
@"Imports System
Friend Class MyAttribute
Inherits Attribute
End Class
Friend Class MyOtherAttribute
Inherits MyAttribute
End Class");
}
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/881")]
public void CA1812_CSharp_NoDiagnostic_TypeContainingAssemblyEntryPointReturningVoid()
{
VerifyCSharp(
@"internal class C
{
private static void Main() {}
}");
}
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/881")]
public void CA1812_Basic_NoDiagnostic_TypeContainingAssemblyEntryPointReturningVoid()
{
VerifyBasic(
@"Friend Class C
Private Shared Sub Main()
End Sub
End Class");
}
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/881")]
public void CA1812_CSharp_NoDiagnostic_TypeContainingAssemblyEntryPointReturningInt()
{
VerifyCSharp(
@"internal class C
{
private static int Main() { return 1; }
}");
}
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/881")]
public void CA1812_Basic_NoDiagnostic_TypeContainingAssemblyEntryPointReturningInt()
{
VerifyBasic(
@"Friend Class C
Private Shared Function Main() As Integer
Return 1
End Sub
End Class");
}
[Fact]
public void CA1812_CSharp_Diagnostic_MainMethodIsNotStatic()
{
VerifyCSharp(
@"internal class C
{
private void Main() {}
}",
GetCSharpResultAt(1, 16, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C"));
}
[Fact]
public void CA1812_Basic_Diagnostic_MainMethodIsNotStatic()
{
VerifyBasic(
@"Friend Class C
Private Sub Main()
End Sub
End Class",
GetBasicResultAt(1, 14, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C"));
}
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/881")]
public void CA1812_Basic_NoDiagnostic_MainMethodIsDifferentlyCased()
{
VerifyBasic(
@"Friend Class C
Private Shared Sub mAiN()
End Sub
End Class");
}
// The following tests are just to ensure that the messages are formatted properly
// for types within namespaces.
[Fact]
public void CA1812_CSharp_Diagnostic_UninstantiatedInternalClassInNamespace()
{
VerifyCSharp(
@"namespace N
{
internal class C { }
}",
GetCSharpResultAt(3, 20, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C"));
}
[Fact]
public void CA1812_Basic_Diagnostic_UninstantiatedInternalClassInNamespace()
{
VerifyBasic(
@"Namespace N
Friend Class C
End Class
End Namespace",
GetBasicResultAt(2, 18, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C"));
}
[Fact]
public void CA1812_CSharp_Diagnostic_UninstantiatedInternalClassNestedInPublicClassInNamespace()
{
VerifyCSharp(
@"namespace N
{
public class C
{
internal class D { }
}
}",
GetCSharpResultAt(5, 24, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C.D"));
}
[Fact]
public void CA1812_Basic_Diagnostic_UninstantiatedInternalClassNestedInPublicClassInNamespace()
{
VerifyBasic(
@"Namespace N
Public Class C
Friend Class D
End Class
End Class
End Namespace",
GetBasicResultAt(3, 22, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C.D"));
}
[Fact]
public void CA1812_CSharp_NoDiagnostic_UninstantiatedInternalMef1ExportedClass()
{
VerifyCSharp(
@"using System;
using System.ComponentModel.Composition;
namespace System.ComponentModel.Composition
{
public class ExportAttribute: Attribute
{
}
}
[Export]
internal class C
{
}");
}
[Fact]
public void CA1812_Basic_NoDiagnostic_UninstantiatedInternalMef1ExportedClass()
{
VerifyBasic(
@"Imports System
Imports System.ComponentModel.Composition
Namespace System.ComponentModel.Composition
Public Class ExportAttribute
Inherits Attribute
End Class
End Namespace
<Export>
Friend Class C
End Class");
}
[Fact]
public void CA1812_CSharp_NoDiagnostic_UninstantiatedInternalMef2ExportedClass()
{
VerifyCSharp(
@"using System;
using System.ComponentModel.Composition;
namespace System.ComponentModel.Composition
{
public class ExportAttribute: Attribute
{
}
}
[Export]
internal class C
{
}");
}
[Fact]
public void CA1812_Basic_NoDiagnostic_UninstantiatedInternalMef2ExportedClass()
{
VerifyBasic(
@"Imports System
Imports System.ComponentModel.Composition
Namespace System.ComponentModel.Composition
Public Class ExportAttribute
Inherits Attribute
End Class
End Namespace
<Export>
Friend Class C
End Class");
}
[Fact]
public void CA1812_CSharp_NoDiagnostic_ImplementsIConfigurationSectionHandler()
{
VerifyCSharp(
@"using System.Configuration;
using System.Xml;
internal class C : IConfigurationSectionHandler
{
public object Create(object parent, object configContext, XmlNode section)
{
return null;
}
}");
}
[Fact]
public void CA1812_Basic_NoDiagnostic_ImplementsIConfigurationSectionHandler()
{
VerifyBasic(
@"Imports System.Configuration
Imports System.Xml
Friend Class C
Implements IConfigurationSectionHandler
Private Function IConfigurationSectionHandler_Create(parent As Object, configContext As Object, section As XmlNode) As Object Implements IConfigurationSectionHandler.Create
Return Nothing
End Function
End Class");
}
[Fact]
public void CA1812_CSharp_NoDiagnostic_DerivesFromConfigurationSection()
{
VerifyCSharp(
@"using System.Configuration;
namespace System.Configuration
{
public class ConfigurationSection
{
}
}
internal class C : ConfigurationSection
{
}");
}
[Fact]
public void CA1812_Basic_NoDiagnostic_DerivesFromConfigurationSection()
{
VerifyBasic(
@"Imports System.Configuration
Namespace System.Configuration
Public Class ConfigurationSection
End Class
End Namespace
Friend Class C
Inherits ConfigurationSection
End Class");
}
[Fact]
public void CA1812_CSharp_NoDiagnostic_DerivesFromSafeHandle()
{
VerifyCSharp(
@"using System;
using System.Runtime.InteropServices;
internal class MySafeHandle : SafeHandle
{
protected MySafeHandle(IntPtr invalidHandleValue, bool ownsHandle)
: base(invalidHandleValue, ownsHandle)
{
}
public override bool IsInvalid => true;
protected override bool ReleaseHandle()
{
return true;
}
}");
}
[Fact]
public void CA1812_Basic_NoDiagnostic_DerivesFromSafeHandle()
{
VerifyBasic(
@"Imports System
Imports System.Runtime.InteropServices
Friend Class MySafeHandle
Inherits SafeHandle
Protected Sub New(invalidHandleValue As IntPtr, ownsHandle As Boolean)
MyBase.New(invalidHandleValue, ownsHandle)
End Sub
Public Overrides ReadOnly Property IsInvalid As Boolean
Get
Return True
End Get
End Property
Protected Overrides Function ReleaseHandle() As Boolean
Return True
End Function
End Class");
}
[Fact]
public void CA1812_CSharp_NoDiagnostic_DerivesFromTraceListener()
{
VerifyCSharp(
@"using System.Diagnostics;
internal class MyTraceListener : TraceListener
{
public override void Write(string message) { }
public override void WriteLine(string message) { }
}");
}
[Fact]
public void CA1812_Basic_NoDiagnostic_DerivesFromTraceListener()
{
VerifyBasic(
@"Imports System.Diagnostics
Friend Class MyTraceListener
Inherits TraceListener
Public Overrides Sub Write(message As String)
End Sub
Public Overrides Sub WriteLine(message As String)
End Sub
End Class");
}
[Fact]
public void CA1812_CSharp_NoDiagnostic_InternalNestedTypeIsInstantiated()
{
VerifyCSharp(
@"internal class C
{
internal class C2
{
}
}
public class D
{
private readonly C.C2 _c2 = new C.C2();
}
");
}
[Fact]
public void CA1812_Basic_NoDiagnostic_InternalNestedTypeIsInstantiated()
{
VerifyBasic(
@"Friend Class C
Friend Class C2
End Class
End Class
Public Class D
Private _c2 As new C.C2
End Class");
}
[Fact]
public void CA1812_CSharp_Diagnostic_InternalNestedTypeIsNotInstantiated()
{
VerifyCSharp(
@"internal class C
{
internal class C2
{
}
}",
GetCSharpResultAt(
3, 20,
AvoidUninstantiatedInternalClassesAnalyzer.Rule,
"C.C2"));
}
[Fact]
public void CA1812_Basic_Diagnostic_InternalNestedTypeIsNotInstantiated()
{
VerifyBasic(
@"Friend Class C
Friend Class C2
End Class
End Class",
GetBasicResultAt(
2, 18,
AvoidUninstantiatedInternalClassesAnalyzer.Rule,
"C.C2"));
}
[Fact]
public void CA1812_CSharp_Diagnostic_PrivateNestedTypeIsInstantiated()
{
VerifyCSharp(
@"internal class C
{
private readonly C2 _c2 = new C2();
private class C2
{
}
}",
GetCSharpResultAt(
1, 16,
AvoidUninstantiatedInternalClassesAnalyzer.Rule,
"C"));
}
[Fact]
public void CA1812_Basic_Diagnostic_PrivateNestedTypeIsInstantiated()
{
VerifyBasic(
@"Friend Class C
Private _c2 As New C2
Private Class C2
End Class
End Class",
GetBasicResultAt(
1, 14,
AvoidUninstantiatedInternalClassesAnalyzer.Rule,
"C"));
}
[Fact]
public void CA1812_CSharp_NoDiagnostic_StaticHolderClass()
{
VerifyCSharp(
@"internal static class C
{
internal static void F() { }
}");
}
[Fact]
public void CA1812_Basic_NoDiagnostic_StaticHolderClass()
{
VerifyBasic(
@"Friend Module C
Friend Sub F()
End Sub
End Module");
}
[Fact]
public void CA1812_CSharp_Diagnostic_EmptyInternalStaticClass()
{
// Note that this is not considered a "static holder class"
// because it doesn't actually have any static members.
VerifyCSharp(
@"internal static class S { }",
GetCSharpResultAt(
1, 23,
AvoidUninstantiatedInternalClassesAnalyzer.Rule,
"S"));
}
[Fact]
public void CA1812_CSharp_NoDiagnostic_UninstantiatedInternalClassInFriendlyAssembly()
{
VerifyCSharp(
@"using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""TestProject"")]
internal class C { }"
);
}
[Fact]
public void CA1812_Basic_NoDiagnostic_UninstantiatedInternalClassInFriendlyAssembly()
{
VerifyBasic(
@"Imports System.Runtime.CompilerServices
<Assembly: InternalsVisibleToAttribute(""TestProject"")>
Friend Class C
End Class"
);
}
protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new AvoidUninstantiatedInternalClassesAnalyzer();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new AvoidUninstantiatedInternalClassesAnalyzer();
}
}
}
| |
/*
Copyright (c) 2007- DEVSENSE
Copyright (c) 2004-2006 Tomas Matousek and Vaclav Novak.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.SymbolStore;
using PHP.Core;
using PHP.Core.Parsers;
using PHP.Core.Text;
namespace PHP.Core.AST
{
#region GlobalCode
/// <summary>
/// Represents a container for global statements.
/// </summary>
/// <remarks>
/// PHP source file can contain global code definition which is represented in AST
/// by GlobalCode node. Finally, it is emitted into Main() method of concrete PHPPage
/// class. The sample code below illustrates a part of PHP global code
/// </remarks>
[Serializable]
public sealed class GlobalCode : AstNode, IHasSourceUnit, IDeclarationElement
{
/// <summary>
/// Array of nodes representing statements in PHP global code
/// </summary>
public Statement[]/*!*/ Statements { get { return statements; } internal set { statements = value; } }
private Statement[]/*!*/ statements;
/// <summary>
/// Represented source unit.
/// </summary>
public SourceUnit/*!*/ SourceUnit { get { return sourceUnit; } }
private readonly SourceUnit/*!*/ sourceUnit;
public Span EntireDeclarationSpan { get { return new Text.Span(0, sourceUnit.LineBreaks.TextLength); } }
#region Constructors
/// <summary>
/// Initializes a new instance of the GlobalCode class.
/// </summary>
public GlobalCode(IList<Statement>/*!*/ statements, SourceUnit/*!*/ sourceUnit)
{
Debug.Assert(statements != null && sourceUnit != null);
this.sourceUnit = sourceUnit;
this.statements = statements.AsArray();
}
#endregion
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public void VisitMe(TreeVisitor visitor)
{
visitor.VisitGlobalCode(this);
}
/// <summary>
/// <see cref="PHPDocBlock"/> instance or <c>null</c> reference.
/// </summary>
public PHPDocBlock PHPDoc
{
get { return this.GetPHPDoc(); }
set { this.SetPHPDoc(value); }
}
}
#endregion
#region NamespaceDecl
[Serializable]
public sealed class NamespaceDecl : Statement, IDeclarationElement
{
internal override bool IsDeclaration { get { return true; } }
/// <summary>
/// Whether the namespace was declared using PHP simple syntax.
/// </summary>
public readonly bool IsSimpleSyntax;
public QualifiedName QualifiedName { get { return this.qualifiedName; } }
private QualifiedName qualifiedName;
public Span EntireDeclarationSpan { get { return this.Span; } }
/// <summary>
/// Naming context defining aliases.
/// </summary>
public NamingContext/*!*/ Naming { get { return this.naming; } }
private readonly NamingContext naming;
public bool IsAnonymous { get { return this.isAnonymous; } }
private readonly bool isAnonymous;
public List<Statement>/*!*/ Statements
{
get { return this.statements; }
internal /* friend Parser */ set { this.statements = value; }
}
private List<Statement>/*!*/ statements;
#region Construction
public NamespaceDecl(Text.Span p)
: base(p)
{
this.isAnonymous = true;
this.qualifiedName = new QualifiedName(Core.Name.EmptyBaseName, Core.Name.EmptyNames);
this.IsSimpleSyntax = false;
this.naming = new NamingContext(null, null);
}
public NamespaceDecl(Text.Span p, List<string>/*!*/ names, bool simpleSyntax)
: base(p)
{
this.isAnonymous = false;
this.qualifiedName = new QualifiedName(names, false, true);
this.IsSimpleSyntax = simpleSyntax;
this.naming = new NamingContext(this.qualifiedName, null);
}
/// <summary>
/// Finish parsing of namespace, complete its position.
/// </summary>
/// <param name="p"></param>
internal void UpdatePosition(Text.Span p)
{
this.Span = p;
}
#endregion
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitNamespaceDecl(this);
}
/// <summary>
/// <see cref="PHPDocBlock"/> instance or <c>null</c> reference.
/// </summary>
public PHPDocBlock PHPDoc
{
get { return this.GetPHPDoc(); }
set { this.SetPHPDoc(value); }
}
}
#endregion
#region GlobalConstDeclList, GlobalConstantDecl
[Serializable]
public sealed class GlobalConstDeclList : Statement, IDeclarationElement
{
/// <summary>
/// Gets collection of CLR attributes annotating this statement.
/// </summary>
public CustomAttributes Attributes
{
get { return this.GetCustomAttributes(); }
set { this.SetCustomAttributes(value); }
}
public List<GlobalConstantDecl>/*!*/ Constants { get { return constants; } }
private readonly List<GlobalConstantDecl>/*!*/ constants;
public Text.Span EntireDeclarationSpan
{
get { return this.Span; }
}
public GlobalConstDeclList(Text.Span span, List<GlobalConstantDecl>/*!*/ constants, List<CustomAttribute> attributes)
: base(span)
{
Debug.Assert(constants != null);
this.constants = constants;
if (attributes != null && attributes.Count != 0)
this.Attributes = new CustomAttributes(attributes);
}
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitGlobalConstDeclList(this);
}
/// <summary>
/// <see cref="PHPDocBlock"/> instance or <c>null</c> reference.
/// </summary>
public PHPDocBlock PHPDoc
{
get { return this.GetPHPDoc(); }
set { this.SetPHPDoc(value); }
}
}
[Serializable]
public sealed class GlobalConstantDecl : ConstantDecl
{
/// <summary>
/// Namespace.
/// </summary>
public NamespaceDecl Namespace { get { return ns; } }
private NamespaceDecl ns;
/// <summary>
/// Gets value indicating whether this global constant is declared conditionally.
/// </summary>
public bool IsConditional { get; private set; }
/// <summary>
/// Scope.
/// </summary>
internal Scope Scope { get; private set; }
/// <summary>
/// Source unit.
/// </summary>
internal SourceUnit SourceUnit { get; private set; }
public GlobalConstantDecl(SourceUnit/*!*/ sourceUnit, Text.Span span, bool isConditional, Scope scope,
string/*!*/ name, NamespaceDecl ns, Expression/*!*/ initializer)
: base(span, name, initializer)
{
this.ns = ns;
this.IsConditional = IsConditional;
this.Scope = scope;
this.SourceUnit = sourceUnit;
}
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitGlobalConstantDecl(this);
}
}
#endregion
}
| |
using System;
using Eto.Drawing;
using Eto.Forms;
using Eto.Mac.Forms.Controls;
using System.Collections.Generic;
using Eto.Mac.Forms.Printing;
#if XAMMAC2
using AppKit;
using Foundation;
using CoreGraphics;
using ObjCRuntime;
using CoreAnimation;
using CoreImage;
#else
using MonoMac.AppKit;
using MonoMac.Foundation;
using MonoMac.CoreGraphics;
using MonoMac.ObjCRuntime;
using MonoMac.CoreAnimation;
using MonoMac.CoreImage;
#if Mac64
using CGSize = MonoMac.Foundation.NSSize;
using CGRect = MonoMac.Foundation.NSRect;
using CGPoint = MonoMac.Foundation.NSPoint;
using nfloat = System.Double;
using nint = System.Int64;
using nuint = System.UInt64;
#else
using CGSize = System.Drawing.SizeF;
using CGRect = System.Drawing.RectangleF;
using CGPoint = System.Drawing.PointF;
using nfloat = System.Single;
using nint = System.Int32;
using nuint = System.UInt32;
#endif
#endif
namespace Eto.Mac.Forms
{
class MouseDelegate : NSObject
{
WeakReference widget;
public IMacViewHandler Handler { get { return (IMacViewHandler)widget.Target; } set { widget = new WeakReference(value); } }
[Export("mouseMoved:")]
public void MouseMoved(NSEvent theEvent)
{
Handler.Callback.OnMouseMove(Handler.Widget, MacConversions.GetMouseEvent(Handler.EventControl, theEvent, false));
}
[Export("mouseEntered:")]
public void MouseEntered(NSEvent theEvent)
{
Handler.Callback.OnMouseEnter(Handler.Widget, MacConversions.GetMouseEvent(Handler.EventControl, theEvent, false));
}
[Export("cursorUpdate:")]
public void CursorUpdate(NSEvent theEvent)
{
}
[Export("mouseExited:")]
public void MouseExited(NSEvent theEvent)
{
Handler.Callback.OnMouseLeave(Handler.Widget, MacConversions.GetMouseEvent(Handler.EventControl, theEvent, false));
}
[Export("scrollWheel:")]
public void ScrollWheel(NSEvent theEvent)
{
Handler.Callback.OnMouseWheel(Handler.Widget, MacConversions.GetMouseEvent(Handler.EventControl, theEvent, true));
}
}
public interface IMacViewHandler : IMacControlHandler
{
Size? PreferredSize { get; }
Control Widget { get; }
Control.ICallback Callback { get; }
Cursor CurrentCursor { get; }
void OnKeyDown(KeyEventArgs e);
void OnSizeChanged(EventArgs e);
NSObject CustomFieldEditor { get; }
bool? ShouldHaveFocus { get; set; }
}
public abstract class MacView<TControl, TWidget, TCallback> : MacObject<TControl, TWidget, TCallback>, Control.IHandler, IMacViewHandler
where TControl: NSObject
where TWidget: Control
where TCallback: Control.ICallback
{
bool mouseMove;
NSTrackingArea tracking;
NSTrackingAreaOptions mouseOptions;
MouseDelegate mouseDelegate;
public override IntPtr NativeHandle { get { return Control.Handle; } }
Control.ICallback IMacViewHandler.Callback { get { return Callback; } }
public abstract NSView ContainerControl { get; }
public virtual NSView ContentControl { get { return ContainerControl; } }
public virtual NSView EventControl { get { return ContainerControl; } }
public virtual NSView FocusControl { get { return EventControl; } }
static readonly object AutoSize_Key = new object();
public virtual bool AutoSize
{
get { return Widget.Properties.Get<bool?>(AutoSize_Key) ?? true; }
protected set { Widget.Properties[AutoSize_Key] = value; }
}
protected virtual Size DefaultMinimumSize
{
get { return Size.Empty; }
}
static readonly object MinimumSize_Key = new object();
public virtual Size MinimumSize
{
get { return Widget.Properties.Get<Size?>(MinimumSize_Key) ?? DefaultMinimumSize; }
set { Widget.Properties[MinimumSize_Key] = value; NaturalSize = null; }
}
static readonly object MaximumSize_Key = new object();
public virtual SizeF MaximumSize
{
get { return Widget.Properties.Get<SizeF?>(MaximumSize_Key) ?? SizeF.MaxValue; }
set { Widget.Properties[MaximumSize_Key] = value; }
}
static readonly object PreferredSize_Key = new object();
public Size? PreferredSize
{
get { return Widget.Properties.Get<Size?>(PreferredSize_Key); }
set { Widget.Properties[PreferredSize_Key] = value; }
}
public virtual Size Size
{
get {
if (!Widget.Loaded)
return PreferredSize ?? new Size(-1, -1);
return ContainerControl.Frame.Size.ToEtoSize();
}
set
{
var oldSize = GetPreferredSize(Size.MaxValue);
PreferredSize = value;
var oldFrameSize = ContainerControl.Frame.Size;
var newSize = oldFrameSize;
if (value.Width >= 0)
newSize.Width = value.Width;
if (value.Height >= 0)
newSize.Height = value.Height;
// this doesn't get to our overridden method to handle the event (since it calls [super setFrameSize:]) so trigger event manually.
ContainerControl.SetFrameSize(newSize);
if (oldFrameSize != newSize)
Callback.OnSizeChanged(Widget, EventArgs.Empty);
AutoSize = value.Width == -1 && value.Height == -1;
CreateTracking();
LayoutIfNeeded(oldSize);
}
}
static readonly object NaturalSize_Key = new object();
protected SizeF? NaturalSize
{
get { return Widget.Properties.Get<SizeF?>(NaturalSize_Key); }
set { Widget.Properties[NaturalSize_Key] = value; }
}
public virtual NSObject CustomFieldEditor { get { return null; } }
protected virtual bool LayoutIfNeeded(SizeF? oldPreferredSize = null, bool force = false)
{
NaturalSize = null;
if (Widget.Loaded)
{
var oldSize = oldPreferredSize ?? ContainerControl.Frame.Size.ToEtoSize();
var newSize = GetPreferredSize(SizeF.MaxValue);
if (newSize != oldSize || force)
{
var container = Widget.Parent.GetMacContainer();
if (container != null)
container.LayoutParent();
return true;
}
}
return false;
}
protected virtual SizeF GetNaturalSize(SizeF availableSize)
{
var naturalSize = NaturalSize;
if (naturalSize != null)
return naturalSize.Value;
var control = Control as NSControl;
if (control != null)
{
var size = (Widget.Loaded) ? (CGSize?)control.Frame.Size : null;
control.SizeToFit();
naturalSize = control.Frame.Size.ToEto();
if (size != null)
control.SetFrameSize(size.Value);
NaturalSize = naturalSize;
return naturalSize.Value;
}
return Size.Empty;
}
public virtual SizeF GetPreferredSize(SizeF availableSize)
{
var size = GetNaturalSize(availableSize);
if (!AutoSize && PreferredSize != null)
{
var preferredSize = PreferredSize.Value;
if (preferredSize.Width >= 0)
size.Width = preferredSize.Width;
if (preferredSize.Height >= 0)
size.Height = preferredSize.Height;
}
return SizeF.Min(SizeF.Max(size, MinimumSize), MaximumSize);
}
public virtual Size PositionOffset { get { return Size.Empty; } }
void CreateTracking()
{
if (!mouseMove)
return;
if (tracking != null)
EventControl.RemoveTrackingArea(tracking);
//Console.WriteLine ("Adding mouse tracking {0} for area {1}", this.Widget.GetType ().FullName, Control.Frame.Size);
if (mouseDelegate == null)
mouseDelegate = new MouseDelegate { Handler = this };
var options = mouseOptions | NSTrackingAreaOptions.ActiveAlways | NSTrackingAreaOptions.EnabledDuringMouseDrag | NSTrackingAreaOptions.InVisibleRect;
tracking = new NSTrackingArea(new CGRect(CGPoint.Empty, EventControl.Frame.Size), options, mouseDelegate, new NSDictionary());
EventControl.AddTrackingArea(tracking);
}
public virtual void SetParent(Container parent)
{
}
static readonly IntPtr selMouseDown = Selector.GetHandle("mouseDown:");
static readonly IntPtr selMouseUp = Selector.GetHandle("mouseUp:");
static readonly IntPtr selMouseDragged = Selector.GetHandle("mouseDragged:");
static readonly IntPtr selRightMouseDown = Selector.GetHandle("rightMouseDown:");
static readonly IntPtr selRightMouseUp = Selector.GetHandle("rightMouseUp:");
static readonly IntPtr selRightMouseDragged = Selector.GetHandle("rightMouseDragged:");
static readonly IntPtr selScrollWheel = Selector.GetHandle("scrollWheel:");
static readonly IntPtr selKeyDown = Selector.GetHandle("keyDown:");
static readonly IntPtr selKeyUp = Selector.GetHandle("keyUp:");
static readonly IntPtr selBecomeFirstResponder = Selector.GetHandle("becomeFirstResponder");
static readonly IntPtr selSetFrameSize = Selector.GetHandle("setFrameSize:");
static readonly IntPtr selResignFirstResponder = Selector.GetHandle("resignFirstResponder");
static readonly IntPtr selInsertText = Selector.GetHandle("insertText:");
public override void AttachEvent(string id)
{
switch (id)
{
case Eto.Forms.Control.MouseEnterEvent:
HandleEvent(Eto.Forms.Control.MouseLeaveEvent);
break;
case Eto.Forms.Control.MouseLeaveEvent:
mouseOptions |= NSTrackingAreaOptions.MouseEnteredAndExited;
mouseMove = true;
HandleEvent(Eto.Forms.Control.SizeChangedEvent);
CreateTracking();
break;
case Eto.Forms.Control.MouseMoveEvent:
mouseOptions |= NSTrackingAreaOptions.MouseMoved;
mouseMove = true;
HandleEvent(Eto.Forms.Control.SizeChangedEvent);
CreateTracking();
AddMethod(selMouseDragged, new Action<IntPtr, IntPtr, IntPtr>(TriggerMouseDragged), "v@:@");
AddMethod(selRightMouseDragged, new Action<IntPtr, IntPtr, IntPtr>(TriggerMouseDragged), "v@:@");
break;
case Eto.Forms.Control.SizeChangedEvent:
AddMethod(selSetFrameSize, new Action<IntPtr, IntPtr, CGSize>(SetFrameSizeAction), "v@:{CGSize=ff}", ContainerControl);
break;
case Eto.Forms.Control.MouseDownEvent:
AddMethod(selMouseDown, new Action<IntPtr, IntPtr, IntPtr>(TriggerMouseDown), "v@:@");
AddMethod(selRightMouseDown, new Action<IntPtr, IntPtr, IntPtr>(TriggerMouseDown), "v@:@");
break;
case Eto.Forms.Control.MouseUpEvent:
AddMethod(selMouseUp, new Action<IntPtr, IntPtr, IntPtr>(TriggerMouseUp), "v@:@");
AddMethod(selRightMouseUp, new Action<IntPtr, IntPtr, IntPtr>(TriggerMouseUp), "v@:@");
break;
case Eto.Forms.Control.MouseDoubleClickEvent:
HandleEvent(Eto.Forms.Control.MouseDownEvent);
break;
case Eto.Forms.Control.MouseWheelEvent:
AddMethod(selScrollWheel, new Action<IntPtr, IntPtr, IntPtr>(TriggerMouseWheel), "v@:@");
break;
case Eto.Forms.Control.KeyDownEvent:
AddMethod(selKeyDown, new Action<IntPtr, IntPtr, IntPtr>(TriggerKeyDown), "v@:@");
break;
case Eto.Forms.Control.KeyUpEvent:
AddMethod(selKeyUp, new Action<IntPtr, IntPtr, IntPtr>(TriggerKeyUp), "v@:@");
break;
case Eto.Forms.Control.LostFocusEvent:
AddMethod(selResignFirstResponder, new Func<IntPtr, IntPtr, bool>(TriggerLostFocus), "B@:");
break;
case Eto.Forms.Control.GotFocusEvent:
AddMethod(selBecomeFirstResponder, new Func<IntPtr, IntPtr, bool>(TriggerGotFocus), "B@:");
break;
case Eto.Forms.Control.ShownEvent:
// TODO
break;
case Eto.Forms.Control.TextInputEvent:
AddMethod(selInsertText, new Action<IntPtr, IntPtr, IntPtr>(TriggerTextInput), "v@:@");
break;
default:
base.AttachEvent(id);
break;
}
}
protected static void TriggerTextInput(IntPtr sender, IntPtr sel, IntPtr textPtr)
{
var obj = Runtime.GetNSObject(sender);
var handler = GetHandler(obj) as IMacViewHandler;
if (handler != null)
{
var text = (string)Messaging.GetNSObject<NSString>(textPtr);
var args = new TextInputEventArgs(text);
handler.Callback.OnTextInput(handler.Widget, args);
if (args.Cancel)
return;
}
Messaging.void_objc_msgSendSuper_IntPtr(obj.SuperHandle, sel, textPtr);
}
static void SetFrameSizeAction(IntPtr sender, IntPtr sel, CGSize size)
{
var obj = Runtime.GetNSObject(sender);
Messaging.void_objc_msgSendSuper_SizeF(obj.SuperHandle, sel, size);
var handler = GetHandler(obj) as IMacViewHandler;
if (handler != null)
{
handler.OnSizeChanged(EventArgs.Empty);
handler.Callback.OnSizeChanged(handler.Widget, EventArgs.Empty);
}
}
protected static bool TriggerGotFocus(IntPtr sender, IntPtr sel)
{
var obj = Runtime.GetNSObject(sender);
var handler = GetHandler(obj) as IMacViewHandler;
if (handler != null)
{
handler.ShouldHaveFocus = true;
handler.Callback.OnGotFocus(handler.Widget, EventArgs.Empty);
handler.ShouldHaveFocus = null;
return Messaging.bool_objc_msgSendSuper(obj.SuperHandle, sel);
}
return false;
}
protected static bool TriggerLostFocus(IntPtr sender, IntPtr sel)
{
var obj = Runtime.GetNSObject(sender);
var handler = GetHandler(obj) as IMacViewHandler;
if (handler != null)
{
handler.ShouldHaveFocus = false;
handler.Callback.OnLostFocus(handler.Widget, EventArgs.Empty);
handler.ShouldHaveFocus = null;
return Messaging.bool_objc_msgSendSuper(obj.SuperHandle, sel);
}
return false;
}
static void TriggerKeyDown(IntPtr sender, IntPtr sel, IntPtr e)
{
var obj = Runtime.GetNSObject(sender);
var handler = GetHandler(obj) as IMacViewHandler;
if (handler != null)
{
var theEvent = Messaging.GetNSObject<NSEvent>(e);
if (!MacEventView.KeyDown(handler.Widget, theEvent))
{
Messaging.void_objc_msgSendSuper_IntPtr(obj.SuperHandle, sel, e);
}
}
}
static void TriggerKeyUp(IntPtr sender, IntPtr sel, IntPtr e)
{
var obj = Runtime.GetNSObject(sender);
var handler = GetHandler(obj) as IMacViewHandler;
if (handler != null)
{
var theEvent = Messaging.GetNSObject<NSEvent>(e);
if (!MacEventView.KeyUp(handler.Widget, theEvent))
{
Messaging.void_objc_msgSendSuper_IntPtr(obj.SuperHandle, sel, e);
}
}
}
static void TriggerMouseDown(IntPtr sender, IntPtr sel, IntPtr e)
{
var obj = Runtime.GetNSObject(sender);
var handler = GetHandler(obj) as IMacViewHandler;
if (handler != null)
{
var theEvent = Messaging.GetNSObject<NSEvent>(e);
var args = MacConversions.GetMouseEvent(handler.ContainerControl, theEvent, false);
if (theEvent.ClickCount >= 2)
handler.Callback.OnMouseDoubleClick(handler.Widget, args);
if (!args.Handled)
{
handler.Callback.OnMouseDown(handler.Widget, args);
}
if (!args.Handled)
{
Messaging.void_objc_msgSendSuper_IntPtr(obj.SuperHandle, sel, e);
}
}
}
/// <summary>
/// Triggers a mouse callback from a different event.
/// e.g. when an NSButton is clicked it is triggered from a mouse up event.
/// </summary>
protected void TriggerMouseCallback()
{
// trigger mouse up event since it's buried by cocoa
var evt = NSApplication.SharedApplication.CurrentEvent;
if (evt == null)
return;
if (evt.Type == NSEventType.LeftMouseUp || evt.Type == NSEventType.RightMouseUp || evt.Type == NSEventType.OtherMouseUp)
{
Callback.OnMouseUp(Widget, MacConversions.GetMouseEvent(ContainerControl, evt, false));
}
if (evt.Type == NSEventType.LeftMouseDragged || evt.Type == NSEventType.RightMouseDragged || evt.Type == NSEventType.OtherMouseDragged)
{
Callback.OnMouseMove(Widget, MacConversions.GetMouseEvent(ContainerControl, evt, false));
}
}
static void TriggerMouseUp(IntPtr sender, IntPtr sel, IntPtr e)
{
var obj = Runtime.GetNSObject(sender);
var handler = GetHandler(obj) as IMacViewHandler;
if (handler != null)
{
var theEvent = Messaging.GetNSObject<NSEvent>(e);
var args = MacConversions.GetMouseEvent(handler.ContainerControl, theEvent, false);
handler.Callback.OnMouseUp(handler.Widget, args);
if (!args.Handled)
{
Messaging.void_objc_msgSendSuper_IntPtr(obj.SuperHandle, sel, e);
}
}
}
static void TriggerMouseDragged(IntPtr sender, IntPtr sel, IntPtr e)
{
var obj = Runtime.GetNSObject(sender);
var handler = GetHandler(obj) as IMacViewHandler;
if (handler != null)
{
var theEvent = Messaging.GetNSObject<NSEvent>(e);
var args = MacConversions.GetMouseEvent(handler.ContainerControl, theEvent, false);
handler.Callback.OnMouseMove(handler.Widget, args);
if (!args.Handled)
{
Messaging.void_objc_msgSendSuper_IntPtr(obj.SuperHandle, sel, e);
}
}
}
static void TriggerMouseWheel(IntPtr sender, IntPtr sel, IntPtr e)
{
var obj = Runtime.GetNSObject(sender);
var handler = GetHandler(obj) as IMacViewHandler;
if (handler != null)
{
var theEvent = Messaging.GetNSObject<NSEvent>(e);
var args = MacConversions.GetMouseEvent(handler.ContainerControl, theEvent, true);
if (!args.Delta.IsZero)
{
handler.Callback.OnMouseWheel(handler.Widget, args);
if (!args.Handled)
{
Messaging.void_objc_msgSendSuper_IntPtr(obj.SuperHandle, sel, e);
}
}
}
}
public virtual void OnSizeChanged(EventArgs e)
{
CreateTracking();
}
public virtual void Invalidate()
{
ContainerControl.NeedsDisplay = true;
}
public virtual void Invalidate(Rectangle rect)
{
var region = rect.ToNS();
region.Y = EventControl.Frame.Height - region.Y - region.Height;
EventControl.SetNeedsDisplayInRect(region);
}
public void SuspendLayout()
{
}
public void ResumeLayout()
{
}
static readonly object InitialFocusKey = new object();
bool InitialFocus
{
get { return Widget.Properties.Get<bool?>(InitialFocusKey) ?? false; }
set { Widget.Properties[InitialFocusKey] = value ? (object)true : null; }
}
public virtual void Focus()
{
if (FocusControl.Window != null)
FocusControl.Window.MakeFirstResponder(FocusControl);
else
InitialFocus = true;
}
static readonly object BackgroundColorKey = new object();
public virtual Color BackgroundColor
{
get { return Widget.Properties.Get<Color?>(BackgroundColorKey) ?? Colors.Transparent; }
set
{
Widget.Properties[BackgroundColorKey] = value;
if (Widget.Loaded)
SetBackgroundColor(value);
}
}
protected virtual void SetBackgroundColor(Color? color)
{
if (color != null) {
if (color.Value.A > 0) {
ContainerControl.WantsLayer = true;
var layer = ContainerControl.Layer;
if (layer != null)
layer.BackgroundColor = color.Value.ToCG();
}
else {
ContainerControl.WantsLayer = false;
var layer = ContainerControl.Layer;
if (layer != null)
layer.BackgroundColor = Colors.Transparent.ToCG();
}
}
}
public abstract bool Enabled { get; set; }
static readonly object ShouldHaveFocusKey = new object();
public bool? ShouldHaveFocus
{
get { return Widget.Properties.Get<bool?>(ShouldHaveFocusKey); }
set { Widget.Properties[ShouldHaveFocusKey] = value; }
}
public virtual bool HasFocus
{
get
{
return ShouldHaveFocus ?? (FocusControl.Window != null && FocusControl.Window.FirstResponder == Control);
}
}
public virtual bool Visible
{
get { return !ContainerControl.Hidden; }
set
{
if (ContainerControl.Hidden == value)
{
var oldSize = GetPreferredSize(Size.MaxValue);
ContainerControl.Hidden = !value;
LayoutIfNeeded(oldSize, true);
}
}
}
static readonly IntPtr selResetCursorRects = Selector.GetHandle("resetCursorRects");
static void TriggerResetCursorRects(IntPtr sender, IntPtr sel)
{
var obj = Runtime.GetNSObject(sender);
var handler = GetHandler(obj) as IMacViewHandler;
if (handler != null)
{
var cursor = handler.CurrentCursor;
if (cursor != null)
{
handler.EventControl.AddCursorRect(new CGRect(CGPoint.Empty, handler.EventControl.Frame.Size), cursor.ControlObject as NSCursor);
}
}
}
public virtual Cursor CurrentCursor
{
get { return Cursor; }
}
static readonly object Cursor_Key = new object();
public virtual Cursor Cursor
{
get { return Widget.Properties.Get<Cursor>(Cursor_Key); }
set {
if (Cursor != value)
{
Widget.Properties[Cursor_Key] = value;
AddMethod(selResetCursorRects, new Action<IntPtr, IntPtr>(TriggerResetCursorRects), "v@:");
}
}
}
public string ToolTip
{
get { return ContentControl.ToolTip; }
set { ContentControl.ToolTip = value ?? string.Empty; }
}
public void Print(PrintSettings settings)
{
var op = NSPrintOperation.FromView(EventControl);
if (settings != null)
op.PrintInfo = ((PrintSettingsHandler)settings.Handler).Control;
op.ShowsPrintPanel = false;
op.RunOperation();
}
public virtual void OnPreLoad(EventArgs e)
{
}
public virtual void OnLoad(EventArgs e)
{
}
public virtual void OnLoadComplete(EventArgs e)
{
if (InitialFocus && FocusControl.Window != null)
{
FocusControl.Window.MakeFirstResponder(FocusControl);
InitialFocus = false;
}
SetBackgroundColor(Widget.Properties.Get<Color?>(BackgroundColorKey));
}
public virtual void OnUnLoad(EventArgs e)
{
}
public virtual void OnKeyDown(KeyEventArgs e)
{
Callback.OnKeyDown(Widget, e);
}
Control IMacViewHandler.Widget { get { return Widget; } }
public virtual PointF PointFromScreen(PointF point)
{
var sdpoint = point.ToNS();
if (EventControl.Window != null)
{
sdpoint.Y = ContentControl.Window.Screen.Frame.Height - sdpoint.Y;
sdpoint = ContentControl.Window.ConvertScreenToBase(sdpoint);
}
sdpoint = ContentControl.ConvertPointFromView(sdpoint, null);
sdpoint.Y = ContentControl.Frame.Height - sdpoint.Y;
return sdpoint.ToEto();
}
public virtual PointF PointToScreen(PointF point)
{
var sdpoint = point.ToNS();
sdpoint.Y = ContentControl.Frame.Height - sdpoint.Y;
sdpoint = ContentControl.ConvertPointToView(sdpoint, null);
if (ContentControl.Window != null)
{
sdpoint = ContentControl.Window.ConvertBaseToScreen(sdpoint);
sdpoint.Y = ContentControl.Window.Screen.Frame.Height - sdpoint.Y;
}
return sdpoint.ToEto();
}
Point Control.IHandler.Location
{
get
{
var frame = ContentControl.Frame;
var location = frame.Location;
var super = ContentControl.Superview;
if (super == null || super.IsFlipped)
return location.ToEtoPoint();
return new Point((int)location.X, (int)(super.Frame.Height - location.Y - frame.Height));
}
}
static void TriggerSystemAction(IntPtr sender, IntPtr sel, IntPtr e)
{
var control = Runtime.GetNSObject(sender);
var handler = GetHandler(control) as MacView<TControl,TWidget,TCallback>;
if (handler != null)
{
Command command;
if (handler.systemActions != null && handler.systemActions.TryGetValue(sel, out command))
{
if (command != null)
{
command.Execute();
return;
}
}
}
Messaging.void_objc_msgSendSuper_IntPtr(control.SuperHandle, sel, e);
}
static bool ValidateSystemUserInterfaceItem(IntPtr sender, IntPtr sel, IntPtr item)
{
var actionHandle = Messaging.IntPtr_objc_msgSend(item, selGetAction);
var control = Runtime.GetNSObject(sender);
var handler = GetHandler(control) as MacView<TControl,TWidget,TCallback>;
if (handler != null)
{
Command command;
if (handler.systemActions != null && actionHandle != IntPtr.Zero && handler.systemActions.TryGetValue(actionHandle, out command))
{
if (command != null)
return command.Enabled;
}
}
var objClass = ObjCExtensions.object_getClass(sender);
if (objClass == IntPtr.Zero)
return false;
var superClass = ObjCExtensions.class_getSuperclass(objClass);
return
superClass != IntPtr.Zero
&& ObjCExtensions.ClassInstancesRespondToSelector(superClass, sel)
&& Messaging.bool_objc_msgSendSuper_IntPtr(control.SuperHandle, sel, item);
}
Dictionary<IntPtr, Command> systemActions;
static readonly IntPtr selGetAction = Selector.GetHandle("action");
static readonly IntPtr selValidateUserInterfaceItem = Selector.GetHandle("validateUserInterfaceItem:");
static readonly IntPtr selCut = Selector.GetHandle("cut:");
static readonly IntPtr selCopy = Selector.GetHandle("copy:");
static readonly IntPtr selPaste = Selector.GetHandle("paste:");
static readonly IntPtr selSelectAll = Selector.GetHandle("selectAll:");
static readonly IntPtr selDelete = Selector.GetHandle("delete:");
static readonly IntPtr selUndo = Selector.GetHandle("undo:");
static readonly IntPtr selRedo = Selector.GetHandle("redo:");
static readonly IntPtr selPasteAsPlainText = Selector.GetHandle("pasteAsPlainText:");
static readonly IntPtr selPerformClose = Selector.GetHandle("performClose:");
static readonly IntPtr selPerformZoom = Selector.GetHandle("performZoom:");
static readonly IntPtr selArrangeInFront = Selector.GetHandle("arrangeInFront:");
static readonly IntPtr selPerformMiniaturize = Selector.GetHandle("performMiniaturize:");
static readonly Dictionary<string, IntPtr> systemActionSelectors = new Dictionary<string, IntPtr>
{
{ "cut", selCut },
{ "copy", selCopy },
{ "paste", selPaste },
{ "selectAll", selSelectAll },
{ "delete", selDelete },
{ "undo", selUndo },
{ "redo", selRedo },
{ "pasteAsPlainText", selPasteAsPlainText },
{ "performClose", selPerformClose },
{ "performZoom", selPerformZoom },
{ "arrangeInFront", selArrangeInFront },
{ "performMiniaturize", selPerformMiniaturize }
};
public virtual IEnumerable<string> SupportedPlatformCommands
{
get { return systemActionSelectors.Keys; }
}
public void MapPlatformCommand(string systemAction, Command command)
{
InnerMapPlatformCommand(systemAction, command, null);
}
protected virtual void InnerMapPlatformCommand(string systemAction, Command command, NSObject control)
{
IntPtr sel;
if (systemActionSelectors.TryGetValue(systemAction, out sel))
{
if (systemActions == null)
{
systemActions = new Dictionary<IntPtr, Command>();
AddMethod(selValidateUserInterfaceItem, new Func<IntPtr, IntPtr, IntPtr, bool>(ValidateSystemUserInterfaceItem), "B@:@", control);
}
AddMethod(sel, new Action<IntPtr, IntPtr, IntPtr>(TriggerSystemAction), "v@:@", control);
systemActions[sel] = command;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Cats.Data.Repository;
using Cats.Data.UnitWork;
using Cats.Models;
using Cats.Models.Constant;
using Cats.Models.ViewModels;
using Cats.Services.Logistics;
using Moq;
using NUnit.Framework;
using Cats.Services.Common;
namespace Cats.Data.Tests.ServicesTest.Logistics
{
[TestFixture]
public class TransportRequisitionServiceTests
{
#region SetUp / TearDown
private List<int> _reliefRequisitions;
private List<TransportRequisition> _transportRequisitions;
private TransportRequisitionService _transportRequisitionService;
private TransportRequisition _transportRequisition;
private IList<ReliefRequisition> reliefRequisitions;
private INotificationService _notificationService;
[SetUp]
public void Init()
{
_transportRequisitions = new List<TransportRequisition>();
_reliefRequisitions = new List<int> { 1 };
var unitOfWork = new Mock<IUnitOfWork>();
var unitOfWorkNotify = new Mock<IUnitOfWork>();
_transportRequisition = new TransportRequisition
{
Status = 1,
RequestedDate = DateTime.Today,
RequestedBy = 1,
CertifiedBy = 1,
CertifiedDate = DateTime.Today,
Remark = "",
TransportRequisitionNo = "REQ-001",
TransportRequisitionID = 1,
TransportRequisitionDetails = new List<TransportRequisitionDetail>()
{
new TransportRequisitionDetail
{
RequisitionID = 1,
TransportRequisitionDetailID
= 1,
TransportRequisitionID = 1
}
}
};
reliefRequisitions = new List<ReliefRequisition>()
{
new ReliefRequisition()
{
RegionID = 1,
ProgramID = 1,
CommodityID = 1,
ZoneID = 2,
RequisitionNo = "REQ-001",
Round = 1,
RegionalRequestID = 1,
RequisitionID = 1,
Status = 4,
AdminUnit = new AdminUnit
{
AdminUnitID = 2,
Name = "Zone1"
},
AdminUnit1 = new AdminUnit
{
AdminUnitID = 1,
Name = "Region1"
},
Commodity = new Commodity
{
CommodityID = 1,
CommodityCode = "C1",
Name = "CSB"
},
//HubAllocations = new List<HubAllocation>(){new HubAllocation()
// {
// HubAllocationID = 1,
// HubID = 1,
// RequisitionID = 1,
// Hub = new Hub
// {
// HubID = 1,
// Name = "Test Hub",
// }
// }},
ReliefRequisitionDetails = new List<ReliefRequisitionDetail>
{
new ReliefRequisitionDetail()
{
RequisitionID = 1,
RequisitionDetailID = 1,
Amount = 100,
CommodityID = 1,
FDPID = 1,
BenficiaryNo = 10,
DonorID = 1,
FDP=new FDP
{
AdminUnitID=1,
FDPID=1,
Name="FDP1"
}
},
new ReliefRequisitionDetail()
{
RequisitionID = 1,
RequisitionDetailID = 2,
Amount = 50,
CommodityID = 1,
FDPID = 2,
BenficiaryNo = 10,
DonorID = 1,
FDP=new FDP
{
AdminUnitID=1,
FDPID=2,
Name="FDP2"
}
},
new ReliefRequisitionDetail()
{
RequisitionID = 1,
RequisitionDetailID = 3,
Amount = 60,
CommodityID = 1,
FDPID = 3,
BenficiaryNo = 10,
DonorID = 1,
FDP=new FDP
{
AdminUnitID=1,
FDPID=3,
Name="FDP3"
}
},
new ReliefRequisitionDetail()
{
RequisitionID = 1,
RequisitionDetailID = 4,
Amount = 70,
CommodityID = 1,
FDPID = 2,
BenficiaryNo = 10,
DonorID = 1,
FDP=new FDP
{
AdminUnitID=1,
FDPID=4,
Name="FDP4"
}
}
}
}
};
var _workflowstatuses = new List<WorkflowStatus>
{
new WorkflowStatus
{
StatusID = 1,
WorkflowID = 2,
Description = "Approved",
}
};
var _hubAllocation = new List<HubAllocation>
{
new HubAllocation
{
RequisitionID = 1,
HubID = 1,
HubAllocationID = 1,
Hub=new Hub
{
Name="Hub 1",
HubID=1,
}
}
};
//_transportRequisition = new TransportRequisition()
// {
// Status = 1,
// RequestedBy = 1,
// CertifiedBy = 1,
// CertifiedDate = DateTime.Today,
// RequestedDate = DateTime.Today,
// TransportRequisitionID = 1,
// TransportRequisitionNo = "T-001",
// Remark = "comment"
// };
var mockReliefRequisitionRepository = new Mock<IGenericRepository<ReliefRequisition>>();
mockReliefRequisitionRepository.Setup(
t => t.Get(It.IsAny<Expression<Func<ReliefRequisition, bool>>>(), It.IsAny<Func<IQueryable<ReliefRequisition>, IOrderedQueryable<ReliefRequisition>>>(), It.IsAny<string>())).Returns(
(Expression<Func<ReliefRequisition, bool>> perdicate, Func<IQueryable<ReliefRequisition>, IOrderedQueryable<ReliefRequisition>> obrderBy, string prop) =>
{
var
result = reliefRequisitions.AsQueryable();
return result;
}
);
mockReliefRequisitionRepository.Setup(t => t.FindById(It.IsAny<int>())).Returns((int id) => reliefRequisitions
.ToList().
Find
(t =>
t.
RequisitionID ==
id));
unitOfWork.Setup(t => t.ReliefRequisitionRepository).Returns(mockReliefRequisitionRepository.Object);
var transportRequisitionReqository = new Mock<IGenericRepository<TransportRequisition>>();
transportRequisitionReqository.Setup(t => t.Add(It.IsAny<TransportRequisition>())).Returns(
(TransportRequisition transportRequisiton) =>
{
_transportRequisitions.Add(transportRequisiton);
return true;
});
transportRequisitionReqository.Setup(t => t.FindById(It.IsAny<int>())).Returns((int id) =>
{
return
_transportRequisition;
});
unitOfWork.Setup(t => t.TransportRequisitionRepository).Returns(transportRequisitionReqository.Object);
unitOfWork.Setup(t => t.Save());
var workflowStatusRepository = new Mock<IGenericRepository<WorkflowStatus>>();
workflowStatusRepository.Setup(
t =>
t.Get(It.IsAny<Expression<Func<WorkflowStatus, bool>>>(),
It.IsAny<Func<IQueryable<WorkflowStatus>, IOrderedQueryable<WorkflowStatus>>>(),
It.IsAny<string>())).Returns(_workflowstatuses);
unitOfWork.Setup(t => t.WorkflowStatusRepository).Returns(workflowStatusRepository.Object);
var hubAllocationRepository = new Mock<IGenericRepository<HubAllocation>>();
hubAllocationRepository.Setup(
t =>
t.Get(It.IsAny<Expression<Func<HubAllocation, bool>>>(),
It.IsAny<Func<IQueryable<HubAllocation>, IOrderedQueryable<HubAllocation>>>(),
It.IsAny<string>())).Returns(_hubAllocation);
unitOfWork.Setup(t => t.HubAllocationRepository).Returns(hubAllocationRepository.Object);
var adminUnitRepository = new Mock<IGenericRepository<AdminUnit>>();
adminUnitRepository.Setup(t => t.FindById(It.IsAny<int>())).Returns(new
AdminUnit()
{
AdminUnitID = 2,
Name = "Zone1",
AdminUnit2 = new AdminUnit
{
AdminUnitID
= 1,
Name =
"Region1"
}
}
);
unitOfWork.Setup(t => t.AdminUnitRepository).Returns(adminUnitRepository.Object);
var programRepository = new Mock<IGenericRepository<Program>>();
programRepository.Setup(t => t.FindById(It.IsAny<int>())).Returns(new Program
{
ProgramID = 1,
Name = "PSNP",
Description = "PSNP Des."
});
unitOfWork.Setup(t => t.ProgramRepository).Returns(programRepository.Object);
_notificationService = new NotificationService(unitOfWorkNotify.Object);
_transportRequisitionService = new TransportRequisitionService(unitOfWork.Object, _notificationService);
}
[TearDown]
public void Dispose()
{
_transportRequisitionService.Dispose();
}
#endregion
#region Tests
[Test]
public void CanGenerateRequisitonReadyToDispatch()
{
//Act
var requisitionToDispatch = _transportRequisitionService.GetRequisitionToDispatch().ToList();
//Assert
Assert.IsInstanceOf<IList<RequisitionToDispatch>>(requisitionToDispatch);
Assert.AreEqual(1, requisitionToDispatch.Count());
}
[Test]
public void ShouldCreateTransportRequision()
{
//Arrange
var reqList = new List<List<int>>();
reqList.Add(_reliefRequisitions);
//Act
var result = _transportRequisitionService.CreateTransportRequisition(reqList,1);
//Assert
Assert.IsTrue(result);
}
[Test]
public void SholdNotCreateTransportRequisitionIfNoReliefRequisition()
{
//Act
var result = _transportRequisitionService.CreateTransportRequisition(new List<List<int>>(),1);
//Assert
Assert.IsFalse(result);
}
[Test]
public void ShouldAddTransportRequisition()
{
//Act
var count = _transportRequisitions.Count;
_transportRequisitionService.AddTransportRequisition(_transportRequisition);
var result = _transportRequisitions.Count;
Assert.AreEqual(1 + count, result);
}
[Test]
public void IsProjectCodeAndOrSINumberAssigned()
{
//Act
var requisition = _transportRequisitionService.GetRequisitionToDispatch();
var result = requisition.ToList().TrueForAll(t => t.RequisitionStatus == (int)ReliefRequisitionStatus.ProjectCodeAssigned);//Project Si Code Assigned,indirectly it means Hub also assigned
//Assert
Assert.IsTrue(result);
}
[Test]
public void CanApproveTransportRequisition()
{
//Act
var result = _transportRequisitionService.ApproveTransportRequisition(1,1);
//Assert
var status = _transportRequisition.Status;
Assert.IsTrue(result);
Assert.AreEqual((int)TransportRequisitionStatus.Approved, status);
}
#endregion
}
}
| |
// ------------------------------------------------------------------------------------------------
// <copyright file="PrivateZoneScenarioTests.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ------------------------------------------------------------------------------------------------
namespace PrivateDns.Tests.ScenarioTests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using FluentAssertions;
using Microsoft.Azure.Management.PrivateDns;
using Microsoft.Azure.Management.PrivateDns.Models;
using Microsoft.Azure.Management.Resources;
using Microsoft.Rest.Azure;
using PrivateDns.Tests.Extensions;
using Xunit;
using Xunit.Abstractions;
public class PrivateZoneScenarioTests : BaseScenarioTests
{
public PrivateZoneScenarioTests(ITestOutputHelper output)
: base(output)
{
}
[Fact]
public void PutZone_ZoneNotExists_ExpectZoneCreated()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = TestDataGenerator.GeneratePrivateZoneName();
var createdPrivateZone = this.PrivateDnsManagementClient.PrivateZones.CreateOrUpdate(
resourceGroupName: resourceGroupName,
privateZoneName: privateZoneName,
parameters: TestDataGenerator.GeneratePrivateZone(location: Constants.PrivateDnsZonesLocation));
createdPrivateZone.Should().NotBeNull();
createdPrivateZone.Id.Should().Be(TestDataGenerator.GeneratePrivateZoneArmId(this.SubscriptionId, resourceGroupName, privateZoneName));
createdPrivateZone.Name.Should().Be(privateZoneName);
createdPrivateZone.Location.Should().Be(Constants.PrivateDnsZonesLocation);
createdPrivateZone.Type.Should().Be(Constants.PrivateDnsZonesResourceType);
createdPrivateZone.Etag.Should().NotBeNullOrEmpty();
createdPrivateZone.Tags.Should().BeNull();
createdPrivateZone.ProvisioningState.Should().Be(Constants.ProvisioningStateSucceeded);
createdPrivateZone.MaxNumberOfRecordSets.Should().BePositive();
createdPrivateZone.MaxNumberOfVirtualNetworkLinks.Should().BePositive();
createdPrivateZone.MaxNumberOfVirtualNetworkLinksWithRegistration.Should().BePositive();
createdPrivateZone.NumberOfRecordSets.Should().Be(1);
createdPrivateZone.NumberOfVirtualNetworkLinks.Should().Be(0);
createdPrivateZone.NumberOfVirtualNetworkLinksWithRegistration.Should().Be(0);
}
[Fact]
public void PutZone_ZoneNotExistsWithTags_ExpectZoneCreatedWithTags()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = TestDataGenerator.GeneratePrivateZoneName();
var privateZoneTags = TestDataGenerator.GenerateTags();
var createdPrivateZone = this.PrivateDnsManagementClient.PrivateZones.CreateOrUpdate(
resourceGroupName: resourceGroupName,
privateZoneName: privateZoneName,
parameters: TestDataGenerator.GeneratePrivateZone(location: Constants.PrivateDnsZonesLocation, tags: privateZoneTags));
createdPrivateZone.Should().NotBeNull();
createdPrivateZone.Tags.Should().NotBeNull().And.BeEquivalentTo(privateZoneTags);
}
[Fact]
public void PutZone_ZoneNotExistsIfNoneMatchSuccess_ExpectZoneCreated()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = TestDataGenerator.GeneratePrivateZoneName();
var createdPrivateZone = this.PrivateDnsManagementClient.PrivateZones.CreateOrUpdate(
resourceGroupName: resourceGroupName,
privateZoneName: privateZoneName,
ifNoneMatch: "*",
parameters: TestDataGenerator.GeneratePrivateZone(location: Constants.PrivateDnsZonesLocation));
createdPrivateZone.Should().NotBeNull();
createdPrivateZone.ProvisioningState.Should().Be(Constants.ProvisioningStateSucceeded);
}
[Fact]
public void PutZone_ZoneExistsIfMatchSuccess_ExpectZoneUpdated()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var createdPrivateZone = this.CreatePrivateZone(resourceGroupName);
var updatedPrivateZone = this.PrivateDnsManagementClient.PrivateZones.CreateOrUpdate(
resourceGroupName: resourceGroupName,
privateZoneName: createdPrivateZone.Name,
ifMatch: createdPrivateZone.Etag,
parameters: TestDataGenerator.GeneratePrivateZone(location: Constants.PrivateDnsZonesLocation));
updatedPrivateZone.Should().NotBeNull();
updatedPrivateZone.ProvisioningState.Should().Be(Constants.ProvisioningStateSucceeded);
updatedPrivateZone.Etag.Should().NotBeNullOrEmpty().And.NotBe(createdPrivateZone.Etag);
}
[Fact]
public void PutZone_ZoneExistsIfMatchFailure_ExpectError()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var createdPrivateZone = this.CreatePrivateZone(resourceGroupName);
Action updatedPrivateZoneAction = () => this.PrivateDnsManagementClient.PrivateZones.CreateOrUpdate(
resourceGroupName: resourceGroupName,
privateZoneName: createdPrivateZone.Name,
ifMatch: Guid.NewGuid().ToString(),
parameters: TestDataGenerator.GeneratePrivateZone(location: Constants.PrivateDnsZonesLocation));
updatedPrivateZoneAction.Should().Throw<CloudException>().Which.Response.ExtractAsyncErrorCode().Should().Be(HttpStatusCode.PreconditionFailed.ToString());
}
[Fact]
public void PutZone_ZoneExistsAddTags_ExpectTagsAdded()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var createdPrivateZone = this.CreatePrivateZone(resourceGroupName, tags: null);
var privateZoneTags = TestDataGenerator.GenerateTags();
var updatedPrivateZone = this.PrivateDnsManagementClient.PrivateZones.CreateOrUpdate(
resourceGroupName: resourceGroupName,
privateZoneName: createdPrivateZone.Name,
parameters: TestDataGenerator.GeneratePrivateZone(location: Constants.PrivateDnsZonesLocation, tags: privateZoneTags));
updatedPrivateZone.Should().NotBeNull();
updatedPrivateZone.Tags.Should().NotBeNull().And.BeEquivalentTo(privateZoneTags);
}
[Fact]
public void PutZone_ZoneExistsChangeTags_ExpectTagsChanged()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var createdPrivateZone = this.CreatePrivateZone(resourceGroupName, tags: TestDataGenerator.GenerateTags());
var updatedPrivateZoneTags = TestDataGenerator.GenerateTags(startFrom: createdPrivateZone.Tags.Count);
var updatedPrivateZone = this.PrivateDnsManagementClient.PrivateZones.CreateOrUpdate(
resourceGroupName: resourceGroupName,
privateZoneName: createdPrivateZone.Name,
parameters: TestDataGenerator.GeneratePrivateZone(location: Constants.PrivateDnsZonesLocation, tags: updatedPrivateZoneTags));
updatedPrivateZone.Should().NotBeNull();
updatedPrivateZone.Tags.Should().NotBeNull().And.BeEquivalentTo(updatedPrivateZoneTags);
}
[Fact]
public void PutZone_ZoneExistsRemoveTags_ExpectTagsRemoved()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var createdPrivateZone = this.CreatePrivateZone(resourceGroupName, tags: TestDataGenerator.GenerateTags());
var updatedPrivateZone = this.PrivateDnsManagementClient.PrivateZones.CreateOrUpdate(
resourceGroupName: resourceGroupName,
privateZoneName: createdPrivateZone.Name,
parameters: TestDataGenerator.GeneratePrivateZone(location: Constants.PrivateDnsZonesLocation, tags: null));
updatedPrivateZone.Should().NotBeNull();
updatedPrivateZone.Tags.Should().BeNull();
}
[Fact]
public void PatchZone_ZoneNotExists_ExpectError()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = TestDataGenerator.GeneratePrivateZoneName();
Action updateZoneAction = () => this.PrivateDnsManagementClient.PrivateZones.Update(
resourceGroupName: resourceGroupName,
privateZoneName: privateZoneName,
parameters: TestDataGenerator.GeneratePrivateZone());
updateZoneAction.Should().Throw<CloudException>().Which.Response.StatusCode.Should().Be(HttpStatusCode.NotFound);
}
[Fact]
public void PatchZone_ZoneExistsEmptyRequest_ExpectNoError()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var createdPrivateZone = this.CreatePrivateZone(resourceGroupName);
var updatedPrivateZone = this.PrivateDnsManagementClient.PrivateZones.Update(
resourceGroupName: resourceGroupName,
privateZoneName: createdPrivateZone.Name,
parameters: TestDataGenerator.GeneratePrivateZone());
updatedPrivateZone.Should().NotBeNull();
}
[Fact]
public void PatchZone_ZoneExistsAddTags_ExpectTagsAdded()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var createdPrivateZone = this.CreatePrivateZone(resourceGroupName, tags: null);
var privateZoneTags = TestDataGenerator.GenerateTags();
var updatedPrivateZone = this.PrivateDnsManagementClient.PrivateZones.Update(
resourceGroupName: resourceGroupName,
privateZoneName: createdPrivateZone.Name,
parameters: TestDataGenerator.GeneratePrivateZone(tags: privateZoneTags));
updatedPrivateZone.Should().NotBeNull();
updatedPrivateZone.Tags.Should().NotBeNull().And.BeEquivalentTo(privateZoneTags);
}
[Fact]
public void PatchZone_ZoneExistsChangeTags_ExpectTagsChanged()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var createdPrivateZone = this.CreatePrivateZone(resourceGroupName, tags: TestDataGenerator.GenerateTags());
var updatedPrivateZoneTags = TestDataGenerator.GenerateTags(startFrom: createdPrivateZone.Tags.Count);
var updatedPrivateZone = this.PrivateDnsManagementClient.PrivateZones.Update(
resourceGroupName: resourceGroupName,
privateZoneName: createdPrivateZone.Name,
parameters: TestDataGenerator.GeneratePrivateZone(tags: updatedPrivateZoneTags));
updatedPrivateZone.Should().NotBeNull();
updatedPrivateZone.Tags.Should().NotBeNull().And.BeEquivalentTo(updatedPrivateZoneTags);
}
[Fact]
public void PatchZone_ZoneExistsRemoveTags_ExpectTagsRemoved()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var createdPrivateZone = this.CreatePrivateZone(resourceGroupName, tags: TestDataGenerator.GenerateTags());
var updatedPrivateZone = this.PrivateDnsManagementClient.PrivateZones.Update(
resourceGroupName: resourceGroupName,
privateZoneName: createdPrivateZone.Name,
parameters: TestDataGenerator.GeneratePrivateZone(tags: new Dictionary<string, string>()));
updatedPrivateZone.Should().NotBeNull();
updatedPrivateZone.Tags.Should().BeEmpty();
}
[Fact]
public void GetZone_ZoneExists_ExpectZoneRetrieved()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var createdPrivateZone = this.CreatePrivateZone(resourceGroupName);
var retrievedZone = this.PrivateDnsManagementClient.PrivateZones.Get(resourceGroupName, createdPrivateZone.Name);
retrievedZone.Should().NotBeNull();
retrievedZone.Id.Should().Be(TestDataGenerator.GeneratePrivateZoneArmId(this.SubscriptionId, resourceGroupName, createdPrivateZone.Name));
retrievedZone.Name.Should().Be(createdPrivateZone.Name);
retrievedZone.Type.Should().Be(Constants.PrivateDnsZonesResourceType);
retrievedZone.Location.Should().Be(Constants.PrivateDnsZonesLocation);
}
[Fact]
public void GetZone_ZoneNotExists_ExpectError()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var nonExistentPrivateZoneName = TestDataGenerator.GeneratePrivateZoneName();
Action retrieveZoneAction = () => this.PrivateDnsManagementClient.PrivateZones.Get(resourceGroupName, nonExistentPrivateZoneName);
retrieveZoneAction.Should().Throw<CloudException>().Which.Response.StatusCode.Should().Be(HttpStatusCode.NotFound);
}
[Fact]
public void ListZonesInSubscription_MultipleZonesPresent_ExpectMultipleZonesRetrieved()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var createdPrivateZones = this.CreatePrivateZones(resourceGroupName);
var listResult = this.PrivateDnsManagementClient.PrivateZones.List();
listResult.Should().NotBeNull();
listResult.NextPageLink.Should().BeNull();
var listedZones = listResult.ToArray();
listedZones.Count().Should().BeGreaterOrEqualTo(createdPrivateZones.Count());
listedZones.All(listedZone => ValidateListedZoneIsExpected(listedZone, createdPrivateZones));
}
[Fact]
public void ListZonesInSubscription_WithTopParameter_ExpectSpecifiedZonesRetrieved()
{
const int numPrivateZones = 2;
const int topValue = numPrivateZones - 1;
var resourceGroupName = this.CreateResourceGroup().Name;
var createdPrivateZones = this.CreatePrivateZones(resourceGroupName, numPrivateZones: numPrivateZones);
var expectedZones = createdPrivateZones.OrderBy(x => x.Name).Take(topValue);
var listResult = this.PrivateDnsManagementClient.PrivateZones.List(top: topValue);
listResult.Should().NotBeNull();
listResult.NextPageLink.Should().NotBeNullOrEmpty();
var listedZones = listResult.ToArray();
listedZones.Count().Should().Be(topValue);
}
[Fact]
public void ListZonesInSubscription_ListNextPage_ExpectNextZonesRetrieved()
{
const int numPrivateZones = 2;
const int topValue = numPrivateZones - 1;
var resourceGroupName = this.CreateResourceGroup().Name;
var createdPrivateZones = this.CreatePrivateZones(resourceGroupName, numPrivateZones: numPrivateZones);
var expectedNextZones = createdPrivateZones.OrderBy(x => x.Name).Skip(topValue);
var initialListResult = this.PrivateDnsManagementClient.PrivateZones.List(top: topValue);
var nextLink = initialListResult.NextPageLink;
var nextListResult = this.PrivateDnsManagementClient.PrivateZones.ListNext(nextLink);
nextListResult.Should().NotBeNull();
var nextListedZones = nextListResult.ToArray();
nextListedZones.Count().Should().Be(topValue);
}
[Fact]
public void ListZonesInResourceGroup_NoZonesPresent_ExpectNoZonesRetrieved()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var extraResourceGroupName = this.CreateResourceGroup().Name;
var createdExtraPrivateZones = this.CreatePrivateZones(extraResourceGroupName, numPrivateZones: 1);
var listResult = this.PrivateDnsManagementClient.PrivateZones.ListByResourceGroup(resourceGroupName);
listResult.Should().NotBeNull();
listResult.NextPageLink.Should().BeNull();
var listedZones = listResult.ToArray();
listedZones.Count().Should().Be(0);
}
[Fact]
public void ListZonesInResourceGroup_MultipleZonesPresent_ExpectMultipleZonesRetrieved()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var extraResourceGroupName = this.CreateResourceGroup().Name;
var createdPrivateZones = this.CreatePrivateZones(resourceGroupName);
var createdExtraPrivateZones = this.CreatePrivateZones(extraResourceGroupName, numPrivateZones: 1);
var listResult = this.PrivateDnsManagementClient.PrivateZones.ListByResourceGroup(resourceGroupName);
listResult.Should().NotBeNull();
listResult.NextPageLink.Should().BeNull();
var listedZones = listResult.ToArray();
listedZones.Count().Should().Be(createdPrivateZones.Count());
listedZones.All(listedZone => ValidateListedZoneIsExpected(listedZone, createdPrivateZones));
}
[Fact]
public void ListZonesInResourceGroup_WithTopParameter_ExpectSpecifiedZonesRetrieved()
{
const int numPrivateZones = 2;
const int topValue = numPrivateZones - 1;
var resourceGroupName = this.CreateResourceGroup().Name;
var extraResourceGroupName = this.CreateResourceGroup().Name;
var createdPrivateZones = this.CreatePrivateZones(resourceGroupName, numPrivateZones: numPrivateZones);
var createdExtraPrivateZones = this.CreatePrivateZones(extraResourceGroupName, numPrivateZones: 1);
var expectedZones = createdPrivateZones.OrderBy(x => x.Name).Take(topValue);
var listResult = this.PrivateDnsManagementClient.PrivateZones.ListByResourceGroup(resourceGroupName, top: topValue);
listResult.Should().NotBeNull();
listResult.NextPageLink.Should().NotBeNullOrEmpty();
var listedZones = listResult.ToArray();
listedZones.Count().Should().Be(topValue);
listedZones.All(listedZone => ValidateListedZoneIsExpected(listedZone, expectedZones));
}
[Fact]
public void ListZonesInResourceGroup_ListNextPage_ExpectNextZonesRetrieved()
{
const int numPrivateZones = 2;
const int topValue = numPrivateZones - 1;
var resourceGroupName = this.CreateResourceGroup().Name;
var extraResourceGroupName = this.CreateResourceGroup().Name;
var createdPrivateZones = this.CreatePrivateZones(resourceGroupName, numPrivateZones: numPrivateZones);
var createdExtraPrivateZones = this.CreatePrivateZones(extraResourceGroupName, numPrivateZones: 1);
var expectedNextZones = createdPrivateZones.OrderBy(x => x.Name).Skip(topValue);
var initialListResult = this.PrivateDnsManagementClient.PrivateZones.ListByResourceGroup(resourceGroupName, top: topValue);
var nextLink = initialListResult.NextPageLink;
var nextListResult = this.PrivateDnsManagementClient.PrivateZones.ListByResourceGroupNext(nextLink);
nextListResult.Should().NotBeNull();
nextListResult.NextPageLink.Should().BeNull();
var nextListedZones = nextListResult.ToArray();
nextListedZones.Count().Should().Be(topValue);
nextListedZones.All(listedZone => ValidateListedZoneIsExpected(listedZone, expectedNextZones));
}
[Fact]
public void DeleteZone_ZoneExists_ExpectZoneDeleted()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var createdPrivateZone = this.CreatePrivateZone(resourceGroupName);
Action deleteZoneAction = () => this.PrivateDnsManagementClient.PrivateZones.Delete(resourceGroupName, createdPrivateZone.Name);
deleteZoneAction.Should().NotThrow();
}
[Fact]
public void DeleteZone_ZoneNotExists_ExpectNoError()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var nonExistentPrivateZoneName = TestDataGenerator.GeneratePrivateZoneName();
Action deleteZoneAction = () => this.PrivateDnsManagementClient.PrivateZones.Delete(resourceGroupName, nonExistentPrivateZoneName);
deleteZoneAction.Should().NotThrow();
}
private static bool ValidateListedZoneIsExpected(PrivateZone listedZone, IEnumerable<PrivateZone> expectedZones)
{
return expectedZones.Any(expectedZone => string.Equals(expectedZone.Id, listedZone.Id, StringComparison.OrdinalIgnoreCase));
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Globalization {
using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
/*=================================ThaiBuddhistCalendar==========================
**
** ThaiBuddhistCalendar is based on Gregorian calendar. Its year value has
** an offset to the Gregorain calendar.
**
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 0001/01/01 9999/12/31
** Thai 0544/01/01 10542/12/31
============================================================================*/
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable] public class ThaiBuddhistCalendar: Calendar {
// Initialize our era info.
static internal EraInfo[] thaiBuddhistEraInfo = new EraInfo[] {
new EraInfo( 1, 1, 1, 1, -543, 544, GregorianCalendar.MaxYear + 543) // era #, start year/month/day, yearOffset, minEraYear
};
//
// The era value for the current era.
//
public const int ThaiBuddhistEra = 1;
//internal static Calendar m_defaultInstance;
internal GregorianCalendarHelper helper;
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
// Return the type of the Thai Buddhist calendar.
//
[System.Runtime.InteropServices.ComVisible(false)]
public override CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.SolarCalendar;
}
}
public ThaiBuddhistCalendar() {
helper = new GregorianCalendarHelper(this, thaiBuddhistEraInfo);
}
internal override int ID {
get {
return (CAL_THAI);
}
}
public override DateTime AddMonths(DateTime time, int months) {
return (helper.AddMonths(time, months));
}
public override DateTime AddYears(DateTime time, int years) {
return (helper.AddYears(time, years));
}
public override int GetDaysInMonth(int year, int month, int era) {
return (helper.GetDaysInMonth(year, month, era));
}
public override int GetDaysInYear(int year, int era) {
return (helper.GetDaysInYear(year, era));
}
public override int GetDayOfMonth(DateTime time) {
return (helper.GetDayOfMonth(time));
}
public override DayOfWeek GetDayOfWeek(DateTime time) {
return (helper.GetDayOfWeek(time));
}
public override int GetDayOfYear(DateTime time)
{
return (helper.GetDayOfYear(time));
}
public override int GetMonthsInYear(int year, int era) {
return (helper.GetMonthsInYear(year, era));
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
return (helper.GetWeekOfYear(time, rule, firstDayOfWeek));
}
public override int GetEra(DateTime time) {
return (helper.GetEra(time));
}
public override int GetMonth(DateTime time) {
return (helper.GetMonth(time));
}
public override int GetYear(DateTime time) {
return (helper.GetYear(time));
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
return (helper.IsLeapDay(year, month, day, era));
}
public override bool IsLeapYear(int year, int era) {
return (helper.IsLeapYear(year, era));
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetLeapMonth(int year, int era)
{
return (helper.GetLeapMonth(year, era));
}
public override bool IsLeapMonth(int year, int month, int era) {
return (helper.IsLeapMonth(year, month, era));
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) {
return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era));
}
public override int[] Eras {
get {
return (helper.Eras);
}
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 2572;
public override int TwoDigitYearMax
{
get
{
if (twoDigitYearMax == -1) {
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
set {
VerifyWritable();
if (value < 99 || value > helper.MaxYear) {
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
99,
helper.MaxYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year) {
if (year < 0) {
throw new ArgumentOutOfRangeException("year",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
return (helper.ToFourDigitYear(year, this.TwoDigitYearMax));
}
}
}
| |
using UnityEngine;
using UnityEngine.Serialization;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(SgtCloudsphere))]
public class SgtCloudsphere_Editor : SgtEditor<SgtCloudsphere>
{
protected override void OnInspector()
{
var updateMaterial = false;
var updateModels = false;
DrawDefault("Color", ref updateMaterial);
BeginError(Any(t => t.Brightness <= 0.0f));
DrawDefault("Brightness", ref updateMaterial);
EndError();
DrawDefault("RenderQueue", ref updateMaterial);
DrawDefault("RenderQueueOffset", ref updateMaterial);
Separator();
BeginError(Any(t => t.MainTex == null));
DrawDefault("MainTex", ref updateMaterial);
EndError();
BeginError(Any(t => t.DepthTex == null));
DrawDefault("DepthTex", ref updateMaterial);
EndError();
BeginError(Any(t => t.Radius < 0.0f));
DrawDefault("Radius", ref updateModels);
EndError();
DrawDefault("CameraOffset"); // Updated automatically
Separator();
DrawDefault("Fade", ref updateMaterial);
if (Any(t => t.Fade == true))
{
BeginIndent();
BeginError(Any(t => t.FadeTex == null));
DrawDefault("FadeTex", ref updateMaterial);
EndError();
BeginError(Any(t => t.FadeDistance <= 0.0f));
DrawDefault("FadeDistance", ref updateMaterial);
EndError();
EndIndent();
}
Separator();
BeginError(Any(t => t.MeshRadius <= 0.0f));
DrawDefault("MeshRadius", ref updateModels);
EndError();
BeginError(Any(t => t.Meshes != null && t.Meshes.Count == 0));
DrawDefault("Meshes", ref updateModels);
EndError();
Separator();
DrawDefault("Lit", ref updateModels);
if (Any(t => t.Lit == true))
{
BeginIndent();
BeginError(Any(t => t.LightingTex == null));
DrawDefault("LightingTex", ref updateMaterial);
EndError();
BeginError(Any(t => t.Lights != null && (t.Lights.Count == 0 || t.Lights.Exists(l => l == null))));
DrawDefault("Lights", ref updateMaterial);
EndError();
BeginError(Any(t => t.Shadows != null && t.Shadows.Exists(s => s == null)));
DrawDefault("Shadows", ref updateMaterial);
EndError();
EndIndent();
}
if (Any(t => t.DepthTex == null && t.GetComponent<SgtCloudsphereDepth>() == null))
{
Separator();
if (Button("Add Depth") == true)
{
Each(t => SgtHelper.GetOrAddComponent<SgtCloudsphereDepth>(t.gameObject));
}
}
if (Any(t => t.Lit == true && t.LightingTex == null && t.GetComponent<SgtCloudsphereLighting>() == null))
{
Separator();
if (Button("Add Lighting") == true)
{
Each(t => SgtHelper.GetOrAddComponent<SgtCloudsphereLighting>(t.gameObject));
}
}
if (Any(t => t.Fade == true && t.FadeTex == null && t.GetComponent<SgtCloudsphereFade>() == null))
{
Separator();
if (Button("Add Fade") == true)
{
Each(t => SgtHelper.GetOrAddComponent<SgtCloudsphereFade>(t.gameObject));
}
}
if (updateMaterial == true) DirtyEach(t => t.UpdateMaterial());
if (updateModels == true) DirtyEach(t => t.UpdateModels ());
}
}
#endif
[ExecuteInEditMode]
[AddComponentMenu("Space Graphics Toolkit/SGT Cloudsphere")]
public class SgtCloudsphere : MonoBehaviour
{
// All active and enabled cloudspheres in the scene
public static List<SgtCloudsphere> AllCloudspheres = new List<SgtCloudsphere>();
[Tooltip("The color tint")]
public Color Color = Color.white;
[Tooltip("The Color.rgb values are multiplied by this")]
public float Brightness = 1.0f;
[Tooltip("The radius of the cloudsphere meshes specified below")]
public float MeshRadius = 1.0f;
[Tooltip("The meshes used to build the cloudsphere (should be a sphere)")]
public List<Mesh> Meshes;
[Tooltip("The render queue group for this cloudsphere")]
public SgtRenderQueue RenderQueue = SgtRenderQueue.Transparent;
[Tooltip("The render queue offset for this cloudsphere")]
public int RenderQueueOffset;
[Tooltip("The desired radius of the cloudsphere in local coordinates")]
public float Radius = 1.5f;
[Tooltip("Should the clouds fade out when the camera gets near?")]
public bool Fade;
[Tooltip("The lookup table used to calculate the fade")]
public Texture FadeTex;
[Tooltip("The distance the fading begins from in world space")]
public float FadeDistance = 1.0f;
[Tooltip("The amount the clouds get moved toward the current camera")]
[FormerlySerializedAs("ObserverOffset")]
public float CameraOffset;
[Tooltip("The cubemap used to render the clouds")]
public Cubemap MainTex;
[Tooltip("The lookup table used for depth color and opacity (bottom = no depth/space, top = maximum depth/center)")]
public Texture2D DepthTex;
[Tooltip("Does this cloudsphere receive light?")]
public bool Lit;
[Tooltip("The lookup table used to calculate the lighting color and brightness")]
public Texture LightingTex;
[Tooltip("The lights shining on this cloudsphere")]
public List<Light> Lights;
[Tooltip("The shadows casting on this cloudsphere")]
public List<SgtShadow> Shadows;
// The material applied to all models
[System.NonSerialized]
public Material Material;
// The models used to render this cloudsphere
[SerializeField]
public List<SgtCloudsphereModel> Models;
[SerializeField]
private bool startCalled;
[System.NonSerialized]
private bool updateMaterialCalled;
[System.NonSerialized]
private bool updateModelsCalled;
public void UpdateDeptchTex()
{
if (Material != null)
{
Material.SetTexture("_DepthTex", DepthTex);
}
}
public void UpdateFadeTex()
{
if (Material != null)
{
Material.SetTexture("_FadeTex", FadeTex);
}
}
public void UpdateLightingTex()
{
if (Material != null)
{
Material.SetTexture("_LightingTex", LightingTex);
}
}
[ContextMenu("Update Material")]
public void UpdateMaterial()
{
updateMaterialCalled = true;
if (Material == null)
{
Material = SgtHelper.CreateTempMaterial("Cloudsphere (Generated)", SgtHelper.ShaderNamePrefix + "Cloudsphere");
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var model = Models[i];
if (model != null)
{
model.SetMaterial(Material);
}
}
}
}
var renderQueue = (int)RenderQueue + RenderQueueOffset;
var color = SgtHelper.Brighten(Color, Brightness);
Material.renderQueue = renderQueue;
Material.SetColor("_Color", color);
Material.SetTexture("_MainTex", MainTex);
Material.SetTexture("_DepthTex", DepthTex);
if (Fade == true)
{
SgtHelper.EnableKeyword("SGT_A", Material); // Fade
Material.SetTexture("_FadeTex", FadeTex);
Material.SetFloat("_FadeDistanceRecip", SgtHelper.Reciprocal(FadeDistance));
}
else
{
SgtHelper.DisableKeyword("SGT_A", Material); // Fade
}
if (Lit == true)
{
Material.SetTexture("_LightingTex", LightingTex);
}
}
[ContextMenu("Update Models")]
public void UpdateModels()
{
updateModelsCalled = true;
var meshCount = Meshes != null ? Meshes.Count : 0;
var scale = SgtHelper.Divide(Radius, MeshRadius);
for (var i = 0; i < meshCount; i++)
{
var mesh = Meshes[i];
var model = GetOrAddModel(i);
model.SetMesh(mesh);
model.SetMaterial(Material);
model.SetScale(scale);
}
// Remove any excess
if (Models != null)
{
for (var i = Models.Count - 1; i >= meshCount; i--)
{
SgtCloudsphereModel.Pool(Models[i]);
Models.RemoveAt(i);
}
}
}
public static SgtCloudsphere CreateCloudsphere(int layer = 0, Transform parent = null)
{
return CreateCloudsphere(layer, parent, Vector3.zero, Quaternion.identity, Vector3.one);
}
public static SgtCloudsphere CreateCloudsphere(int layer, Transform parent, Vector3 localPosition, Quaternion localRotation, Vector3 localScale)
{
var gameObject = SgtHelper.CreateGameObject("Cloudsphere", layer, parent, localPosition, localRotation, localScale);
var cloudsphere = gameObject.AddComponent<SgtCloudsphere>();
return cloudsphere;
}
#if UNITY_EDITOR
[MenuItem(SgtHelper.GameObjectMenuPrefix + "Cloudsphere", false, 10)]
public static void CreateCloudsphereMenuItem()
{
var parent = SgtHelper.GetSelectedParent();
var cloudsphere = CreateCloudsphere(parent != null ? parent.gameObject.layer : 0, parent);
SgtHelper.SelectAndPing(cloudsphere);
}
#endif
protected virtual void OnEnable()
{
AllCloudspheres.Add(this);
Camera.onPreCull += CameraPreCull;
Camera.onPreRender += CameraPreRender;
Camera.onPostRender += CameraPostRender;
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var model = Models[i];
if (model != null)
{
model.gameObject.SetActive(true);
}
}
}
if (startCalled == true)
{
CheckUpdateCalls();
}
}
protected virtual void Start()
{
if (startCalled == false)
{
startCalled = true;
// Add a mesh?
#if UNITY_EDITOR
if (Meshes == null)
{
var mesh = SgtHelper.LoadFirstAsset<Mesh>("Geosphere40 t:mesh");
if (mesh != null)
{
Meshes = new List<Mesh>();
Meshes.Add(mesh);
}
}
#endif
CheckUpdateCalls();
}
}
protected virtual void LateUpdate()
{
// The lights and shadows may have moved, so write them
if (Material != null)
{
SgtHelper.SetTempMaterial(Material);
SgtHelper.WriteLights(Lit, Lights, 2, transform.position, null, null, SgtHelper.Brighten(Color, Brightness), 1.0f);
SgtHelper.WriteShadows(Shadows, 2);
}
}
protected virtual void OnDisable()
{
AllCloudspheres.Remove(this);
Camera.onPreCull -= CameraPreCull;
Camera.onPreRender -= CameraPreRender;
Camera.onPostRender -= CameraPostRender;
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var model = Models[i];
if (model != null)
{
model.gameObject.SetActive(false);
}
}
}
}
protected virtual void OnDestroy()
{
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
SgtCloudsphereModel.MarkForDestruction(Models[i]);
}
}
SgtHelper.Destroy(Material);
}
private void CameraPreCull(Camera camera)
{
if (Material != null)
{
UpdateMaterialNonSerialized();
}
if (CameraOffset != 0.0f)
{
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var model = Models[i];
if (model != null)
{
model.Revert();
{
var modelTransform = model.transform;
var cameraDir = (modelTransform.position - camera.transform.position).normalized;
modelTransform.position += cameraDir * CameraOffset;
}
model.Save(camera);
}
}
}
}
}
private void CameraPreRender(Camera camera)
{
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var model = Models[i];
if (model != null)
{
model.Restore(camera);
}
}
}
}
private void CameraPostRender(Camera camera)
{
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var model = Models[i];
if (model != null)
{
model.Revert();
}
}
}
}
private void UpdateMaterialNonSerialized()
{
SgtHelper.SetTempMaterial(Material);
SgtHelper.WriteShadowsNonSerialized(Shadows, 2);
}
private SgtCloudsphereModel GetOrAddModel(int index)
{
var model = default(SgtCloudsphereModel);
if (Models == null)
{
Models = new List<SgtCloudsphereModel>();
}
if (index < Models.Count)
{
model = Models[index];
if (model == null)
{
model = SgtCloudsphereModel.Create(this);
Models[index] = model;
}
}
else
{
model = SgtCloudsphereModel.Create(this);
Models.Add(model);
}
return model;
}
private void CheckUpdateCalls()
{
if (updateMaterialCalled == false)
{
UpdateMaterial();
}
if (updateModelsCalled == false)
{
UpdateModels();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using umbraco.BasePages;
using Umbraco.Core;
using Umbraco.Core.Models;
namespace Umbraco.Web.UI.Umbraco.Dialogs
{
public partial class ChangeDocType : UmbracoEnsuredPage
{
class PropertyMapping
{
public string FromName { get; set; }
public string ToName { get; set; }
public string ToAlias { get; set; }
public object Value { get; set; }
}
private IContent _content;
protected void Page_Load(object sender, EventArgs e)
{
var contentNodeId = int.Parse(Request.QueryString["id"]);
_content = ApplicationContext.Current.Services.ContentService.GetById(contentNodeId);
LocalizeTexts();
if (!Page.IsPostBack)
{
DisplayContentDetails();
if (PopulateListOfValidAlternateDocumentTypes())
{
PopulateListOfTemplates();
PopulatePropertyMappingWithSources();
PopulatePropertyMappingWithDestinations();
}
else
{
DisplayNotAvailable();
}
}
}
private void LocalizeTexts()
{
ChangeDocTypePane.Text = global::umbraco.ui.Text("changeDocType", "selectNewDocType");
ContentNamePropertyPanel.Text = global::umbraco.ui.Text("changeDocType", "selectedContent");
CurrentTypePropertyPanel.Text = global::umbraco.ui.Text("changeDocType", "currentType");
NewTypePropertyPanel.Text = global::umbraco.ui.Text("changeDocType", "newType");
NewTemplatePropertyPanel.Text = global::umbraco.ui.Text("changeDocType", "newTemplate");
ChangeDocTypePropertyMappingPane.Text = global::umbraco.ui.Text("changeDocType", "mapProperties");
ValidateAndSave.Text = global::umbraco.ui.Text("buttons", "save");
}
private void DisplayContentDetails()
{
ContentNameLabel.Text = _content.Name;
CurrentTypeLabel.Text = _content.ContentType.Name;
}
private bool PopulateListOfValidAlternateDocumentTypes()
{
// Start with all content types
var documentTypes = ApplicationContext.Current.Services.ContentTypeService.GetAllContentTypes();
// Remove invalid ones from list of potential alternatives
documentTypes = RemoveCurrentDocumentTypeFromAlternatives(documentTypes);
documentTypes = RemoveInvalidByParentDocumentTypesFromAlternatives(documentTypes);
documentTypes = RemoveInvalidByChildrenDocumentTypesFromAlternatives(documentTypes);
// If we have at least one, bind to list and return true
if (documentTypes.Any())
{
NewDocumentTypeList.DataSource = documentTypes.OrderBy(x => x.Name);
NewDocumentTypeList.DataValueField = "Id";
NewDocumentTypeList.DataTextField = "Name";
NewDocumentTypeList.DataBind();
return true;
}
return false;
}
private IEnumerable<IContentType> RemoveCurrentDocumentTypeFromAlternatives(IEnumerable<IContentType> documentTypes)
{
return documentTypes
.Where(x => x.Id != _content.ContentType.Id);
}
private IEnumerable<IContentType> RemoveInvalidByParentDocumentTypesFromAlternatives(IEnumerable<IContentType> documentTypes)
{
if (_content.ParentId == -1)
{
// Root content, only include those that have been selected as allowed at root
return documentTypes
.Where(x => x.AllowedAsRoot);
}
else
{
// Below root, so only include those allowed as sub-nodes for the parent
var parentNode = ApplicationContext.Current.Services.ContentService.GetById(_content.ParentId);
return documentTypes
.Where(x => parentNode.ContentType.AllowedContentTypes
.Select(y => y.Id.Value)
.Contains(x.Id));
}
}
private IEnumerable<IContentType> RemoveInvalidByChildrenDocumentTypesFromAlternatives(IEnumerable<IContentType> documentTypes)
{
var docTypeIdsOfChildren = _content.Children()
.Select(x => x.ContentType.Id)
.Distinct()
.ToList();
return documentTypes
.Where(x => x.AllowedContentTypes
.Select(y => y.Id.Value)
.ContainsAll(docTypeIdsOfChildren));
}
private void PopulateListOfTemplates()
{
// Get selected new document type
var contentType = GetSelectedDocumentType();
// Populate template list
NewTemplateList.DataSource = contentType.AllowedTemplates;
NewTemplateList.DataValueField = "Id";
NewTemplateList.DataTextField = "Name";
NewTemplateList.DataBind();
NewTemplateList.Items.Add(new ListItem("<" + global::umbraco.ui.Text("changeDocType", "none") + ">", "0"));
// Set default template
if (contentType.DefaultTemplate != null)
{
var itemToSelect = NewTemplateList.Items.FindByValue(contentType.DefaultTemplate.Id.ToString());
if (itemToSelect != null)
{
itemToSelect.Selected = true;
}
}
}
private void PopulatePropertyMappingWithSources()
{
PropertyMappingRepeater.DataSource = GetPropertiesOfContentType(_content.ContentType);
PropertyMappingRepeater.DataBind();
}
private void PopulatePropertyMappingWithDestinations()
{
// Get selected new document type
var contentType = GetSelectedDocumentType();
// Get properties of new document type (including any from parent types)
var properties = GetPropertiesOfContentType(contentType);
// Loop through list of source properties and populate destination options with all those of same property type
foreach (RepeaterItem ri in PropertyMappingRepeater.Items)
{
if (ri.ItemType == ListItemType.Item || ri.ItemType == ListItemType.AlternatingItem)
{
// Get data type from hidden field
var propEdAlias = ((HiddenField)ri.FindControl("PropertyEditorAlias")).Value;
// Bind destination list with properties that match data type
var ddl = (DropDownList)ri.FindControl("DestinationProperty");
ddl.DataSource = properties.Where(x => x.PropertyEditorAlias == propEdAlias);
ddl.DataValueField = "Alias";
ddl.DataTextField = "Name";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("<" + global::umbraco.ui.Text("changeDocType", "none") + ">", string.Empty));
// Set default selection to be one with matching alias
var alias = ((HiddenField)ri.FindControl("Alias")).Value;
var item = ddl.Items.FindByValue(alias);
if (item != null)
{
item.Selected = true;
}
}
}
}
private IContentType GetSelectedDocumentType()
{
return ApplicationContext.Current.Services.ContentTypeService.GetContentType(int.Parse(NewDocumentTypeList.SelectedItem.Value));
}
private IEnumerable<PropertyType> GetPropertiesOfContentType(IContentType contentType)
{
var properties = contentType.PropertyTypes.ToList();
while (contentType.ParentId > -1)
{
contentType = ApplicationContext.Current.Services.ContentTypeService.GetContentType(contentType.ParentId);
properties.AddRange(contentType.PropertyTypes);
}
return properties.OrderBy(x => x.Name);
}
private void DisplayNotAvailable()
{
NewTypePropertyPanel.Visible = false;
NewTemplatePropertyPanel.Visible = false;
SavePlaceholder.Visible = false;
NotAvailablePlaceholder.Visible = true;
ChangeDocTypePropertyMappingPane.Visible = false;
}
protected void NewDocumentTypeList_SelectedIndexChanged(object sender, EventArgs e)
{
PopulateListOfTemplates();
PopulatePropertyMappingWithDestinations();
}
protected void ValidateAndSave_Click(object sender, EventArgs e)
{
if (IsPropertyMappingValid())
{
// For all properties to be mapped, save the values to a temporary list
var propertyMappings = SavePropertyMappings();
// Get flag for if content already published
var wasPublished = _content.Published;
// Change the document type passing flag to clear the properties
var newContentType = GetSelectedDocumentType();
_content.ChangeContentType(newContentType, true);
// Set the template if one has been selected
if (NewTemplateList.SelectedItem != null)
{
var templateId = int.Parse(NewTemplateList.SelectedItem.Value);
_content.Template = templateId > 0 ? ApplicationContext.Current.Services.FileService.GetTemplate(templateId) : null;
}
// Set the property values
var propertiesMappedMessageBuilder = new StringBuilder("<ul>");
foreach (var propertyMapping in propertyMappings)
{
propertiesMappedMessageBuilder.AppendFormat("<li>{0} {1} {2}</li>",
propertyMapping.FromName, global::umbraco.ui.Text("changeDocType", "to"), propertyMapping.ToName);
_content.SetValue(propertyMapping.ToAlias, propertyMapping.Value);
}
propertiesMappedMessageBuilder.Append("</ul>");
// Save
var user = global::umbraco.BusinessLogic.User.GetCurrent();
ApplicationContext.Current.Services.ContentService.Save(_content, user.Id);
// Publish if the content was already published
if (wasPublished)
{
ApplicationContext.Current.Services.ContentService.Publish(_content, user.Id);
}
// Sync the tree
ClientTools.SyncTree(_content.Path, true);
// Reload the page if the content was already being viewed
ClientTools.ReloadContentFrameUrlIfPathLoaded("/editContent.aspx?id=" + _content.Id);
// Display success message
SuccessMessage.Text = global::umbraco.ui.Text("changeDocType", "successMessage").Replace("[new type]", "<strong>" + newContentType.Name + "</strong>");
PropertiesMappedMessage.Text = propertiesMappedMessageBuilder.ToString();
if (wasPublished)
{
ContentPublishedMessage.Text = global::umbraco.ui.Text("changeDocType", "contentRepublished");
ContentPublishedMessage.Visible = true;
}
else
{
ContentPublishedMessage.Visible = false;
}
SuccessPlaceholder.Visible = true;
SaveAndCancelPlaceholder.Visible = false;
ValidationPlaceholder.Visible = false;
ChangeDocTypePane.Visible = false;
ChangeDocTypePropertyMappingPane.Visible = false;
}
else
{
ValidationPlaceholder.Visible = true;
}
}
private bool IsPropertyMappingValid()
{
// Check whether any properties have been mapped to more than once
var mappedPropertyAliases = new List<string>();
foreach (RepeaterItem ri in PropertyMappingRepeater.Items)
{
if (ri.ItemType == ListItemType.Item || ri.ItemType == ListItemType.AlternatingItem)
{
var ddl = (DropDownList)ri.FindControl("DestinationProperty");
var mappedPropertyAlias = ddl.SelectedItem.Value;
if (!string.IsNullOrEmpty(mappedPropertyAlias))
{
if (mappedPropertyAliases.Contains(mappedPropertyAlias))
{
ValidationError.Text = global::umbraco.ui.Text("changeDocType", "validationErrorPropertyWithMoreThanOneMapping");
return false;
}
mappedPropertyAliases.Add(mappedPropertyAlias);
}
}
}
return true;
}
private IList<PropertyMapping> SavePropertyMappings()
{
// Create list of mapped property values for assignment after the document type is changed
var mappedPropertyValues = new List<PropertyMapping>();
foreach (RepeaterItem ri in PropertyMappingRepeater.Items)
{
if (ri.ItemType == ListItemType.Item || ri.ItemType == ListItemType.AlternatingItem)
{
// Get property alias to map to
var ddl = (DropDownList)ri.FindControl("DestinationProperty");
var mappedAlias = ddl.SelectedItem.Value;
if (!string.IsNullOrEmpty(mappedAlias))
{
// If mapping property, get current property value from alias
var sourceAlias = ((HiddenField)ri.FindControl("Alias")).Value;
var sourcePropertyValue = _content.GetValue(sourceAlias);
// Add to list
mappedPropertyValues.Add(new PropertyMapping
{
FromName = ((HiddenField)ri.FindControl("Name")).Value,
ToName = ddl.SelectedItem.Text,
ToAlias = mappedAlias,
Value = sourcePropertyValue
});
}
}
}
return mappedPropertyValues;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Security.Permissions;
using System.Windows.Forms;
namespace SIL.Windows.Forms.Widgets
{
[ProvideProperty("Prompt", typeof (Control))]
public class Prompt: Component, IExtenderProvider
{
private readonly Dictionary<Control, PromptPainter> _extendees;
public Prompt()
{
_extendees = new Dictionary<Control, PromptPainter>();
}
#region IExtenderProvider Members
public bool CanExtend(object extendee)
{
VerifyNotDisposed();
return extendee is TextBoxBase;
}
#endregion
[DefaultValue("")]
public string GetPrompt(Control c)
{
if (c == null)
{
throw new ArgumentNullException();
}
if (!CanExtend(c))
{
throw new ArgumentException("Control must be derived from TextBoxBase");
}
PromptPainter value;
if (_extendees.TryGetValue(c, out value))
{
return value.Prompt;
}
return string.Empty;
}
public void SetPrompt(Control c, string value)
{
if (c == null)
{
throw new ArgumentNullException();
}
if (!CanExtend(c))
{
throw new ArgumentException("Control must be derived from TextBoxBase");
}
if (String.IsNullOrEmpty(value))
{
_extendees.Remove(c);
}
else
{
if (_extendees.ContainsKey(c))
{
_extendees[c].Prompt = value;
}
else
{
_extendees[c] = new PromptPainter(c, value);
}
}
}
public bool GetIsPromptVisible(Control c)
{
if (c == null)
{
throw new ArgumentNullException();
}
if (!CanExtend(c))
{
throw new ArgumentException("Control must be derived from TextBoxBase");
}
PromptPainter value;
if (_extendees.TryGetValue(c, out value))
{
return value.ShouldShowPrompt(c);
}
return false;
}
#region IComponent Members
public override ISite Site
{
get
{
VerifyNotDisposed();
return base.Site;
}
set
{
VerifyNotDisposed();
base.Site = value;
}
}
private bool _isDisposed = false;
protected override void Dispose(bool disposing)
{
if (_isDisposed)
return;
if (disposing)
{
_extendees.Clear();
_isDisposed = true;
}
base.Dispose(disposing);
}
private void VerifyNotDisposed()
{
if (_isDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
}
#endregion
#region Nested type: PromptPainter
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
private class PromptPainter: NativeWindow, IDisposable
{
private readonly Control _control;
private bool _hasFocus;
private string _prompt;
public PromptPainter(Control c, string prompt)
{
if (c.IsHandleCreated)
{
AssignHandle(c.Handle);
}
c.HandleCreated += ControlHandleCreated;
c.HandleDestroyed += ControlHandleDestroyed;
_control = c;
Prompt = prompt;
}
private void ControlHandleCreated(object sender, EventArgs e)
{
AssignHandle(((Control)sender).Handle);
}
private void ControlHandleDestroyed(object sender, EventArgs e)
{
ReleaseHandle();
}
public string Prompt
{
get { return _prompt; }
set { _prompt = value; }
}
public bool Focused
{
get
{
return _hasFocus;
}
}
protected override void WndProc(ref Message m)
{
const int WM_PAINT = 0xF;
const int WM_SETFOCUS = 0x7;
const int WM_KILLFOCUS = 0x8;
base.WndProc(ref m);
switch (m.Msg)
{
case WM_SETFOCUS:
_hasFocus = true;
_control.Invalidate();
break;
case WM_KILLFOCUS:
_hasFocus = false;
_control.Invalidate();
break;
case WM_PAINT:
OnWmPaint();
break;
}
}
private void OnWmPaint()
{
if (ShouldShowPrompt(_control))
{
using (Graphics g = (_control is ComboBox)?_control.CreateGraphics():Graphics.FromHwnd(Handle))
{
TextFormatFlags flags = GetTextFormatFlags(_control);
Rectangle bounds = _control.ClientRectangle;
bounds.Inflate(-1, 0);
TextRenderer.DrawText(g,
Prompt,
_control.Font,
bounds,
SystemColors.GrayText,
_control.BackColor,
flags);
}
}
}
private static TextFormatFlags GetTextFormatFlags(Control c)
{
TextFormatFlags flags = TextFormatFlags.TextBoxControl | TextFormatFlags.NoPadding |
TextFormatFlags.WordBreak;
HorizontalAlignment horizontalAlignment = HorizontalAlignment.Left;
TextBox textbox = c as TextBox;
if (textbox != null)
{
horizontalAlignment = textbox.TextAlign;
}
else
{
RichTextBox richtextbox = c as RichTextBox;
if (richtextbox != null)
{
horizontalAlignment = richtextbox.SelectionAlignment;
}
}
switch (horizontalAlignment)
{
case HorizontalAlignment.Center:
flags |= TextFormatFlags.HorizontalCenter;
break;
case HorizontalAlignment.Left:
flags |= TextFormatFlags.Left;
break;
case HorizontalAlignment.Right:
flags |= TextFormatFlags.Right;
break;
}
if (IsControlRightToLeft(c))
{
flags |= TextFormatFlags.RightToLeft;
}
return flags;
}
public bool ShouldShowPrompt(Control c)
{
return (!Focused && String.IsNullOrEmpty(c.Text));
}
private static bool IsControlRightToLeft(Control control)
{
while (control != null)
{
switch (control.RightToLeft)
{
case RightToLeft.Yes:
return true;
case RightToLeft.No:
return false;
case RightToLeft.Inherit:
control = control.Parent;
break;
}
}
return false;
}
#region IDisposable Members
private bool _disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this._disposed)
{
if (disposing)
{
// dispose-only, i.e. non-finalizable logic
_control.HandleCreated -= ControlHandleCreated;
_control.HandleDestroyed -= ControlHandleDestroyed;
if(Handle != IntPtr.Zero)
{
ReleaseHandle();
}
}
// shared (dispose and finalizable) cleanup logic
this._disposed = true;
}
}
#endregion
}
#endregion
}
}
| |
/* ====================================================================
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.Collections;
using System.Drawing;
namespace fyiReporting.RDL
{
///<summary>
/// Bar chart definition and processing.
///</summary>
internal class ChartBar: ChartBase
{
int _GapSize = 6; // TODO: hard code for now
internal ChartBar(Report r, Row row, Chart c, MatrixCellEntry[,] m, Expression showTooltips, Expression showTooltipsX,Expression _ToolTipYFormat, Expression _ToolTipXFormat)
: base(r, row, c, m,showTooltips,showTooltipsX,_ToolTipYFormat,_ToolTipXFormat)
{
}
override internal void Draw(Report rpt)
{
CreateSizedBitmap();
//AJM GJL 14082008 Using Vector Graphics
using (Graphics g1 = Graphics.FromImage(_bm))
{
_aStream = new System.IO.MemoryStream();
IntPtr HDC = g1.GetHdc();
_mf = new System.Drawing.Imaging.Metafile(_aStream, HDC, new RectangleF(0, 0, _bm.Width, _bm.Height), System.Drawing.Imaging.MetafileFrameUnit.Pixel);
g1.ReleaseHdc(HDC);
}
using (Graphics g = Graphics.FromImage(_mf))
{
// 06122007AJM Used to Force Higher Quality
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
// Adjust the top margin to depend on the title height
Size titleSize = DrawTitleMeasure(rpt, g, ChartDefn.Title);
Layout.TopMargin = titleSize.Height;
double max=0,min=0; // Get the max and min values
// 20022008 AJM GJL - Now requires Y axis identifier
GetValueMaxMin(rpt, ref max, ref min, 0,1);
DrawChartStyle(rpt, g);
// Draw title; routine determines if necessary
DrawTitle(rpt, g, ChartDefn.Title, new System.Drawing.Rectangle(0, 0, _bm.Width, Layout.TopMargin));
// Adjust the left margin to depend on the Category Axis
Size caSize = CategoryAxisSize(rpt, g);
Layout.LeftMargin = caSize.Width;
// Adjust the bottom margin to depend on the Value Axis
Size vaSize = ValueAxisSize(rpt, g, min, max);
Layout.BottomMargin = vaSize.Height;
// Draw legend
System.Drawing.Rectangle lRect = DrawLegend(rpt, g, false, true);
// 20022008 AJM GJL - Requires Rpt and Graphics
AdjustMargins(lRect,rpt,g ); // Adjust margins based on legend.
// Draw Plot area
DrawPlotAreaStyle(rpt, g, lRect);
// Draw Value Axis
if (vaSize.Width > 0) // If we made room for the axis - we need to draw it
DrawValueAxis(rpt, g, min, max,
new System.Drawing.Rectangle(Layout.LeftMargin, _bm.Height-Layout.BottomMargin, _bm.Width - Layout.LeftMargin - Layout.RightMargin, vaSize.Height), Layout.TopMargin, _bm.Height - Layout.BottomMargin);
// Draw Category Axis
if (caSize.Height > 0)
DrawCategoryAxis(rpt, g,
new System.Drawing.Rectangle(Layout.LeftMargin - caSize.Width, Layout.TopMargin, caSize.Width, _bm.Height - Layout.TopMargin - Layout.BottomMargin));
if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.Stacked)
DrawPlotAreaStacked(rpt, g, min, max);
else if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.PercentStacked)
DrawPlotAreaPercentStacked(rpt, g);
else
DrawPlotAreaPlain(rpt, g, min, max);
DrawLegend(rpt, g, false, false); // after the plot is drawn
}
}
void DrawPlotAreaPercentStacked(Report rpt, Graphics g)
{
int barsNeeded = CategoryCount;
int gapsNeeded = CategoryCount * 2;
// Draw Plot area data
double max = 1;
int heightBar = (int) ((Layout.PlotArea.Height - gapsNeeded*_GapSize) / barsNeeded);
int maxBarWidth = (int) (Layout.PlotArea.Width);
// Loop thru calculating all the data points
for (int iRow = 1; iRow <= CategoryCount; iRow++)
{
int barLoc=(int) (Layout.PlotArea.Top + (iRow-1) * ((double) (Layout.PlotArea.Height) / CategoryCount));
barLoc += _GapSize; // space before series
double sum=0;
for (int iCol = 1; iCol <= SeriesCount; iCol++)
{
sum += GetDataValue(rpt, iRow, iCol);
}
double v=0;
int saveX=0;
double t=0;
for (int iCol = 1; iCol <= SeriesCount; iCol++)
{
t = GetDataValue(rpt, iRow, iCol);
v += t;
int x = (int) ((Math.Min(v/sum,max) / max) * maxBarWidth);
System.Drawing.Rectangle rect;
rect = new System.Drawing.Rectangle(Layout.PlotArea.Left + saveX, barLoc, x - saveX, heightBar);
DrawColumnBar(rpt, g,
GetSeriesBrush(rpt, iRow, iCol),
rect, iRow, iCol);
//Add a metafilecomment to use as a tooltip GJL 26092008
if (_showToolTips)
{
String val = "ToolTip:" + t.ToString(_tooltipYFormat) + "|X:" + (int)rect.X + "|Y:" + (int)rect.Y + "|W:" + rect.Width + "|H:" + rect.Height;
g.AddMetafileComment(new System.Text.ASCIIEncoding().GetBytes(val));
}
saveX = x;
}
}
return;
}
void DrawPlotAreaPlain(Report rpt, Graphics g, double min, double max)
{
int barsNeeded = SeriesCount * CategoryCount;
int gapsNeeded = CategoryCount * 2;
// Draw Plot area data
int heightBar = (int) ((Layout.PlotArea.Height - gapsNeeded*_GapSize) / barsNeeded);
int maxBarWidth = (int) (Layout.PlotArea.Width);
//int barLoc=Layout.LeftMargin;
for (int iRow=1; iRow <= CategoryCount; iRow++)
{
int barLoc=(int) (Layout.PlotArea.Top + (iRow-1) * ((double) (Layout.PlotArea.Height) / CategoryCount));
barLoc += _GapSize; // space before series
for (int iCol=1; iCol <= SeriesCount; iCol++)
{
double v = this.GetDataValue(rpt, iRow, iCol);
int x = (int) (((Math.Min(v,max)-min) / (max-min)) * maxBarWidth);
DrawColumnBar(rpt, g, GetSeriesBrush(rpt, iRow, iCol),
new System.Drawing.Rectangle(Layout.PlotArea.Left, barLoc, x, heightBar), iRow, iCol);
//Add a metafilecomment to use as a tooltip GJL 26092008
if (_showToolTips)
{
String val = "ToolTip:" + v.ToString(_tooltipYFormat) + "|X:" + (int)Layout.PlotArea.Left + "|Y:" + (int)(barLoc) + "|W:" + x + "|H:" + heightBar;
g.AddMetafileComment(new System.Text.ASCIIEncoding().GetBytes(val));
}
barLoc += heightBar;
}
}
return;
}
void DrawPlotAreaStacked(Report rpt, Graphics g, double min, double max)
{
int barsNeeded = CategoryCount;
int gapsNeeded = CategoryCount * 2;
int heightBar = (int) ((Layout.PlotArea.Height - gapsNeeded*_GapSize) / barsNeeded);
int maxBarWidth = (int) (Layout.PlotArea.Width);
// Loop thru calculating all the data points
for (int iRow = 1; iRow <= CategoryCount; iRow++)
{
int barLoc=(int) (Layout.PlotArea.Top + (iRow-1) * ((double) (Layout.PlotArea.Height) / CategoryCount));
barLoc += _GapSize; // space before series
double v=0;
double t = 0;
int saveX=0;
for (int iCol = 1; iCol <= SeriesCount; iCol++)
{
t = GetDataValue(rpt, iRow, iCol);
v += t;
int x = (int) (((Math.Min(v,max)-min) / (max-min)) * maxBarWidth);
System.Drawing.Rectangle rect;
rect = new System.Drawing.Rectangle(Layout.PlotArea.Left + saveX, barLoc, x - saveX, heightBar);
DrawColumnBar(rpt, g, GetSeriesBrush(rpt, iRow, iCol), rect, iRow, iCol);
if (_showToolTips)
{
String val = "ToolTip:" + v.ToString(_tooltipYFormat) + "|X:" + (int)rect.X + "|Y:" + (int)rect.Y + "|W:" + rect.Width + "|H:" + rect.Height;
g.AddMetafileComment(new System.Text.ASCIIEncoding().GetBytes(val));
}
saveX = x;
}
}
return;
}
// Calculate the size of the category axis
Size CategoryAxisSize(Report rpt, Graphics g)
{
_LastCategoryWidth = 0;
Size size=Size.Empty;
if (this.ChartDefn.CategoryAxis == null)
return size;
Axis a = this.ChartDefn.CategoryAxis.Axis;
if (a == null)
return size;
Style s = a.Style;
// Measure the title
size = DrawTitleMeasure(rpt, g, a.Title);
if (!a.Visible) // don't need to calculate the height
return size;
// Calculate the tallest category name
TypeCode tc;
int maxWidth=0;
for (int iRow=1; iRow <= CategoryCount; iRow++)
{
object v = this.GetCategoryValue(rpt, iRow, out tc);
Size tSize;
if (s == null)
tSize = Style.MeasureStringDefaults(rpt, g, v, tc, null, int.MaxValue);
else
tSize =s.MeasureString(rpt, g, v, tc, null, int.MaxValue);
if (tSize.Width > maxWidth)
maxWidth = tSize.Width;
if (iRow == CategoryCount)
_LastCategoryWidth = tSize.Width;
}
// Add on the widest category name
size.Width += maxWidth;
return size;
}
// DrawCategoryAxis
void DrawCategoryAxis(Report rpt, Graphics g, System.Drawing.Rectangle rect)
{
if (this.ChartDefn.CategoryAxis == null)
return;
Axis a = this.ChartDefn.CategoryAxis.Axis;
if (a == null)
return;
Style s = a.Style;
Size tSize = DrawTitleMeasure(rpt, g, a.Title);
DrawTitle(rpt, g, a.Title,
new System.Drawing.Rectangle(rect.Left, rect.Top, tSize.Width, rect.Height));
int drawHeight = rect.Height / CategoryCount;
TypeCode tc;
for (int iRow=1; iRow <= CategoryCount; iRow++)
{
object v = this.GetCategoryValue(rpt, iRow, out tc);
int drawLoc=(int) (rect.Top + (iRow-1) * ((double) rect.Height / CategoryCount));
// Draw the category text
if (a.Visible)
{
System.Drawing.Rectangle drawRect = new System.Drawing.Rectangle(rect.Left + tSize.Width, drawLoc, rect.Width-tSize.Width, drawHeight);
if (s == null)
Style.DrawStringDefaults(g, v, drawRect);
else
s.DrawString(rpt, g, v, tc, null, drawRect);
}
// Draw the Major Tick Marks (if necessary)
DrawCategoryAxisTick(g, true, a.MajorTickMarks, new Point(rect.Right, drawLoc));
}
// Draw the end on (if necessary)
DrawCategoryAxisTick(g, true, a.MajorTickMarks, new Point(rect.Right, rect.Bottom));
return;
}
protected void DrawCategoryAxisTick(Graphics g, bool bMajor, AxisTickMarksEnum tickType, Point p)
{
int len = bMajor? AxisTickMarkMajorLen: AxisTickMarkMinorLen;
switch (tickType)
{
case AxisTickMarksEnum.Outside:
g.DrawLine(Pens.Black, new Point(p.X, p.Y), new Point(p.X-len, p.Y));
break;
case AxisTickMarksEnum.Inside:
g.DrawLine(Pens.Black, new Point(p.X, p.Y), new Point(p.X+len, p.Y));
break;
case AxisTickMarksEnum.Cross:
g.DrawLine(Pens.Black, new Point(p.X-len, p.Y), new Point(p.X+len, p.Y));
break;
case AxisTickMarksEnum.None:
default:
break;
}
return;
}
void DrawColumnBar(Report rpt, Graphics g, Brush brush, System.Drawing.Rectangle rect, int iRow, int iCol)
{
g.FillRectangle(brush, rect);
g.DrawRectangle(Pens.Black, rect);
if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.Stacked ||
(ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.PercentStacked)
{
DrawDataPoint(rpt, g, rect, iRow, iCol);
}
else
{
Point p;
p = new Point(rect.Right, rect.Top);
DrawDataPoint(rpt, g, p, iRow, iCol);
}
return;
}
protected void DrawValueAxis(Report rpt, Graphics g, double min, double max, System.Drawing.Rectangle rect, int plotTop, int plotBottom)
{
if (this.ChartDefn.ValueAxis == null)
return;
Axis a = this.ChartDefn.ValueAxis.Axis;
if (a == null)
return;
Style s = a.Style;
// Account for tick marks
int tickSize=0;
if (a.MajorTickMarks == AxisTickMarksEnum.Cross ||
a.MajorTickMarks == AxisTickMarksEnum.Outside)
tickSize = this.AxisTickMarkMajorLen;
else if (a.MinorTickMarks == AxisTickMarksEnum.Cross ||
a.MinorTickMarks == AxisTickMarksEnum.Outside)
tickSize += this.AxisTickMarkMinorLen;
int intervalCount;
double incr;
SetIncrementAndInterval(rpt, a, min, max, out incr, out intervalCount); // Calculate the interval count
int maxValueHeight = 0;
double v = min;
Size size= Size.Empty;
for (int i = 0; i < intervalCount+1; i++)
{
int x = (int) (((Math.Min(v,max)-min) / (max-min)) * rect.Width);
if (!a.Visible)
{
// nothing to do
}
else if (s != null)
{
size = s.MeasureString(rpt, g, v, TypeCode.Double, null, int.MaxValue);
System.Drawing.Rectangle vRect =
new System.Drawing.Rectangle(rect.Left + x - size.Width/2, rect.Top+tickSize, size.Width, size.Height);
s.DrawString(rpt, g, v, TypeCode.Double, null, vRect);
}
else
{
size = Style.MeasureStringDefaults(rpt, g, v, TypeCode.Double, null, int.MaxValue);
System.Drawing.Rectangle vRect =
new System.Drawing.Rectangle(rect.Left + x - size.Width/2, rect.Top+tickSize, size.Width, size.Height);
Style.DrawStringDefaults(g, v, vRect);
}
if (size.Height > maxValueHeight) // Need to keep track of the maximum height
maxValueHeight = size.Height; // this is probably overkill since it should always be the same??
DrawValueAxisGrid(rpt, g, a.MajorGridLines, new Point(rect.Left + x, plotTop), new Point(rect.Left + x, plotBottom));
DrawValueAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(rect.Left + x, plotBottom ));
v += incr;
}
// Draw the end points of the major grid lines
DrawValueAxisGrid(rpt, g, a.MajorGridLines, new Point(rect.Left, plotTop), new Point(rect.Left, plotBottom));
DrawValueAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(rect.Left, plotBottom));
DrawValueAxisGrid(rpt, g, a.MajorGridLines, new Point(rect.Right, plotTop), new Point(rect.Right, plotBottom));
DrawValueAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(rect.Right, plotBottom));
Size tSize = DrawTitleMeasure(rpt, g, a.Title);
DrawTitle(rpt, g, a.Title,
new System.Drawing.Rectangle(rect.Left, rect.Top+maxValueHeight+tickSize, rect.Width, tSize.Height));
return;
}
protected void DrawValueAxisGrid(Report rpt, Graphics g, ChartGridLines gl, Point s, Point e)
{
if (gl == null || !gl.ShowGridLines)
return;
if (gl.Style != null)
gl.Style.DrawStyleLine(rpt, g, null, s, e);
else
g.DrawLine(Pens.Black, s, e);
return;
}
protected void DrawValueAxisTick(Report rpt, Graphics g, bool bMajor, AxisTickMarksEnum tickType, ChartGridLines gl, Point p)
{
if (tickType == AxisTickMarksEnum.None)
return;
int len = bMajor? AxisTickMarkMajorLen: AxisTickMarkMinorLen;
Point s, e;
switch (tickType)
{
case AxisTickMarksEnum.Inside:
s = new Point(p.X, p.Y);
e = new Point(p.X, p.Y-len);
break;
case AxisTickMarksEnum.Cross:
s = new Point(p.X, p.Y-len);
e = new Point(p.X, p.Y+len);
break;
case AxisTickMarksEnum.Outside:
default:
s = new Point(p.X, p.Y+len);
e = new Point(p.X, p.Y);
break;
}
Style style = gl.Style;
if (style != null)
style.DrawStyleLine(rpt, g, null, s, e);
else
g.DrawLine(Pens.Black, s, e);
return;
}
// Calculate the size of the value axis; width is max value width + title width
// height is max value height
protected Size ValueAxisSize(Report rpt, Graphics g, double min, double max)
{
Size size=Size.Empty;
if (ChartDefn.ValueAxis == null)
return size;
Axis a = ChartDefn.ValueAxis.Axis;
if (a == null)
return size;
Size minSize;
Size maxSize;
if (!a.Visible)
{
minSize = maxSize = Size.Empty;
}
else if (a.Style != null)
{
minSize = a.Style.MeasureString(rpt, g, min, TypeCode.Double, null, int.MaxValue);
maxSize = a.Style.MeasureString(rpt, g, max, TypeCode.Double, null, int.MaxValue);
}
else
{
minSize = Style.MeasureStringDefaults(rpt, g, min, TypeCode.Double, null, int.MaxValue);
maxSize = Style.MeasureStringDefaults(rpt, g, max, TypeCode.Double, null, int.MaxValue);
}
// Choose the largest
size.Width = Math.Max(minSize.Width, maxSize.Width);
size.Height = Math.Max(minSize.Height, maxSize.Height);
// Now we need to add in the height of the title (if any)
Size titleSize = DrawTitleMeasure(rpt, g, a.Title);
size.Height += titleSize.Height;
if (a.MajorTickMarks == AxisTickMarksEnum.Cross ||
a.MajorTickMarks == AxisTickMarksEnum.Outside)
size.Height += this.AxisTickMarkMajorLen;
else if (a.MinorTickMarks == AxisTickMarksEnum.Cross ||
a.MinorTickMarks == AxisTickMarksEnum.Outside)
size.Height += this.AxisTickMarkMinorLen;
return size;
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// MobileResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Api.V2010.Account.AvailablePhoneNumberCountry
{
public class MobileResource : Resource
{
private static Request BuildReadRequest(ReadMobileOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Api,
"/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/AvailablePhoneNumbers/" + options.PathCountryCode + "/Mobile.json",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Mobile parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Mobile </returns>
public static ResourceSet<MobileResource> Read(ReadMobileOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<MobileResource>.FromJson("available_phone_numbers", response.Content);
return new ResourceSet<MobileResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Mobile parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Mobile </returns>
public static async System.Threading.Tasks.Task<ResourceSet<MobileResource>> ReadAsync(ReadMobileOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<MobileResource>.FromJson("available_phone_numbers", response.Content);
return new ResourceSet<MobileResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathCountryCode"> The ISO Country code of the country from which to read phone numbers </param>
/// <param name="pathAccountSid"> The SID of the Account requesting the AvailablePhoneNumber resources </param>
/// <param name="areaCode"> The area code of the phone numbers to read </param>
/// <param name="contains"> The pattern on which to match phone numbers </param>
/// <param name="smsEnabled"> Whether the phone numbers can receive text messages </param>
/// <param name="mmsEnabled"> Whether the phone numbers can receive MMS messages </param>
/// <param name="voiceEnabled"> Whether the phone numbers can receive calls. </param>
/// <param name="excludeAllAddressRequired"> Whether to exclude phone numbers that require an Address </param>
/// <param name="excludeLocalAddressRequired"> Whether to exclude phone numbers that require a local address </param>
/// <param name="excludeForeignAddressRequired"> Whether to exclude phone numbers that require a foreign address
/// </param>
/// <param name="beta"> Whether to read phone numbers new to the Twilio platform </param>
/// <param name="nearNumber"> Given a phone number, find a geographically close number within distance miles.
/// (US/Canada only) </param>
/// <param name="nearLatLong"> Given a latitude/longitude pair lat,long find geographically close numbers within
/// distance miles. (US/Canada only) </param>
/// <param name="distance"> The search radius, in miles, for a near_ query. (US/Canada only) </param>
/// <param name="inPostalCode"> Limit results to a particular postal code. (US/Canada only) </param>
/// <param name="inRegion"> Limit results to a particular region. (US/Canada only) </param>
/// <param name="inRateCenter"> Limit results to a specific rate center, or given a phone number search within the same
/// rate center as that number. (US/Canada only) </param>
/// <param name="inLata"> Limit results to a specific local access and transport area. (US/Canada only) </param>
/// <param name="inLocality"> Limit results to a particular locality </param>
/// <param name="faxEnabled"> Whether the phone numbers can receive faxes </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Mobile </returns>
public static ResourceSet<MobileResource> Read(string pathCountryCode,
string pathAccountSid = null,
int? areaCode = null,
string contains = null,
bool? smsEnabled = null,
bool? mmsEnabled = null,
bool? voiceEnabled = null,
bool? excludeAllAddressRequired = null,
bool? excludeLocalAddressRequired = null,
bool? excludeForeignAddressRequired = null,
bool? beta = null,
Types.PhoneNumber nearNumber = null,
string nearLatLong = null,
int? distance = null,
string inPostalCode = null,
string inRegion = null,
string inRateCenter = null,
string inLata = null,
string inLocality = null,
bool? faxEnabled = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadMobileOptions(pathCountryCode){PathAccountSid = pathAccountSid, AreaCode = areaCode, Contains = contains, SmsEnabled = smsEnabled, MmsEnabled = mmsEnabled, VoiceEnabled = voiceEnabled, ExcludeAllAddressRequired = excludeAllAddressRequired, ExcludeLocalAddressRequired = excludeLocalAddressRequired, ExcludeForeignAddressRequired = excludeForeignAddressRequired, Beta = beta, NearNumber = nearNumber, NearLatLong = nearLatLong, Distance = distance, InPostalCode = inPostalCode, InRegion = inRegion, InRateCenter = inRateCenter, InLata = inLata, InLocality = inLocality, FaxEnabled = faxEnabled, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathCountryCode"> The ISO Country code of the country from which to read phone numbers </param>
/// <param name="pathAccountSid"> The SID of the Account requesting the AvailablePhoneNumber resources </param>
/// <param name="areaCode"> The area code of the phone numbers to read </param>
/// <param name="contains"> The pattern on which to match phone numbers </param>
/// <param name="smsEnabled"> Whether the phone numbers can receive text messages </param>
/// <param name="mmsEnabled"> Whether the phone numbers can receive MMS messages </param>
/// <param name="voiceEnabled"> Whether the phone numbers can receive calls. </param>
/// <param name="excludeAllAddressRequired"> Whether to exclude phone numbers that require an Address </param>
/// <param name="excludeLocalAddressRequired"> Whether to exclude phone numbers that require a local address </param>
/// <param name="excludeForeignAddressRequired"> Whether to exclude phone numbers that require a foreign address
/// </param>
/// <param name="beta"> Whether to read phone numbers new to the Twilio platform </param>
/// <param name="nearNumber"> Given a phone number, find a geographically close number within distance miles.
/// (US/Canada only) </param>
/// <param name="nearLatLong"> Given a latitude/longitude pair lat,long find geographically close numbers within
/// distance miles. (US/Canada only) </param>
/// <param name="distance"> The search radius, in miles, for a near_ query. (US/Canada only) </param>
/// <param name="inPostalCode"> Limit results to a particular postal code. (US/Canada only) </param>
/// <param name="inRegion"> Limit results to a particular region. (US/Canada only) </param>
/// <param name="inRateCenter"> Limit results to a specific rate center, or given a phone number search within the same
/// rate center as that number. (US/Canada only) </param>
/// <param name="inLata"> Limit results to a specific local access and transport area. (US/Canada only) </param>
/// <param name="inLocality"> Limit results to a particular locality </param>
/// <param name="faxEnabled"> Whether the phone numbers can receive faxes </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Mobile </returns>
public static async System.Threading.Tasks.Task<ResourceSet<MobileResource>> ReadAsync(string pathCountryCode,
string pathAccountSid = null,
int? areaCode = null,
string contains = null,
bool? smsEnabled = null,
bool? mmsEnabled = null,
bool? voiceEnabled = null,
bool? excludeAllAddressRequired = null,
bool? excludeLocalAddressRequired = null,
bool? excludeForeignAddressRequired = null,
bool? beta = null,
Types.PhoneNumber nearNumber = null,
string nearLatLong = null,
int? distance = null,
string inPostalCode = null,
string inRegion = null,
string inRateCenter = null,
string inLata = null,
string inLocality = null,
bool? faxEnabled = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadMobileOptions(pathCountryCode){PathAccountSid = pathAccountSid, AreaCode = areaCode, Contains = contains, SmsEnabled = smsEnabled, MmsEnabled = mmsEnabled, VoiceEnabled = voiceEnabled, ExcludeAllAddressRequired = excludeAllAddressRequired, ExcludeLocalAddressRequired = excludeLocalAddressRequired, ExcludeForeignAddressRequired = excludeForeignAddressRequired, Beta = beta, NearNumber = nearNumber, NearLatLong = nearLatLong, Distance = distance, InPostalCode = inPostalCode, InRegion = inRegion, InRateCenter = inRateCenter, InLata = inLata, InLocality = inLocality, FaxEnabled = faxEnabled, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<MobileResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<MobileResource>.FromJson("available_phone_numbers", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<MobileResource> NextPage(Page<MobileResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<MobileResource>.FromJson("available_phone_numbers", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<MobileResource> PreviousPage(Page<MobileResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<MobileResource>.FromJson("available_phone_numbers", response.Content);
}
/// <summary>
/// Converts a JSON string into a MobileResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> MobileResource object represented by the provided JSON </returns>
public static MobileResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<MobileResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// A formatted version of the phone number
/// </summary>
[JsonProperty("friendly_name")]
[JsonConverter(typeof(PhoneNumberConverter))]
public Types.PhoneNumber FriendlyName { get; private set; }
/// <summary>
/// The phone number in E.164 format
/// </summary>
[JsonProperty("phone_number")]
[JsonConverter(typeof(PhoneNumberConverter))]
public Types.PhoneNumber PhoneNumber { get; private set; }
/// <summary>
/// The LATA of this phone number
/// </summary>
[JsonProperty("lata")]
public string Lata { get; private set; }
/// <summary>
/// The locality or city of this phone number's location
/// </summary>
[JsonProperty("locality")]
public string Locality { get; private set; }
/// <summary>
/// The rate center of this phone number
/// </summary>
[JsonProperty("rate_center")]
public string RateCenter { get; private set; }
/// <summary>
/// The latitude of this phone number's location
/// </summary>
[JsonProperty("latitude")]
public decimal? Latitude { get; private set; }
/// <summary>
/// The longitude of this phone number's location
/// </summary>
[JsonProperty("longitude")]
public decimal? Longitude { get; private set; }
/// <summary>
/// The two-letter state or province abbreviation of this phone number's location
/// </summary>
[JsonProperty("region")]
public string Region { get; private set; }
/// <summary>
/// The postal or ZIP code of this phone number's location
/// </summary>
[JsonProperty("postal_code")]
public string PostalCode { get; private set; }
/// <summary>
/// The ISO country code of this phone number
/// </summary>
[JsonProperty("iso_country")]
public string IsoCountry { get; private set; }
/// <summary>
/// The type of Address resource the phone number requires
/// </summary>
[JsonProperty("address_requirements")]
public string AddressRequirements { get; private set; }
/// <summary>
/// Whether the phone number is new to the Twilio platform
/// </summary>
[JsonProperty("beta")]
public bool? Beta { get; private set; }
/// <summary>
/// Whether a phone number can receive calls or messages
/// </summary>
[JsonProperty("capabilities")]
public PhoneNumberCapabilities Capabilities { get; private set; }
private MobileResource()
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Drawing.Internal;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Drawing
{
public sealed partial class Icon : MarshalByRefObject, ICloneable, IDisposable
{
#if FINALIZATION_WATCH
private string allocationSite = Graphics.GetAllocationStack();
#endif
private static int s_bitDepth;
// The PNG signature is specified at http://www.w3.org/TR/PNG/#5PNG-file-signature
private const int PNGSignature1 = 137 + ('P' << 8) + ('N' << 16) + ('G' << 24);
private const int PNGSignature2 = 13 + (10 << 8) + (26 << 16) + (10 << 24);
// Icon data
private readonly byte[] _iconData;
private int _bestImageOffset;
private int _bestBitDepth;
private int _bestBytesInRes;
private bool? _isBestImagePng = null;
private Size _iconSize = Size.Empty;
private IntPtr _handle = IntPtr.Zero;
private bool _ownHandle = true;
private Icon() { }
internal Icon(IntPtr handle) : this(handle, false)
{
}
internal Icon(IntPtr handle, bool takeOwnership)
{
if (handle == IntPtr.Zero)
{
throw new ArgumentException(SR.Format(SR.InvalidGDIHandle, nameof(Icon)));
}
_handle = handle;
_ownHandle = takeOwnership;
}
public Icon(string fileName) : this(fileName, 0, 0)
{
}
public Icon(string fileName, Size size) : this(fileName, size.Width, size.Height)
{
}
public Icon(string fileName, int width, int height) : this()
{
using (FileStream f = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
Debug.Assert(f != null, "File.OpenRead returned null instead of throwing an exception");
_iconData = new byte[(int)f.Length];
f.Read(_iconData, 0, _iconData.Length);
}
Initialize(width, height);
}
public Icon(Icon original, Size size) : this(original, size.Width, size.Height)
{
}
public Icon(Icon original, int width, int height) : this()
{
if (original == null)
{
throw new ArgumentNullException(nameof(original));
}
_iconData = original._iconData;
if (_iconData == null)
{
_iconSize = original.Size;
_handle = SafeNativeMethods.CopyImage(new HandleRef(original, original.Handle), SafeNativeMethods.IMAGE_ICON, _iconSize.Width, _iconSize.Height, 0);
}
else
{
Initialize(width, height);
}
}
public Icon(Type type, string resource) : this()
{
Stream stream = type.Module.Assembly.GetManifestResourceStream(type, resource);
if (stream == null)
{
throw new ArgumentException(SR.Format(SR.ResourceNotFound, type, resource));
}
_iconData = new byte[(int)stream.Length];
stream.Read(_iconData, 0, _iconData.Length);
Initialize(0, 0);
}
public Icon(Stream stream) : this(stream, 0, 0)
{
}
public Icon(Stream stream, Size size) : this(stream, size.Width, size.Height)
{
}
public Icon(Stream stream, int width, int height) : this()
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
_iconData = new byte[(int)stream.Length];
stream.Read(_iconData, 0, _iconData.Length);
Initialize(width, height);
}
public static Icon ExtractAssociatedIcon(string filePath) => ExtractAssociatedIcon(filePath, 0);
private static Icon ExtractAssociatedIcon(string filePath, int index)
{
if (filePath == null)
{
throw new ArgumentNullException(nameof(filePath));
}
Uri uri;
try
{
uri = new Uri(filePath);
}
catch (UriFormatException)
{
// It's a relative pathname, get its full path as a file.
filePath = Path.GetFullPath(filePath);
uri = new Uri(filePath);
}
if (uri.IsUnc)
{
throw new ArgumentException(SR.Format(SR.InvalidArgument, nameof(filePath), filePath));
}
if (!uri.IsFile)
{
return null;
}
if (!File.Exists(filePath))
{
throw new FileNotFoundException(filePath);
}
var sb = new StringBuilder(NativeMethods.MAX_PATH);
sb.Append(filePath);
IntPtr hIcon = SafeNativeMethods.ExtractAssociatedIcon(NativeMethods.NullHandleRef, sb, ref index);
if (hIcon != IntPtr.Zero)
{
return new Icon(hIcon, true);
}
return null;
}
[Browsable(false)]
public IntPtr Handle
{
get
{
if (_handle == IntPtr.Zero)
{
throw new ObjectDisposedException(GetType().Name);
}
return _handle;
}
}
[Browsable(false)]
public int Height => Size.Height;
public Size Size
{
get
{
if (_iconSize.IsEmpty)
{
var info = new SafeNativeMethods.ICONINFO();
SafeNativeMethods.GetIconInfo(new HandleRef(this, Handle), info);
var bmp = new SafeNativeMethods.BITMAP();
if (info.hbmColor != IntPtr.Zero)
{
SafeNativeMethods.GetObject(new HandleRef(null, info.hbmColor), Marshal.SizeOf(typeof(SafeNativeMethods.BITMAP)), bmp);
SafeNativeMethods.IntDeleteObject(new HandleRef(null, info.hbmColor));
_iconSize = new Size(bmp.bmWidth, bmp.bmHeight);
}
else if (info.hbmMask != IntPtr.Zero)
{
SafeNativeMethods.GetObject(new HandleRef(null, info.hbmMask), Marshal.SizeOf(typeof(SafeNativeMethods.BITMAP)), bmp);
_iconSize = new Size(bmp.bmWidth, bmp.bmHeight / 2);
}
if (info.hbmMask != IntPtr.Zero)
{
SafeNativeMethods.IntDeleteObject(new HandleRef(null, info.hbmMask));
}
}
return _iconSize;
}
}
[Browsable(false)]
public int Width => Size.Width;
public object Clone() => new Icon(this, Size.Width, Size.Height);
// Called when this object is going to destroy it's Win32 handle. You
// may override this if there is something special you need to do to
// destroy the handle. This will be called even if the handle is not
// owned by this object, which is handy if you want to create a
// derived class that has it's own create/destroy semantics.
//
// The default implementation will call the appropriate Win32
// call to destroy the handle if this object currently owns the
// handle. It will do nothing if the object does not currently
// own the handle.
internal void DestroyHandle()
{
if (_ownHandle)
{
SafeNativeMethods.DestroyIcon(new HandleRef(this, _handle));
_handle = IntPtr.Zero;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (_handle != IntPtr.Zero)
{
#if FINALIZATION_WATCH
if (!disposing)
{
Debug.WriteLine("**********************\nDisposed through finalization:\n" + allocationSite);
}
#endif
DestroyHandle();
}
}
// Draws this image to a graphics object. The drawing command originates on the graphics
// object, but a graphics object generally has no idea how to render a given image. So,
// it passes the call to the actual image. This version crops the image to the given
// dimensions and allows the user to specify a rectangle within the image to draw.
private void DrawIcon(IntPtr dc, Rectangle imageRect, Rectangle targetRect, bool stretch)
{
int imageX = 0;
int imageY = 0;
int imageWidth;
int imageHeight;
int targetX = 0;
int targetY = 0;
int targetWidth = 0;
int targetHeight = 0;
Size cursorSize = Size;
// Compute the dimensions of the icon if needed.
if (!imageRect.IsEmpty)
{
imageX = imageRect.X;
imageY = imageRect.Y;
imageWidth = imageRect.Width;
imageHeight = imageRect.Height;
}
else
{
imageWidth = cursorSize.Width;
imageHeight = cursorSize.Height;
}
if (!targetRect.IsEmpty)
{
targetX = targetRect.X;
targetY = targetRect.Y;
targetWidth = targetRect.Width;
targetHeight = targetRect.Height;
}
else
{
targetWidth = cursorSize.Width;
targetHeight = cursorSize.Height;
}
int drawWidth, drawHeight;
int clipWidth, clipHeight;
if (stretch)
{
drawWidth = cursorSize.Width * targetWidth / imageWidth;
drawHeight = cursorSize.Height * targetHeight / imageHeight;
clipWidth = targetWidth;
clipHeight = targetHeight;
}
else
{
drawWidth = cursorSize.Width;
drawHeight = cursorSize.Height;
clipWidth = targetWidth < imageWidth ? targetWidth : imageWidth;
clipHeight = targetHeight < imageHeight ? targetHeight : imageHeight;
}
// The ROP is SRCCOPY, so we can be simple here and take
// advantage of clipping regions. Drawing the cursor
// is merely a matter of offsetting and clipping.
IntPtr hSaveRgn = SafeNativeMethods.SaveClipRgn(dc);
try
{
SafeNativeMethods.IntersectClipRect(new HandleRef(this, dc), targetX, targetY, targetX + clipWidth, targetY + clipHeight);
SafeNativeMethods.DrawIconEx(new HandleRef(null, dc),
targetX - imageX,
targetY - imageY,
new HandleRef(this, _handle),
drawWidth,
drawHeight,
0,
NativeMethods.NullHandleRef,
SafeNativeMethods.DI_NORMAL);
}
finally
{
SafeNativeMethods.RestoreClipRgn(dc, hSaveRgn);
}
}
internal void Draw(Graphics graphics, int x, int y)
{
Size size = Size;
Draw(graphics, new Rectangle(x, y, size.Width, size.Height));
}
// Draws this image to a graphics object. The drawing command originates on the graphics
// object, but a graphics object generally has no idea how to render a given image. So,
// it passes the call to the actual image. This version stretches the image to the given
// dimensions and allows the user to specify a rectangle within the image to draw.
internal void Draw(Graphics graphics, Rectangle targetRect)
{
Rectangle copy = targetRect;
copy.X += (int)graphics.Transform.OffsetX;
copy.Y += (int)graphics.Transform.OffsetY;
using (WindowsGraphics wg = WindowsGraphics.FromGraphics(graphics, ApplyGraphicsProperties.Clipping))
{
IntPtr dc = wg.GetHdc();
DrawIcon(dc, Rectangle.Empty, copy, true);
}
}
// Draws this image to a graphics object. The drawing command originates on the graphics
// object, but a graphics object generally has no idea how to render a given image. So,
// it passes the call to the actual image. This version crops the image to the given
// dimensions and allows the user to specify a rectangle within the image to draw.
internal void DrawUnstretched(Graphics graphics, Rectangle targetRect)
{
Rectangle copy = targetRect;
copy.X += (int)graphics.Transform.OffsetX;
copy.Y += (int)graphics.Transform.OffsetY;
using (WindowsGraphics wg = WindowsGraphics.FromGraphics(graphics, ApplyGraphicsProperties.Clipping))
{
IntPtr dc = wg.GetHdc();
DrawIcon(dc, Rectangle.Empty, copy, false);
}
}
~Icon() => Dispose(false);
public static Icon FromHandle(IntPtr handle) => new Icon(handle);
private unsafe short GetShort(byte* pb)
{
int retval = 0;
if (0 != (unchecked((byte)pb) & 1))
{
retval = *pb;
pb++;
retval = unchecked(retval | (*pb << 8));
}
else
{
retval = unchecked(*(short*)pb);
}
return unchecked((short)retval);
}
private unsafe int GetInt(byte* pb)
{
int retval = 0;
if (0 != (unchecked((byte)pb) & 3))
{
retval = *pb; pb++;
retval = retval | (*pb << 8); pb++;
retval = retval | (*pb << 16); pb++;
retval = unchecked(retval | (*pb << 24));
}
else
{
retval = *(int*)pb;
}
return retval;
}
// Initializes this Image object. This is identical to calling the image's
// constructor with picture, but this allows non-constructor initialization,
// which may be necessary in some instances.
private unsafe void Initialize(int width, int height)
{
if (_iconData == null || _handle != IntPtr.Zero)
{
throw new InvalidOperationException(SR.Format(SR.IllegalState, GetType().Name));
}
int icondirSize = Marshal.SizeOf(typeof(SafeNativeMethods.ICONDIR));
if (_iconData.Length < icondirSize)
{
throw new ArgumentException(SR.Format(SR.InvalidPictureType, "picture", nameof(Icon)));
}
// Get the correct width and height.
if (width == 0)
{
width = UnsafeNativeMethods.GetSystemMetrics(SafeNativeMethods.SM_CXICON);
}
if (height == 0)
{
height = UnsafeNativeMethods.GetSystemMetrics(SafeNativeMethods.SM_CYICON);
}
if (s_bitDepth == 0)
{
IntPtr dc = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef);
s_bitDepth = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, dc), SafeNativeMethods.BITSPIXEL);
s_bitDepth *= UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, dc), SafeNativeMethods.PLANES);
UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, dc));
// If the bitdepth is 8, make it 4 because windows does not
// choose a 256 color icon if the display is running in 256 color mode
// due to palette flicker.
if (s_bitDepth == 8)
{
s_bitDepth = 4;
}
}
fixed (byte* pbIconData = _iconData)
{
short idReserved = GetShort(pbIconData);
short idType = GetShort(pbIconData + 2);
short idCount = GetShort(pbIconData + 4);
if (idReserved != 0 || idType != 1 || idCount == 0)
{
throw new ArgumentException(SR.Format(SR.InvalidPictureType, "picture", nameof(Icon)));
}
SafeNativeMethods.ICONDIRENTRY EntryTemp;
byte bestWidth = 0;
byte bestHeight = 0;
byte* pbIconDirEntry = unchecked(pbIconData + 6);
int icondirEntrySize = Marshal.SizeOf(typeof(SafeNativeMethods.ICONDIRENTRY));
if ((icondirEntrySize * (idCount - 1) + icondirSize) > _iconData.Length)
{
throw new ArgumentException(SR.Format(SR.InvalidPictureType, "picture", nameof(Icon)));
}
for (int i = 0; i < idCount; i++)
{
// Fill in EntryTemp
EntryTemp.bWidth = pbIconDirEntry[0];
EntryTemp.bHeight = pbIconDirEntry[1];
EntryTemp.bColorCount = pbIconDirEntry[2];
EntryTemp.bReserved = pbIconDirEntry[3];
EntryTemp.wPlanes = GetShort(pbIconDirEntry + 4);
EntryTemp.wBitCount = GetShort(pbIconDirEntry + 6);
EntryTemp.dwBytesInRes = GetInt(pbIconDirEntry + 8);
EntryTemp.dwImageOffset = GetInt(pbIconDirEntry + 12);
bool fUpdateBestFit = false;
int iconBitDepth = 0;
if (EntryTemp.bColorCount != 0)
{
iconBitDepth = 4;
if (EntryTemp.bColorCount < 0x10)
{
iconBitDepth = 1;
}
}
else
{
iconBitDepth = EntryTemp.wBitCount;
}
// If it looks like if nothing is specified at this point then set the bits per pixel to 8.
if (iconBitDepth == 0)
{
iconBitDepth = 8;
}
// Windows rules for specifing an icon:
//
// 1. The icon with the closest size match.
// 2. For matching sizes, the image with the closest bit depth.
// 3. If there is no color depth match, the icon with the closest color depth that does not exceed the display.
// 4. If all icon color depth > display, lowest color depth is chosen.
// 5. color depth of > 8bpp are all equal.
// 6. Never choose an 8bpp icon on an 8bpp system.
//
if (_bestBytesInRes == 0)
{
fUpdateBestFit = true;
}
else
{
int bestDelta = Math.Abs(bestWidth - width) + Math.Abs(bestHeight - height);
int thisDelta = Math.Abs(EntryTemp.bWidth - width) + Math.Abs(EntryTemp.bHeight - height);
if ((thisDelta < bestDelta) ||
(thisDelta == bestDelta && (iconBitDepth <= s_bitDepth && iconBitDepth > _bestBitDepth || _bestBitDepth > s_bitDepth && iconBitDepth < _bestBitDepth)))
{
fUpdateBestFit = true;
}
}
if (fUpdateBestFit)
{
bestWidth = EntryTemp.bWidth;
bestHeight = EntryTemp.bHeight;
_bestImageOffset = EntryTemp.dwImageOffset;
_bestBytesInRes = EntryTemp.dwBytesInRes;
_bestBitDepth = iconBitDepth;
}
pbIconDirEntry += icondirEntrySize;
}
if (_bestImageOffset < 0)
{
throw new ArgumentException(SR.Format(SR.InvalidPictureType, "picture", nameof(Icon)));
}
if (_bestBytesInRes < 0)
{
throw new Win32Exception(SafeNativeMethods.ERROR_INVALID_PARAMETER);
}
int endOffset;
try
{
endOffset = checked(_bestImageOffset + _bestBytesInRes);
}
catch (OverflowException)
{
throw new Win32Exception(SafeNativeMethods.ERROR_INVALID_PARAMETER);
}
if (endOffset > _iconData.Length)
{
throw new ArgumentException(SR.Format(SR.InvalidPictureType, "picture", nameof(Icon)));
}
// Copy the bytes into an aligned buffer if needed.
if ((_bestImageOffset % IntPtr.Size) != 0)
{
// Beginning of icon's content is misaligned.
byte[] alignedBuffer = new byte[_bestBytesInRes];
Array.Copy(_iconData, _bestImageOffset, alignedBuffer, 0, _bestBytesInRes);
fixed (byte* pbAlignedBuffer = alignedBuffer)
{
_handle = SafeNativeMethods.CreateIconFromResourceEx(pbAlignedBuffer, _bestBytesInRes, true, 0x00030000, 0, 0, 0);
}
}
else
{
try
{
_handle = SafeNativeMethods.CreateIconFromResourceEx(checked(pbIconData + _bestImageOffset), _bestBytesInRes, true, 0x00030000, 0, 0, 0);
}
catch (OverflowException)
{
throw new Win32Exception(SafeNativeMethods.ERROR_INVALID_PARAMETER);
}
}
if (_handle == IntPtr.Zero)
{
throw new Win32Exception();
}
}
}
public void Save(Stream outputStream)
{
if (_iconData != null)
{
outputStream.Write(_iconData, 0, _iconData.Length);
}
else
{
// Ideally, we would pick apart the icon using
// GetIconInfo, and then pull the individual bitmaps out,
// converting them to DIBS and saving them into the file.
// But, in the interest of simplicity, we just call to
// OLE to do it for us.
SafeNativeMethods.PICTDESC pictdesc = SafeNativeMethods.PICTDESC.CreateIconPICTDESC(Handle);
Guid g = typeof(SafeNativeMethods.IPicture).GUID;
SafeNativeMethods.IPicture picture = SafeNativeMethods.OleCreatePictureIndirect(pictdesc, ref g, false);
if (picture != null)
{
try
{
picture.SaveAsFile(new UnsafeNativeMethods.ComStreamFromDataStream(outputStream), -1, out int temp);
}
finally
{
Marshal.ReleaseComObject(picture);
}
}
}
}
private void CopyBitmapData(BitmapData sourceData, BitmapData targetData)
{
int offsetSrc = 0;
int offsetDest = 0;
Debug.Assert(sourceData.Height == targetData.Height, "Unexpected height. How did this happen?");
for (int i = 0; i < Math.Min(sourceData.Height, targetData.Height); i++)
{
IntPtr srcPtr, destPtr;
if (IntPtr.Size == 4)
{
srcPtr = new IntPtr(sourceData.Scan0.ToInt32() + offsetSrc);
destPtr = new IntPtr(targetData.Scan0.ToInt32() + offsetDest);
}
else
{
srcPtr = new IntPtr(sourceData.Scan0.ToInt64() + offsetSrc);
destPtr = new IntPtr(targetData.Scan0.ToInt64() + offsetDest);
}
UnsafeNativeMethods.CopyMemory(new HandleRef(this, destPtr), new HandleRef(this, srcPtr), Math.Abs(targetData.Stride));
offsetSrc += sourceData.Stride;
offsetDest += targetData.Stride;
}
}
private static bool BitmapHasAlpha(BitmapData bmpData)
{
bool hasAlpha = false;
for (int i = 0; i < bmpData.Height; i++)
{
for (int j = 3; j < Math.Abs(bmpData.Stride); j += 4)
{
// Stride here is fine since we know we're doing this on the whole image.
unsafe
{
byte* candidate = unchecked(((byte*)bmpData.Scan0.ToPointer()) + (i * bmpData.Stride) + j);
if (*candidate != 0)
{
hasAlpha = true;
return hasAlpha;
}
}
}
}
return false;
}
public Bitmap ToBitmap()
{
// DontSupportPngFramesInIcons is true when the application is targeting framework version below 4.6
// and false when the application is targeting 4.6 and above. Downlevel application can also set the following switch
// to false in the .config file's runtime section in order to opt-in into the new behavior:
// <AppContextSwitchOverrides value="Switch.System.Drawing.DontSupportPngFramesInIcons=false" />
if (HasPngSignature() && !LocalAppContextSwitches.DontSupportPngFramesInIcons)
{
return PngFrame();
}
return BmpFrame();
}
private Bitmap BmpFrame()
{
Bitmap bitmap = null;
if (_iconData != null && _bestBitDepth == 32)
{
// GDI+ doesnt handle 32 bpp icons with alpha properly
// we load the icon ourself from the byte table
bitmap = new Bitmap(Size.Width, Size.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Debug.Assert(_bestImageOffset >= 0 && (_bestImageOffset + _bestBytesInRes) <= _iconData.Length, "Illegal offset/length for the Icon data");
unsafe
{
BitmapData bmpdata = bitmap.LockBits(new Rectangle(0, 0, Size.Width, Size.Height),
ImageLockMode.WriteOnly,
PixelFormat.Format32bppArgb);
try
{
uint* pixelPtr = (uint*)bmpdata.Scan0.ToPointer();
// jumping the image header
int newOffset = _bestImageOffset + Marshal.SizeOf(typeof(SafeNativeMethods.BITMAPINFOHEADER));
// there is no color table that we need to skip since we're 32bpp
int lineLength = Size.Width * 4;
int width = Size.Width;
for (int j = (Size.Height - 1) * 4; j >= 0; j -= 4)
{
Marshal.Copy(_iconData, newOffset + j * width, (IntPtr)pixelPtr, lineLength);
pixelPtr += width;
}
// note: we ignore the mask that's available after the pixel table
}
finally
{
bitmap.UnlockBits(bmpdata);
}
}
}
else if (_bestBitDepth == 0 || _bestBitDepth == 32)
{
// This may be a 32bpp icon or an icon without any data.
var info = new SafeNativeMethods.ICONINFO();
SafeNativeMethods.GetIconInfo(new HandleRef(this, _handle), info);
var bmp = new SafeNativeMethods.BITMAP();
try
{
if (info.hbmColor != IntPtr.Zero)
{
SafeNativeMethods.GetObject(new HandleRef(null, info.hbmColor), Marshal.SizeOf(typeof(SafeNativeMethods.BITMAP)), bmp);
if (bmp.bmBitsPixel == 32)
{
Bitmap tmpBitmap = null;
BitmapData bmpData = null;
BitmapData targetData = null;
try
{
tmpBitmap = Image.FromHbitmap(info.hbmColor);
// In GDI+ the bits are there but the bitmap was created with no alpha channel
// so copy the bits by hand to a new bitmap
// we also need to go around a limitation in the way the ICON is stored (ie if it's another bpp
// but stored in 32bpp all pixels are transparent and not opaque)
// (Here you mostly need to remain calm....)
bmpData = tmpBitmap.LockBits(new Rectangle(0, 0, tmpBitmap.Width, tmpBitmap.Height), ImageLockMode.ReadOnly, tmpBitmap.PixelFormat);
// we need do the following if the image has alpha because otherwise the image is fully transparent even though it has data
if (BitmapHasAlpha(bmpData))
{
bitmap = new Bitmap(bmpData.Width, bmpData.Height, PixelFormat.Format32bppArgb);
targetData = bitmap.LockBits(new Rectangle(0, 0, bmpData.Width, bmpData.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
CopyBitmapData(bmpData, targetData);
}
}
finally
{
if (tmpBitmap != null && bmpData != null)
{
tmpBitmap.UnlockBits(bmpData);
}
if (bitmap != null && targetData != null)
{
bitmap.UnlockBits(targetData);
}
}
tmpBitmap.Dispose();
}
}
}
finally
{
if (info.hbmColor != IntPtr.Zero)
{
SafeNativeMethods.IntDeleteObject(new HandleRef(null, info.hbmColor));
}
if (info.hbmMask != IntPtr.Zero)
{
SafeNativeMethods.IntDeleteObject(new HandleRef(null, info.hbmMask));
}
}
}
if (bitmap == null)
{
// last chance... all the other cases (ie non 32 bpp icons coming from a handle or from the bitmapData)
// we have to do this rather than just return Bitmap.FromHIcon because
// the bitmap returned from that, even though it's 32bpp, just paints where the mask allows it
// seems like another GDI+ weirdness. might be interesting to investigate further. In the meantime
// this looks like the right thing to do and is not more expansive that what was present before.
Size size = Size;
bitmap = new Bitmap(size.Width, size.Height); // initialized to transparent
Graphics graphics = null;
using (graphics = Graphics.FromImage(bitmap))
{
try
{
using (Bitmap tmpBitmap = Bitmap.FromHicon(Handle))
{
graphics.DrawImage(tmpBitmap, new Rectangle(0, 0, size.Width, size.Height));
}
}
catch (ArgumentException)
{
// Sometimes FromHicon will crash with no real reason.
// The backup plan is to just draw the image like we used to.
// NOTE: FromHIcon is also where we have the buffer overrun
// if width and height are mismatched.
Draw(graphics, new Rectangle(0, 0, size.Width, size.Height));
}
}
// GDI+ fills the surface with a sentinel color for GetDC, but does
// not correctly clean it up again, so we have to do it.
Color fakeTransparencyColor = Color.FromArgb(0x0d, 0x0b, 0x0c);
bitmap.MakeTransparent(fakeTransparencyColor);
}
Debug.Assert(bitmap != null, "Bitmap cannot be null");
return bitmap;
}
private Bitmap PngFrame()
{
Debug.Assert(_iconData != null);
using (var stream = new MemoryStream())
{
stream.Write(_iconData, _bestImageOffset, _bestBytesInRes);
return new Bitmap(stream);
}
}
private bool HasPngSignature()
{
if (!_isBestImagePng.HasValue)
{
if (_iconData != null && _iconData.Length >= _bestImageOffset + 8)
{
int iconSignature1 = BitConverter.ToInt32(_iconData, _bestImageOffset);
int iconSignature2 = BitConverter.ToInt32(_iconData, _bestImageOffset + 4);
_isBestImagePng = (iconSignature1 == PNGSignature1) && (iconSignature2 == PNGSignature2);
}
else
{
_isBestImagePng = false;
}
}
return _isBestImagePng.Value;
}
public override string ToString() => SR.toStringIcon;
}
}
| |
// 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.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Collections.ObjectModel
{
[Serializable]
[DebuggerTypeProxy(typeof(DictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>
{
private readonly IDictionary<TKey, TValue> _dictionary;
[NonSerialized]
private Object _syncRoot;
[NonSerialized]
private KeyCollection _keys;
[NonSerialized]
private ValueCollection _values;
public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
throw new ArgumentNullException(nameof(dictionary));
}
Contract.EndContractBlock();
_dictionary = dictionary;
}
protected IDictionary<TKey, TValue> Dictionary
{
get { return _dictionary; }
}
public KeyCollection Keys
{
get
{
Contract.Ensures(Contract.Result<KeyCollection>() != null);
if (_keys == null)
{
_keys = new KeyCollection(_dictionary.Keys);
}
return _keys;
}
}
public ValueCollection Values
{
get
{
Contract.Ensures(Contract.Result<ValueCollection>() != null);
if (_values == null)
{
_values = new ValueCollection(_dictionary.Values);
}
return _values;
}
}
#region IDictionary<TKey, TValue> Members
public bool ContainsKey(TKey key)
{
return _dictionary.ContainsKey(key);
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get
{
return Keys;
}
}
public bool TryGetValue(TKey key, out TValue value)
{
return _dictionary.TryGetValue(key, out value);
}
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get
{
return Values;
}
}
public TValue this[TKey key]
{
get
{
return _dictionary[key];
}
}
void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool IDictionary<TKey, TValue>.Remove(TKey key)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
TValue IDictionary<TKey, TValue>.this[TKey key]
{
get
{
return _dictionary[key];
}
set
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
}
#endregion
#region ICollection<KeyValuePair<TKey, TValue>> Members
public int Count
{
get { return _dictionary.Count; }
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
{
return _dictionary.Contains(item);
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
_dictionary.CopyTo(array, arrayIndex);
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return true; }
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void ICollection<KeyValuePair<TKey, TValue>>.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
#endregion
#region IEnumerable<KeyValuePair<TKey, TValue>> Members
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return _dictionary.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((IEnumerable)_dictionary).GetEnumerator();
}
#endregion
#region IDictionary Members
private static bool IsCompatibleKey(object key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return key is TKey;
}
void IDictionary.Add(object key, object value)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void IDictionary.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool IDictionary.Contains(object key)
{
return IsCompatibleKey(key) && ContainsKey((TKey)key);
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
IDictionary d = _dictionary as IDictionary;
if (d != null)
{
return d.GetEnumerator();
}
return new DictionaryEnumerator(_dictionary);
}
bool IDictionary.IsFixedSize
{
get { return true; }
}
bool IDictionary.IsReadOnly
{
get { return true; }
}
ICollection IDictionary.Keys
{
get
{
return Keys;
}
}
void IDictionary.Remove(object key)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
ICollection IDictionary.Values
{
get
{
return Values;
}
}
object IDictionary.this[object key]
{
get
{
if (IsCompatibleKey(key))
{
return this[(TKey)key];
}
return null;
}
set
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[];
if (pairs != null)
{
_dictionary.CopyTo(pairs, index);
}
else
{
DictionaryEntry[] dictEntryArray = array as DictionaryEntry[];
if (dictEntryArray != null)
{
foreach (var item in _dictionary)
{
dictEntryArray[index++] = new DictionaryEntry(item.Key, item.Value);
}
}
else
{
object[] objects = array as object[];
if (objects == null)
{
throw new ArgumentException(SR.Argument_InvalidArrayType);
}
try
{
foreach (var item in _dictionary)
{
objects[index++] = new KeyValuePair<TKey, TValue>(item.Key, item.Value);
}
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType);
}
}
}
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
ICollection c = _dictionary as ICollection;
if (c != null)
{
_syncRoot = c.SyncRoot;
}
else
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
}
return _syncRoot;
}
}
private struct DictionaryEnumerator : IDictionaryEnumerator
{
private readonly IDictionary<TKey, TValue> _dictionary;
private IEnumerator<KeyValuePair<TKey, TValue>> _enumerator;
public DictionaryEnumerator(IDictionary<TKey, TValue> dictionary)
{
_dictionary = dictionary;
_enumerator = _dictionary.GetEnumerator();
}
public DictionaryEntry Entry
{
get { return new DictionaryEntry(_enumerator.Current.Key, _enumerator.Current.Value); }
}
public object Key
{
get { return _enumerator.Current.Key; }
}
public object Value
{
get { return _enumerator.Current.Value; }
}
public object Current
{
get { return Entry; }
}
public bool MoveNext()
{
return _enumerator.MoveNext();
}
public void Reset()
{
_enumerator.Reset();
}
}
#endregion
#region IReadOnlyDictionary members
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys
{
get
{
return Keys;
}
}
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values
{
get
{
return Values;
}
}
#endregion IReadOnlyDictionary members
[DebuggerTypeProxy(typeof(CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey>
{
private readonly ICollection<TKey> _collection;
[NonSerialized]
private Object _syncRoot;
internal KeyCollection(ICollection<TKey> collection)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
_collection = collection;
}
#region ICollection<T> Members
void ICollection<TKey>.Add(TKey item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void ICollection<TKey>.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool ICollection<TKey>.Contains(TKey item)
{
return _collection.Contains(item);
}
public void CopyTo(TKey[] array, int arrayIndex)
{
_collection.CopyTo(array, arrayIndex);
}
public int Count
{
get { return _collection.Count; }
}
bool ICollection<TKey>.IsReadOnly
{
get { return true; }
}
bool ICollection<TKey>.Remove(TKey item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<TKey> GetEnumerator()
{
return _collection.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((IEnumerable)_collection).GetEnumerator();
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index)
{
ReadOnlyDictionaryHelpers.CopyToNonGenericICollectionHelper<TKey>(_collection, array, index);
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
ICollection c = _collection as ICollection;
if (c != null)
{
_syncRoot = c.SyncRoot;
}
else
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
}
return _syncRoot;
}
}
#endregion
}
[DebuggerTypeProxy(typeof(CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue>
{
private readonly ICollection<TValue> _collection;
[NonSerialized]
private Object _syncRoot;
internal ValueCollection(ICollection<TValue> collection)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
_collection = collection;
}
#region ICollection<T> Members
void ICollection<TValue>.Add(TValue item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void ICollection<TValue>.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool ICollection<TValue>.Contains(TValue item)
{
return _collection.Contains(item);
}
public void CopyTo(TValue[] array, int arrayIndex)
{
_collection.CopyTo(array, arrayIndex);
}
public int Count
{
get { return _collection.Count; }
}
bool ICollection<TValue>.IsReadOnly
{
get { return true; }
}
bool ICollection<TValue>.Remove(TValue item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<TValue> GetEnumerator()
{
return _collection.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((IEnumerable)_collection).GetEnumerator();
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index)
{
ReadOnlyDictionaryHelpers.CopyToNonGenericICollectionHelper<TValue>(_collection, array, index);
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
ICollection c = _collection as ICollection;
if (c != null)
{
_syncRoot = c.SyncRoot;
}
else
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
}
return _syncRoot;
}
}
#endregion ICollection Members
}
}
// To share code when possible, use a non-generic class to get rid of irrelevant type parameters.
internal static class ReadOnlyDictionaryHelpers
{
#region Helper method for our KeyCollection and ValueCollection
// Abstracted away to avoid redundant implementations.
internal static void CopyToNonGenericICollectionHelper<T>(ICollection<T> collection, Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < collection.Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
// Easy out if the ICollection<T> implements the non-generic ICollection
ICollection nonGenericCollection = collection as ICollection;
if (nonGenericCollection != null)
{
nonGenericCollection.CopyTo(array, index);
return;
}
T[] items = array as T[];
if (items != null)
{
collection.CopyTo(items, index);
}
else
{
/*
FxOverRh: Type.IsAssignableNot() not an api on that platform.
//
// Catch the obvious case assignment will fail.
// We can found all possible problems by doing the check though.
// For example, if the element type of the Array is derived from T,
// we can't figure out if we can successfully copy the element beforehand.
//
Type targetType = array.GetType().GetElementType();
Type sourceType = typeof(T);
if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) {
throw new ArgumentException(SR.Argument_InvalidArrayType);
}
*/
//
// We can't cast array of value type to object[], so we don't support
// widening of primitive types here.
//
object[] objects = array as object[];
if (objects == null)
{
throw new ArgumentException(SR.Argument_InvalidArrayType);
}
try
{
foreach (var item in collection)
{
objects[index++] = item;
}
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType);
}
}
}
#endregion Helper method for our KeyCollection and ValueCollection
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using 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>
/// UsagesOperations operations.
/// </summary>
internal partial class UsagesOperations : IServiceOperations<NetworkManagementClient>, IUsagesOperations
{
/// <summary>
/// Initializes a new instance of the UsagesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal UsagesOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Lists compute usages for a subscription.
/// </summary>
/// <param name='location'>
/// The location where resource usage is queried.
/// </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<Usage>>> ListWithHttpMessagesAsync(string location, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (location == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "location");
}
if (location != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(location, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "location", "^[-\\w\\._]+$");
}
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("location", location);
tracingParameters.Add("apiVersion", apiVersion);
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("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/usages").ToString();
_url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(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 (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<Usage>>();
_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<Usage>>(_responseContent, Client.DeserializationSettings);
}
catch (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 compute usages for a subscription.
/// </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<Usage>>> 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 (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<Usage>>();
_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<Usage>>(_responseContent, Client.DeserializationSettings);
}
catch (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;
}
}
}
| |
/*
* C# port of Mozilla Character Set Detector
* https://code.google.com/p/chardetsharp/
*
* Original Mozilla License Block follows
*
*/
#region 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):
//
// 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.
#endregion
namespace Cloney.Core.CharsetDetection
{
internal abstract class JapaneseContextAnalysis
{
const int NUM_OF_CATEGORY = 6;
const int ENOUGH_REL_THRESHOLD = 100;
const int MAX_REL_THRESHOLD = 1000;
public bool GotEnoughData() { return mTotalRel > ENOUGH_REL_THRESHOLD; }
internal abstract int GetOrder(byte[] str, ref int charLen);
internal abstract int GetOrder(byte[] str);
//category counters, each integer counts sequences in its category
int[] mRelSample = new int[NUM_OF_CATEGORY];
//total sequence received
int mTotalRel;
//The order of previous char
int mLastCharOrder;
//if last byte in current buffer is not the last byte of a character, we
//need to know how many byte to skip in next buffer.
int mNeedToSkipCharNum;
//If this flag is set to PR_TRUE, detection is done and conclusion has been made
bool mDone;
//This is hiragana 2-char sequence table, the number in each cell represents its frequency category
byte[][] jp2CharContext = new byte[][] {
new byte[]{ 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,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,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,},
new byte[]{ 2,4,0,4,0,3,0,4,0,3,4,4,4,2,4,3,3,4,3,2,3,3,4,2,3,3,3,2,4,1,4,3,3,1,5,4,3,4,3,4,3,5,3,0,3,5,4,2,0,3,1,0,3,3,0,3,3,0,1,1,0,4,3,0,3,3,0,4,0,2,0,3,5,5,5,5,4,0,4,1,0,3,4,},
new byte[]{ 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,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,2,},
new byte[]{ 0,4,0,5,0,5,0,4,0,4,5,4,4,3,5,3,5,1,5,3,4,3,4,4,3,4,3,3,4,3,5,4,4,3,5,5,3,5,5,5,3,5,5,3,4,5,5,3,1,3,2,0,3,4,0,4,2,0,4,2,1,5,3,2,3,5,0,4,0,2,0,5,4,4,5,4,5,0,4,0,0,4,4,},
new byte[]{ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,},
new byte[]{ 0,3,0,4,0,3,0,3,0,4,5,4,3,3,3,3,4,3,5,4,4,3,5,4,4,3,4,3,4,4,4,4,5,3,4,4,3,4,5,5,4,5,5,1,4,5,4,3,0,3,3,1,3,3,0,4,4,0,3,3,1,5,3,3,3,5,0,4,0,3,0,4,4,3,4,3,3,0,4,1,1,3,4,},
new byte[]{ 0,0,0,0,0,0,0,0,0,0,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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,},
new byte[]{ 0,4,0,3,0,3,0,4,0,3,4,4,3,2,2,1,2,1,3,1,3,3,3,3,3,4,3,1,3,3,5,3,3,0,4,3,0,5,4,3,3,5,4,4,3,4,4,5,0,1,2,0,1,2,0,2,2,0,1,0,0,5,2,2,1,4,0,3,0,1,0,4,4,3,5,4,3,0,2,1,0,4,3,},
new byte[]{ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,},
new byte[]{ 0,3,0,5,0,4,0,2,1,4,4,2,4,1,4,2,4,2,4,3,3,3,4,3,3,3,3,1,4,2,3,3,3,1,4,4,1,1,1,4,3,3,2,0,2,4,3,2,0,3,3,0,3,1,1,0,0,0,3,3,0,4,2,2,3,4,0,4,0,3,0,4,4,5,3,4,4,0,3,0,0,1,4,},
new byte[]{ 1,4,0,4,0,4,0,4,0,3,5,4,4,3,4,3,5,4,3,3,4,3,5,4,4,4,4,3,4,2,4,3,3,1,5,4,3,2,4,5,4,5,5,4,4,5,4,4,0,3,2,2,3,3,0,4,3,1,3,2,1,4,3,3,4,5,0,3,0,2,0,4,5,5,4,5,4,0,4,0,0,5,4,},
new byte[]{ 0,5,0,5,0,4,0,3,0,4,4,3,4,3,3,3,4,0,4,4,4,3,4,3,4,3,3,1,4,2,4,3,4,0,5,4,1,4,5,4,4,5,3,2,4,3,4,3,2,4,1,3,3,3,2,3,2,0,4,3,3,4,3,3,3,4,0,4,0,3,0,4,5,4,4,4,3,0,4,1,0,1,3,},
new byte[]{ 0,3,1,4,0,3,0,2,0,3,4,4,3,1,4,2,3,3,4,3,4,3,4,3,4,4,3,2,3,1,5,4,4,1,4,4,3,5,4,4,3,5,5,4,3,4,4,3,1,2,3,1,2,2,0,3,2,0,3,1,0,5,3,3,3,4,3,3,3,3,4,4,4,4,5,4,2,0,3,3,2,4,3,},
new byte[]{ 0,2,0,3,0,1,0,1,0,0,3,2,0,0,2,0,1,0,2,1,3,3,3,1,2,3,1,0,1,0,4,2,1,1,3,3,0,4,3,3,1,4,3,3,0,3,3,2,0,0,0,0,1,0,0,2,0,0,0,0,0,4,1,0,2,3,2,2,2,1,3,3,3,4,4,3,2,0,3,1,0,3,3,},
new byte[]{ 0,4,0,4,0,3,0,3,0,4,4,4,3,3,3,3,3,3,4,3,4,2,4,3,4,3,3,2,4,3,4,5,4,1,4,5,3,5,4,5,3,5,4,0,3,5,5,3,1,3,3,2,2,3,0,3,4,1,3,3,2,4,3,3,3,4,0,4,0,3,0,4,5,4,4,5,3,0,4,1,0,3,4,},
new byte[]{ 0,2,0,3,0,3,0,0,0,2,2,2,1,0,1,0,0,0,3,0,3,0,3,0,1,3,1,0,3,1,3,3,3,1,3,3,3,0,1,3,1,3,4,0,0,3,1,1,0,3,2,0,0,0,0,1,3,0,1,0,0,3,3,2,0,3,0,0,0,0,0,3,4,3,4,3,3,0,3,0,0,2,3,},
new byte[]{ 2,3,0,3,0,2,0,1,0,3,3,4,3,1,3,1,1,1,3,1,4,3,4,3,3,3,0,0,3,1,5,4,3,1,4,3,2,5,5,4,4,4,4,3,3,4,4,4,0,2,1,1,3,2,0,1,2,0,0,1,0,4,1,3,3,3,0,3,0,1,0,4,4,4,5,5,3,0,2,0,0,4,4,},
new byte[]{ 0,2,0,1,0,3,1,3,0,2,3,3,3,0,3,1,0,0,3,0,3,2,3,1,3,2,1,1,0,0,4,2,1,0,2,3,1,4,3,2,0,4,4,3,1,3,1,3,0,1,0,0,1,0,0,0,1,0,0,0,0,4,1,1,1,2,0,3,0,0,0,3,4,2,4,3,2,0,1,0,0,3,3,},
new byte[]{ 0,1,0,4,0,5,0,4,0,2,4,4,2,3,3,2,3,3,5,3,3,3,4,3,4,2,3,0,4,3,3,3,4,1,4,3,2,1,5,5,3,4,5,1,3,5,4,2,0,3,3,0,1,3,0,4,2,0,1,3,1,4,3,3,3,3,0,3,0,1,0,3,4,4,4,5,5,0,3,0,1,4,5,},
new byte[]{ 0,2,0,3,0,3,0,0,0,2,3,1,3,0,4,0,1,1,3,0,3,4,3,2,3,1,0,3,3,2,3,1,3,0,2,3,0,2,1,4,1,2,2,0,0,3,3,0,0,2,0,0,0,1,0,0,0,0,2,2,0,3,2,1,3,3,0,2,0,2,0,0,3,3,1,2,4,0,3,0,2,2,3,},
new byte[]{ 2,4,0,5,0,4,0,4,0,2,4,4,4,3,4,3,3,3,1,2,4,3,4,3,4,4,5,0,3,3,3,3,2,0,4,3,1,4,3,4,1,4,4,3,3,4,4,3,1,2,3,0,4,2,0,4,1,0,3,3,0,4,3,3,3,4,0,4,0,2,0,3,5,3,4,5,2,0,3,0,0,4,5,},
new byte[]{ 0,3,0,4,0,1,0,1,0,1,3,2,2,1,3,0,3,0,2,0,2,0,3,0,2,0,0,0,1,0,1,1,0,0,3,1,0,0,0,4,0,3,1,0,2,1,3,0,0,0,0,0,0,3,0,0,0,0,0,0,0,4,2,2,3,1,0,3,0,0,0,1,4,4,4,3,0,0,4,0,0,1,4,},
new byte[]{ 1,4,1,5,0,3,0,3,0,4,5,4,4,3,5,3,3,4,4,3,4,1,3,3,3,3,2,1,4,1,5,4,3,1,4,4,3,5,4,4,3,5,4,3,3,4,4,4,0,3,3,1,2,3,0,3,1,0,3,3,0,5,4,4,4,4,4,4,3,3,5,4,4,3,3,5,4,0,3,2,0,4,4,},
new byte[]{ 0,2,0,3,0,1,0,0,0,1,3,3,3,2,4,1,3,0,3,1,3,0,2,2,1,1,0,0,2,0,4,3,1,0,4,3,0,4,4,4,1,4,3,1,1,3,3,1,0,2,0,0,1,3,0,0,0,0,2,0,0,4,3,2,4,3,5,4,3,3,3,4,3,3,4,3,3,0,2,1,0,3,3,},
new byte[]{ 0,2,0,4,0,3,0,2,0,2,5,5,3,4,4,4,4,1,4,3,3,0,4,3,4,3,1,3,3,2,4,3,0,3,4,3,0,3,4,4,2,4,4,0,4,5,3,3,2,2,1,1,1,2,0,1,5,0,3,3,2,4,3,3,3,4,0,3,0,2,0,4,4,3,5,5,0,0,3,0,2,3,3,},
new byte[]{ 0,3,0,4,0,3,0,1,0,3,4,3,3,1,3,3,3,0,3,1,3,0,4,3,3,1,1,0,3,0,3,3,0,0,4,4,0,1,5,4,3,3,5,0,3,3,4,3,0,2,0,1,1,1,0,1,3,0,1,2,1,3,3,2,3,3,0,3,0,1,0,1,3,3,4,4,1,0,1,2,2,1,3,},
new byte[]{ 0,1,0,4,0,4,0,3,0,1,3,3,3,2,3,1,1,0,3,0,3,3,4,3,2,4,2,0,1,0,4,3,2,0,4,3,0,5,3,3,2,4,4,4,3,3,3,4,0,1,3,0,0,1,0,0,1,0,0,0,0,4,2,3,3,3,0,3,0,0,0,4,4,4,5,3,2,0,3,3,0,3,5,},
new byte[]{ 0,2,0,3,0,0,0,3,0,1,3,0,2,0,0,0,1,0,3,1,1,3,3,0,0,3,0,0,3,0,2,3,1,0,3,1,0,3,3,2,0,4,2,2,0,2,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,2,1,2,0,1,0,1,0,0,0,1,3,1,2,0,0,0,1,0,0,1,4,},
new byte[]{ 0,3,0,3,0,5,0,1,0,2,4,3,1,3,3,2,1,1,5,2,1,0,5,1,2,0,0,0,3,3,2,2,3,2,4,3,0,0,3,3,1,3,3,0,2,5,3,4,0,3,3,0,1,2,0,2,2,0,3,2,0,2,2,3,3,3,0,2,0,1,0,3,4,4,2,5,4,0,3,0,0,3,5,},
new byte[]{ 0,3,0,3,0,3,0,1,0,3,3,3,3,0,3,0,2,0,2,1,1,0,2,0,1,0,0,0,2,1,0,0,1,0,3,2,0,0,3,3,1,2,3,1,0,3,3,0,0,1,0,0,0,0,0,2,0,0,0,0,0,2,3,1,2,3,0,3,0,1,0,3,2,1,0,4,3,0,1,1,0,3,3,},
new byte[]{ 0,4,0,5,0,3,0,3,0,4,5,5,4,3,5,3,4,3,5,3,3,2,5,3,4,4,4,3,4,3,4,5,5,3,4,4,3,4,4,5,4,4,4,3,4,5,5,4,2,3,4,2,3,4,0,3,3,1,4,3,2,4,3,3,5,5,0,3,0,3,0,5,5,5,5,4,4,0,4,0,1,4,4,},
new byte[]{ 0,4,0,4,0,3,0,3,0,3,5,4,4,2,3,2,5,1,3,2,5,1,4,2,3,2,3,3,4,3,3,3,3,2,5,4,1,3,3,5,3,4,4,0,4,4,3,1,1,3,1,0,2,3,0,2,3,0,3,0,0,4,3,1,3,4,0,3,0,2,0,4,4,4,3,4,5,0,4,0,0,3,4,},
new byte[]{ 0,3,0,3,0,3,1,2,0,3,4,4,3,3,3,0,2,2,4,3,3,1,3,3,3,1,1,0,3,1,4,3,2,3,4,4,2,4,4,4,3,4,4,3,2,4,4,3,1,3,3,1,3,3,0,4,1,0,2,2,1,4,3,2,3,3,5,4,3,3,5,4,4,3,3,0,4,0,3,2,2,4,4,},
new byte[]{ 0,2,0,1,0,0,0,0,0,1,2,1,3,0,0,0,0,0,2,0,1,2,1,0,0,1,0,0,0,0,3,0,0,1,0,1,1,3,1,0,0,0,1,1,0,1,1,0,0,0,0,0,2,0,0,0,0,0,0,0,0,1,1,2,2,0,3,4,0,0,0,1,1,0,0,1,0,0,0,0,0,1,1,},
new byte[]{ 0,1,0,0,0,1,0,0,0,0,4,0,4,1,4,0,3,0,4,0,3,0,4,0,3,0,3,0,4,1,5,1,4,0,0,3,0,5,0,5,2,0,1,0,0,0,2,1,4,0,1,3,0,0,3,0,0,3,1,1,4,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,},
new byte[]{ 1,4,0,5,0,3,0,2,0,3,5,4,4,3,4,3,5,3,4,3,3,0,4,3,3,3,3,3,3,2,4,4,3,1,3,4,4,5,4,4,3,4,4,1,3,5,4,3,3,3,1,2,2,3,3,1,3,1,3,3,3,5,3,3,4,5,0,3,0,3,0,3,4,3,4,4,3,0,3,0,2,4,3,},
new byte[]{ 0,1,0,4,0,0,0,0,0,1,4,0,4,1,4,2,4,0,3,0,1,0,1,0,0,0,0,0,2,0,3,1,1,1,0,3,0,0,0,1,2,1,0,0,1,1,1,1,0,1,0,0,0,1,0,0,3,0,0,0,0,3,2,0,2,2,0,1,0,0,0,2,3,2,3,3,0,0,0,0,2,1,0,},
new byte[]{ 0,5,1,5,0,3,0,3,0,5,4,4,5,1,5,3,3,0,4,3,4,3,5,3,4,3,3,2,4,3,4,3,3,0,3,3,1,4,4,3,4,4,4,3,4,5,5,3,2,3,1,1,3,3,1,3,1,1,3,3,2,4,5,3,3,5,0,4,0,3,0,4,4,3,5,3,3,0,3,4,0,4,3,},
new byte[]{ 0,5,0,5,0,3,0,2,0,4,4,3,5,2,4,3,3,3,4,4,4,3,5,3,5,3,3,1,4,0,4,3,3,0,3,3,0,4,4,4,4,5,4,3,3,5,5,3,2,3,1,2,3,2,0,1,0,0,3,2,2,4,4,3,1,5,0,4,0,3,0,4,3,1,3,2,1,0,3,3,0,3,3,},
new byte[]{ 0,4,0,5,0,5,0,4,0,4,5,5,5,3,4,3,3,2,5,4,4,3,5,3,5,3,4,0,4,3,4,4,3,2,4,4,3,4,5,4,4,5,5,0,3,5,5,4,1,3,3,2,3,3,1,3,1,0,4,3,1,4,4,3,4,5,0,4,0,2,0,4,3,4,4,3,3,0,4,0,0,5,5,},
new byte[]{ 0,4,0,4,0,5,0,1,1,3,3,4,4,3,4,1,3,0,5,1,3,0,3,1,3,1,1,0,3,0,3,3,4,0,4,3,0,4,4,4,3,4,4,0,3,5,4,1,0,3,0,0,2,3,0,3,1,0,3,1,0,3,2,1,3,5,0,3,0,1,0,3,2,3,3,4,4,0,2,2,0,4,4,},
new byte[]{ 2,4,0,5,0,4,0,3,0,4,5,5,4,3,5,3,5,3,5,3,5,2,5,3,4,3,3,4,3,4,5,3,2,1,5,4,3,2,3,4,5,3,4,1,2,5,4,3,0,3,3,0,3,2,0,2,3,0,4,1,0,3,4,3,3,5,0,3,0,1,0,4,5,5,5,4,3,0,4,2,0,3,5,},
new byte[]{ 0,5,0,4,0,4,0,2,0,5,4,3,4,3,4,3,3,3,4,3,4,2,5,3,5,3,4,1,4,3,4,4,4,0,3,5,0,4,4,4,4,5,3,1,3,4,5,3,3,3,3,3,3,3,0,2,2,0,3,3,2,4,3,3,3,5,3,4,1,3,3,5,3,2,0,0,0,0,4,3,1,3,3,},
new byte[]{ 0,1,0,3,0,3,0,1,0,1,3,3,3,2,3,3,3,0,3,0,0,0,3,1,3,0,0,0,2,2,2,3,0,0,3,2,0,1,2,4,1,3,3,0,0,3,3,3,0,1,0,0,2,1,0,0,3,0,3,1,0,3,0,0,1,3,0,2,0,1,0,3,3,1,3,3,0,0,1,1,0,3,3,},
new byte[]{ 0,2,0,3,0,2,1,4,0,2,2,3,1,1,3,1,1,0,2,0,3,1,2,3,1,3,0,0,1,0,4,3,2,3,3,3,1,4,2,3,3,3,3,1,0,3,1,4,0,1,1,0,1,2,0,1,1,0,1,1,0,3,1,3,2,2,0,1,0,0,0,2,3,3,3,1,0,0,0,0,0,2,3,},
new byte[]{ 0,5,0,4,0,5,0,2,0,4,5,5,3,3,4,3,3,1,5,4,4,2,4,4,4,3,4,2,4,3,5,5,4,3,3,4,3,3,5,5,4,5,5,1,3,4,5,3,1,4,3,1,3,3,0,3,3,1,4,3,1,4,5,3,3,5,0,4,0,3,0,5,3,3,1,4,3,0,4,0,1,5,3,},
new byte[]{ 0,5,0,5,0,4,0,2,0,4,4,3,4,3,3,3,3,3,5,4,4,4,4,4,4,5,3,3,5,2,4,4,4,3,4,4,3,3,4,4,5,5,3,3,4,3,4,3,3,4,3,3,3,3,1,2,2,1,4,3,3,5,4,4,3,4,0,4,0,3,0,4,4,4,4,4,1,0,4,2,0,2,4,},
new byte[]{ 0,4,0,4,0,3,0,1,0,3,5,2,3,0,3,0,2,1,4,2,3,3,4,1,4,3,3,2,4,1,3,3,3,0,3,3,0,0,3,3,3,5,3,3,3,3,3,2,0,2,0,0,2,0,0,2,0,0,1,0,0,3,1,2,2,3,0,3,0,2,0,4,4,3,3,4,1,0,3,0,0,2,4,},
new byte[]{ 0,0,0,4,0,0,0,0,0,0,1,0,1,0,2,0,0,0,0,0,1,0,2,0,1,0,0,0,0,0,3,1,3,0,3,2,0,0,0,1,0,3,2,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,3,4,0,2,0,0,0,0,0,0,2,},
new byte[]{ 0,2,1,3,0,2,0,2,0,3,3,3,3,1,3,1,3,3,3,3,3,3,4,2,2,1,2,1,4,0,4,3,1,3,3,3,2,4,3,5,4,3,3,3,3,3,3,3,0,1,3,0,2,0,0,1,0,0,1,0,0,4,2,0,2,3,0,3,3,0,3,3,4,2,3,1,4,0,1,2,0,2,3,},
new byte[]{ 0,3,0,3,0,1,0,3,0,2,3,3,3,0,3,1,2,0,3,3,2,3,3,2,3,2,3,1,3,0,4,3,2,0,3,3,1,4,3,3,2,3,4,3,1,3,3,1,1,0,1,1,0,1,0,1,0,1,0,0,0,4,1,1,0,3,0,3,1,0,2,3,3,3,3,3,1,0,0,2,0,3,3,},
new byte[]{ 0,0,0,0,0,0,0,0,0,0,3,0,2,0,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,3,0,3,1,0,1,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,3,0,2,0,2,3,0,0,0,0,0,0,0,0,3,},
new byte[]{ 0,2,0,3,1,3,0,3,0,2,3,3,3,1,3,1,3,1,3,1,3,3,3,1,3,0,2,3,1,1,4,3,3,2,3,3,1,2,2,4,1,3,3,0,1,4,2,3,0,1,3,0,3,0,0,1,3,0,2,0,0,3,3,2,1,3,0,3,0,2,0,3,4,4,4,3,1,0,3,0,0,3,3,},
new byte[]{ 0,2,0,1,0,2,0,0,0,1,3,2,2,1,3,0,1,1,3,0,3,2,3,1,2,0,2,0,1,1,3,3,3,0,3,3,1,1,2,3,2,3,3,1,2,3,2,0,0,1,0,0,0,0,0,0,3,0,1,0,0,2,1,2,1,3,0,3,0,0,0,3,4,4,4,3,2,0,2,0,0,2,4,},
new byte[]{ 0,0,0,1,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,2,2,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,1,0,0,0,0,1,3,1,0,0,0,0,0,0,0,3,},
new byte[]{ 0,3,0,3,0,2,0,3,0,3,3,3,2,3,2,2,2,0,3,1,3,3,3,2,3,3,0,0,3,0,3,2,2,0,2,3,1,4,3,4,3,3,2,3,1,5,4,4,0,3,1,2,1,3,0,3,1,1,2,0,2,3,1,3,1,3,0,3,0,1,0,3,3,4,4,2,1,0,2,1,0,2,4,},
new byte[]{ 0,1,0,3,0,1,0,2,0,1,4,2,5,1,4,0,2,0,2,1,3,1,4,0,2,1,0,0,2,1,4,1,1,0,3,3,0,5,1,3,2,3,3,1,0,3,2,3,0,1,0,0,0,0,0,0,1,0,0,0,0,4,0,1,0,3,0,2,0,1,0,3,3,3,4,3,3,0,0,0,0,2,3,},
new byte[]{ 0,0,0,1,0,0,0,0,0,0,2,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,3,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,2,1,0,0,1,0,0,0,0,0,3,},
new byte[]{ 0,1,0,3,0,4,0,3,0,2,4,3,1,0,3,2,2,1,3,1,2,2,3,1,1,1,2,1,3,0,1,2,0,1,3,2,1,3,0,5,5,1,0,0,1,3,2,1,0,3,0,0,1,0,0,0,0,0,3,4,0,1,1,1,3,2,0,2,0,1,0,2,3,3,1,2,3,0,1,0,1,0,4,},
new byte[]{ 0,0,0,1,0,3,0,3,0,2,2,1,0,0,4,0,3,0,3,1,3,0,3,0,3,0,1,0,3,0,3,1,3,0,3,3,0,0,1,2,1,1,1,0,1,2,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,2,2,1,2,0,0,2,0,0,0,0,2,3,3,3,3,0,0,0,0,1,4,},
new byte[]{ 0,0,0,3,0,3,0,0,0,0,3,1,1,0,3,0,1,0,2,0,1,0,0,0,0,0,0,0,1,0,3,0,2,0,2,3,0,0,2,2,3,1,2,0,0,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,0,3,0,0,2,0,0,0,0,2,3,},
new byte[]{ 2,4,0,5,0,5,0,4,0,3,4,3,3,3,4,3,3,3,4,3,4,4,5,4,5,5,5,2,3,0,5,5,4,1,5,4,3,1,5,4,3,4,4,3,3,4,3,3,0,3,2,0,2,3,0,3,0,0,3,3,0,5,3,2,3,3,0,3,0,3,0,3,4,5,4,5,3,0,4,3,0,3,4,},
new byte[]{ 0,3,0,3,0,3,0,3,0,3,3,4,3,2,3,2,3,0,4,3,3,3,3,3,3,3,3,0,3,2,4,3,3,1,3,4,3,4,4,4,3,4,4,3,2,4,4,1,0,2,0,0,1,1,0,2,0,0,3,1,0,5,3,2,1,3,0,3,0,1,2,4,3,2,4,3,3,0,3,2,0,4,4,},
new byte[]{ 0,3,0,3,0,1,0,0,0,1,4,3,3,2,3,1,3,1,4,2,3,2,4,2,3,4,3,0,2,2,3,3,3,0,3,3,3,0,3,4,1,3,3,0,3,4,3,3,0,1,1,0,1,0,0,0,4,0,3,0,0,3,1,2,1,3,0,4,0,1,0,4,3,3,4,3,3,0,2,0,0,3,3,},
new byte[]{ 0,3,0,4,0,1,0,3,0,3,4,3,3,0,3,3,3,1,3,1,3,3,4,3,3,3,0,0,3,1,5,3,3,1,3,3,2,5,4,3,3,4,5,3,2,5,3,4,0,1,0,0,0,0,0,2,0,0,1,1,0,4,2,2,1,3,0,3,0,2,0,4,4,3,5,3,2,0,1,1,0,3,4,},
new byte[]{ 0,5,0,4,0,5,0,2,0,4,4,3,3,2,3,3,3,1,4,3,4,1,5,3,4,3,4,0,4,2,4,3,4,1,5,4,0,4,4,4,4,5,4,1,3,5,4,2,1,4,1,1,3,2,0,3,1,0,3,2,1,4,3,3,3,4,0,4,0,3,0,4,4,4,3,3,3,0,4,2,0,3,4,},
new byte[]{ 1,4,0,4,0,3,0,1,0,3,3,3,1,1,3,3,2,2,3,3,1,0,3,2,2,1,2,0,3,1,2,1,2,0,3,2,0,2,2,3,3,4,3,0,3,3,1,2,0,1,1,3,1,2,0,0,3,0,1,1,0,3,2,2,3,3,0,3,0,0,0,2,3,3,4,3,3,0,1,0,0,1,4,},
new byte[]{ 0,4,0,4,0,4,0,0,0,3,4,4,3,1,4,2,3,2,3,3,3,1,4,3,4,0,3,0,4,2,3,3,2,2,5,4,2,1,3,4,3,4,3,1,3,3,4,2,0,2,1,0,3,3,0,0,2,0,3,1,0,4,4,3,4,3,0,4,0,1,0,2,4,4,4,4,4,0,3,2,0,3,3,},
new byte[]{ 0,0,0,1,0,4,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,3,2,0,0,1,0,0,0,1,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,1,0,0,0,0,0,2,},
new byte[]{ 0,2,0,3,0,4,0,4,0,1,3,3,3,0,4,0,2,1,2,1,1,1,2,0,3,1,1,0,1,0,3,1,0,0,3,3,2,0,1,1,0,0,0,0,0,1,0,2,0,2,2,0,3,1,0,0,1,0,1,1,0,1,2,0,3,0,0,0,0,1,0,0,3,3,4,3,1,0,1,0,3,0,2,},
new byte[]{ 0,0,0,3,0,5,0,0,0,0,1,0,2,0,3,1,0,1,3,0,0,0,2,0,0,0,1,0,0,0,1,1,0,0,4,0,0,0,2,3,0,1,4,1,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,1,0,0,0,0,0,0,0,2,0,0,3,0,0,0,0,0,3,},
new byte[]{ 0,2,0,5,0,5,0,1,0,2,4,3,3,2,5,1,3,2,3,3,3,0,4,1,2,0,3,0,4,0,2,2,1,1,5,3,0,0,1,4,2,3,2,0,3,3,3,2,0,2,4,1,1,2,0,1,1,0,3,1,0,1,3,1,2,3,0,2,0,0,0,1,3,5,4,4,4,0,3,0,0,1,3,},
new byte[]{ 0,4,0,5,0,4,0,4,0,4,5,4,3,3,4,3,3,3,4,3,4,4,5,3,4,5,4,2,4,2,3,4,3,1,4,4,1,3,5,4,4,5,5,4,4,5,5,5,2,3,3,1,4,3,1,3,3,0,3,3,1,4,3,4,4,4,0,3,0,4,0,3,3,4,4,5,0,0,4,3,0,4,5,},
new byte[]{ 0,4,0,4,0,3,0,3,0,3,4,4,4,3,3,2,4,3,4,3,4,3,5,3,4,3,2,1,4,2,4,4,3,1,3,4,2,4,5,5,3,4,5,4,1,5,4,3,0,3,2,2,3,2,1,3,1,0,3,3,3,5,3,3,3,5,4,4,2,3,3,4,3,3,3,2,1,0,3,2,1,4,3,},
new byte[]{ 0,4,0,5,0,4,0,3,0,3,5,5,3,2,4,3,4,0,5,4,4,1,4,4,4,3,3,3,4,3,5,5,2,3,3,4,1,2,5,5,3,5,5,2,3,5,5,4,0,3,2,0,3,3,1,1,5,1,4,1,0,4,3,2,3,5,0,4,0,3,0,5,4,3,4,3,0,0,4,1,0,4,4,},
new byte[]{ 1,3,0,4,0,2,0,2,0,2,5,5,3,3,3,3,3,0,4,2,3,4,4,4,3,4,0,0,3,4,5,4,3,3,3,3,2,5,5,4,5,5,5,4,3,5,5,5,1,3,1,0,1,0,0,3,2,0,4,2,0,5,2,3,2,4,1,3,0,3,0,4,5,4,5,4,3,0,4,2,0,5,4,},
new byte[]{ 0,3,0,4,0,5,0,3,0,3,4,4,3,2,3,2,3,3,3,3,3,2,4,3,3,2,2,0,3,3,3,3,3,1,3,3,3,0,4,4,3,4,4,1,1,4,4,2,0,3,1,0,1,1,0,4,1,0,2,3,1,3,3,1,3,4,0,3,0,1,0,3,1,3,0,0,1,0,2,0,0,4,4,},
new byte[]{ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,},
new byte[]{ 0,3,0,3,0,2,0,3,0,1,5,4,3,3,3,1,4,2,1,2,3,4,4,2,4,4,5,0,3,1,4,3,4,0,4,3,3,3,2,3,2,5,3,4,3,2,2,3,0,0,3,0,2,1,0,1,2,0,0,0,0,2,1,1,3,1,0,2,0,4,0,3,4,4,4,5,2,0,2,0,0,1,3,},
new byte[]{ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,0,0,1,1,0,0,0,4,2,1,1,0,1,0,3,2,0,0,3,1,1,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,1,0,0,0,2,0,0,0,1,4,0,4,2,1,0,0,0,0,0,1,},
new byte[]{ 0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,1,0,1,0,0,0,0,3,1,0,0,0,2,0,2,1,0,0,1,2,1,0,1,1,0,0,3,0,0,0,0,0,0,0,0,0,0,0,1,3,1,0,0,0,0,0,1,0,0,2,1,0,0,0,0,0,0,0,0,2,},
new byte[]{ 0,4,0,4,0,4,0,3,0,4,4,3,4,2,4,3,2,0,4,4,4,3,5,3,5,3,3,2,4,2,4,3,4,3,1,4,0,2,3,4,4,4,3,3,3,4,4,4,3,4,1,3,4,3,2,1,2,1,3,3,3,4,4,3,3,5,0,4,0,3,0,4,3,3,3,2,1,0,3,0,0,3,3,},
new byte[]{ 0,4,0,3,0,3,0,3,0,3,5,5,3,3,3,3,4,3,4,3,3,3,4,4,4,3,3,3,3,4,3,5,3,3,1,3,2,4,5,5,5,5,4,3,4,5,5,3,2,2,3,3,3,3,2,3,3,1,2,3,2,4,3,3,3,4,0,4,0,2,0,4,3,2,2,1,2,0,3,0,0,4,1,},
};
const int MINIMUM_DATA_THRESHOLD = 4;
public void HandleData(byte[] aBuf)
{
HandleData(aBuf, aBuf.Length);
}
public void HandleData(byte[] aBuf, int aLen)
{
int charLen = 0;
int order;
if (mDone)
return;
//The buffer we got is byte oriented, and a character may span in more than one
//buffers. In case the last one or two byte in last buffer is not complete, we
//record how many byte needed to complete that character and skip these bytes here.
//We can choose to record those bytes as well and analyse the character once it
//is complete, but since a character will not make much difference, by simply skipping
//this character will simply our logic and improve performance.
for (int i = mNeedToSkipCharNum; i < aLen; )
{
order = GetOrder(new byte[] { aBuf[i], aBuf[i + 1] }, ref charLen);
i += charLen;
if (i > aLen)
{
mNeedToSkipCharNum = i - aLen;
mLastCharOrder = -1;
}
else
{
if (order != -1 && mLastCharOrder != -1)
{
mTotalRel++;
if (mTotalRel > MAX_REL_THRESHOLD)
{
mDone = true;
break;
}
mRelSample[jp2CharContext[mLastCharOrder][order]]++;
}
mLastCharOrder = order;
}
}
return;
}
void HandleOneChar(byte[] aStr, int aCharLen)
{
int order;
//if we received enough data, stop here
if (mTotalRel > MAX_REL_THRESHOLD) mDone = true;
if (mDone) return;
//Only 2-bytes characters are of our interest
order = (aCharLen == 2) ? GetOrder(aStr) : -1;
if (order != -1 && mLastCharOrder != -1)
{
mTotalRel++;
//count this sequence to its category counter
mRelSample[jp2CharContext[mLastCharOrder][order]]++;
}
mLastCharOrder = order;
}
public void Reset()
{
mTotalRel = 0;
for (int i = 0; i < NUM_OF_CATEGORY; i++)
mRelSample[i] = 0;
mNeedToSkipCharNum = 0;
mLastCharOrder = -1;
mDone = false;
}
const float DONT_KNOW = -1.0f;
public float Confidence
{
get
{
//This is just one way to calculate confidence. It works well for me.
if (mTotalRel > MINIMUM_DATA_THRESHOLD)
return ((float)(mTotalRel - mRelSample[0])) / mTotalRel;
else
return DONT_KNOW;
}
}
}
internal class SJISContextAnalysis : JapaneseContextAnalysis
{
//SJISContextAnalysis(){};
internal override int GetOrder(byte[] str, ref int charLen)
{
//find out current char's byte length
if (str[0] >= 0x81 && str[0] <= 0x9f ||
str[0] >= 0xe0 && str[0] <= 0xfc)
charLen = 2;
else
charLen = 1;
//return its order if it is hiragana
if (str[0] == 202 &&
str[1] >= 0x9f &&
str[1] <= 0xf1)
return str[1] - 0x9f;
return -1;
}
internal override int GetOrder(byte[] str)
{
//We only interested in Hiragana, so first byte is '\202'
if (str[0] == 202 &&
str[1] >= 0x9f &&
str[1] <= 0xf1)
return str[1] - 0x9f;
return -1;
}
}
internal class EUCJPContextAnalysis : JapaneseContextAnalysis
{
internal override int GetOrder(byte[] str, ref int charLen)
{
//find out current char's byte length
if (str[0] == 0x8e ||
str[0] >= 0xa1 &&
str[0] <= 0xfe)
charLen = 2;
else if (str[0] == 0x8f)
charLen = 3;
else
charLen = 1;
//return its order if it is hiragana
if (str[0] == 0xa4 &&
str[1] >= 0xa1 &&
str[1] <= 0xf3)
return str[1] - 0xa1;
return -1;
}
internal override int GetOrder(byte[] str)
{
//We only interested in Hiragana, so first byte is '\244'
if (str[0] == 244 &&
str[1] >= 0xa1 &&
str[1] <= 0xf3)
return str[1] - 0xa1;
return -1;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/appengine/v1/operation.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Appengine.V1 {
/// <summary>Holder for reflection information generated from google/appengine/v1/operation.proto</summary>
public static partial class OperationReflection {
#region Descriptor
/// <summary>File descriptor for google/appengine/v1/operation.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static OperationReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiNnb29nbGUvYXBwZW5naW5lL3YxL29wZXJhdGlvbi5wcm90bxITZ29vZ2xl",
"LmFwcGVuZ2luZS52MRocZ29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5wcm90bxof",
"Z29vZ2xlL3Byb3RvYnVmL3RpbWVzdGFtcC5wcm90byKiAQoTT3BlcmF0aW9u",
"TWV0YWRhdGFWMRIOCgZtZXRob2QYASABKAkSLwoLaW5zZXJ0X3RpbWUYAiAB",
"KAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEiwKCGVuZF90aW1lGAMg",
"ASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBIMCgR1c2VyGAQgASgJ",
"Eg4KBnRhcmdldBgFIAEoCUJpChdjb20uZ29vZ2xlLmFwcGVuZ2luZS52MUIO",
"T3BlcmF0aW9uUHJvdG9QAVo8Z29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8v",
"Z29vZ2xlYXBpcy9hcHBlbmdpbmUvdjE7YXBwZW5naW5lYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Appengine.V1.OperationMetadataV1), global::Google.Appengine.V1.OperationMetadataV1.Parser, new[]{ "Method", "InsertTime", "EndTime", "User", "Target" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Metadata for the given [google.longrunning.Operation][google.longrunning.Operation].
/// </summary>
public sealed partial class OperationMetadataV1 : pb::IMessage<OperationMetadataV1> {
private static readonly pb::MessageParser<OperationMetadataV1> _parser = new pb::MessageParser<OperationMetadataV1>(() => new OperationMetadataV1());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<OperationMetadataV1> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Appengine.V1.OperationReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public OperationMetadataV1() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public OperationMetadataV1(OperationMetadataV1 other) : this() {
method_ = other.method_;
InsertTime = other.insertTime_ != null ? other.InsertTime.Clone() : null;
EndTime = other.endTime_ != null ? other.EndTime.Clone() : null;
user_ = other.user_;
target_ = other.target_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public OperationMetadataV1 Clone() {
return new OperationMetadataV1(this);
}
/// <summary>Field number for the "method" field.</summary>
public const int MethodFieldNumber = 1;
private string method_ = "";
/// <summary>
/// API method that initiated this operation. Example:
/// `google.appengine.v1.Versions.CreateVersion`.
///
/// @OutputOnly
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Method {
get { return method_; }
set {
method_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "insert_time" field.</summary>
public const int InsertTimeFieldNumber = 2;
private global::Google.Protobuf.WellKnownTypes.Timestamp insertTime_;
/// <summary>
/// Time that this operation was created.
///
/// @OutputOnly
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp InsertTime {
get { return insertTime_; }
set {
insertTime_ = value;
}
}
/// <summary>Field number for the "end_time" field.</summary>
public const int EndTimeFieldNumber = 3;
private global::Google.Protobuf.WellKnownTypes.Timestamp endTime_;
/// <summary>
/// Time that this operation completed.
///
/// @OutputOnly
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp EndTime {
get { return endTime_; }
set {
endTime_ = value;
}
}
/// <summary>Field number for the "user" field.</summary>
public const int UserFieldNumber = 4;
private string user_ = "";
/// <summary>
/// User who requested this operation.
///
/// @OutputOnly
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string User {
get { return user_; }
set {
user_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "target" field.</summary>
public const int TargetFieldNumber = 5;
private string target_ = "";
/// <summary>
/// Name of the resource that this operation is acting on. Example:
/// `apps/myapp/services/default`.
///
/// @OutputOnly
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Target {
get { return target_; }
set {
target_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as OperationMetadataV1);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(OperationMetadataV1 other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Method != other.Method) return false;
if (!object.Equals(InsertTime, other.InsertTime)) return false;
if (!object.Equals(EndTime, other.EndTime)) return false;
if (User != other.User) return false;
if (Target != other.Target) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Method.Length != 0) hash ^= Method.GetHashCode();
if (insertTime_ != null) hash ^= InsertTime.GetHashCode();
if (endTime_ != null) hash ^= EndTime.GetHashCode();
if (User.Length != 0) hash ^= User.GetHashCode();
if (Target.Length != 0) hash ^= Target.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Method.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Method);
}
if (insertTime_ != null) {
output.WriteRawTag(18);
output.WriteMessage(InsertTime);
}
if (endTime_ != null) {
output.WriteRawTag(26);
output.WriteMessage(EndTime);
}
if (User.Length != 0) {
output.WriteRawTag(34);
output.WriteString(User);
}
if (Target.Length != 0) {
output.WriteRawTag(42);
output.WriteString(Target);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Method.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Method);
}
if (insertTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(InsertTime);
}
if (endTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(EndTime);
}
if (User.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(User);
}
if (Target.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Target);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(OperationMetadataV1 other) {
if (other == null) {
return;
}
if (other.Method.Length != 0) {
Method = other.Method;
}
if (other.insertTime_ != null) {
if (insertTime_ == null) {
insertTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
InsertTime.MergeFrom(other.InsertTime);
}
if (other.endTime_ != null) {
if (endTime_ == null) {
endTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
EndTime.MergeFrom(other.EndTime);
}
if (other.User.Length != 0) {
User = other.User;
}
if (other.Target.Length != 0) {
Target = other.Target;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Method = input.ReadString();
break;
}
case 18: {
if (insertTime_ == null) {
insertTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(insertTime_);
break;
}
case 26: {
if (endTime_ == null) {
endTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(endTime_);
break;
}
case 34: {
User = input.ReadString();
break;
}
case 42: {
Target = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// AppearanceClass.cs
//
// Copyright (c) 2013 Brent Knowles (http://www.brentknowles.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Review documentation at http://www.yourothermind.com for updated implementation notes, license updates
// or other general information/
//
// Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW
// Full source code: https://github.com/BrentKnowles/YourOtherMind
//###
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Xml.Serialization;
using CoreUtilities;
namespace Layout
{
// This class is serialized into a column in the Database. Users may add/edit and then select them to modify the appearance of notes
[XmlRootAttribute("Appearance", Namespace = "", IsNullable = false)]
public class AppearanceClass
{
public AppearanceClass ()
{
}
string name = Constants.BLANK;
// this is the key into the db
public string Name {
get {
return name;
}
set {
name = value;
}
}
private int mnHeaderHeight;
public int nHeaderHeight
{
get {return mnHeaderHeight;}
set {mnHeaderHeight = value;}
}
private BorderStyle mHeaderBorderStyle;
public BorderStyle HeaderBorderStyle
{
get
{
return mHeaderBorderStyle;
}
set
{
mHeaderBorderStyle = value;
}
}
private BorderStyle mmainPanelBorderStyle;
public BorderStyle mainPanelBorderStyle
{
get
{
return mmainPanelBorderStyle;
}
set
{
mmainPanelBorderStyle = value;
}
}
public string mcaptionFont;
// don't output the heading to XML because it won't serialize
// instead the string behidn the scenes is output
[XmlIgnoreAttribute()]
public Font captionFont
{
get
{
return General.StringToFont(mcaptionFont);
}
set
{
FontConverter fc = new FontConverter();
mcaptionFont = (string)fc.ConvertTo(value, typeof(string));
}
}
// public string mtextFont;
//
// [XmlIgnoreAttribute()]
// public Font textFont
// {
// get
// {
// return General.StringToFont(mtextFont);
// }
// set
// {
// FontConverter fc = new FontConverter();
// mtextFont = (string)fc.ConvertTo(value, typeof(string));
// }
// }
public string mdayFont;
[XmlIgnoreAttribute()]
public Font dayFont
{
get
{
return General.StringToFont(mdayFont);
}
set
{
FontConverter fc = new FontConverter();
mdayFont = (string)fc.ConvertTo(value, typeof(string));
}
}
[XmlIgnore]
public Color captionBackground; // what is reade
public int mcaptionBackground // what is stored
{
get
{
return captionBackground.ToArgb();
}
set
{
captionBackground = Color.FromArgb(value);
}
}
[XmlIgnore]
public Color captionForeground;
public int mcaptionForeground
{
get
{
return captionForeground.ToArgb(); ;
}
set
{
captionForeground = Color.FromArgb(value);
}
}
[XmlIgnore]
public Color mainBackground;
public int mmainBackground
{
get
{
return mainBackground.ToArgb(); ;
}
set
{
mainBackground = Color.FromArgb(value); ;
}
}
[XmlIgnore]
public Color secondaryForeground;
public int SecondaryForeground
{
get
{
return secondaryForeground.ToArgb(); ;
}
set
{
secondaryForeground = Color.FromArgb(value); ;
}
}
// [XmlIgnore]
// public Color textColor;
// public int mtextColor
// {
// get
// {
// return textColor.ToArgb(); ; ;
// }
// set
// {
// textColor = Color.FromArgb(value); ; ;
// }
// }
//
// [XmlIgnore]
// public Color timelineZoomOutPanelBackground;
// public int mtimelineZoomOutPanelBackground
// {
// get
// {
// return timelineZoomOutPanelBackground.ToArgb(); ;
// }
// set
// {
// timelineZoomOutPanelBackground = Color.FromArgb(value); ;
// }
// }
// private BorderStyle mrichTextBorderStyle;
// public BorderStyle richTextBorderStyle
// {
// get
// {
// return mrichTextBorderStyle;
// }
// set
// {
// mrichTextBorderStyle = value;
// }
// }
//
// [XmlIgnore]
// public Color monthFontColor;
// public int mmonthFontColor
// {
// get
// {
// return monthFontColor.ToArgb();
// }
// set
// {
// monthFontColor = Color.FromArgb(value);
// }
// }
//
// public string mmonthFont;
//
// [XmlIgnoreAttribute()]
// public Font monthFont
// {
// get
// {
// return General.StringToFont(mmonthFont);
// }
// set
// {
// FontConverter fc = new FontConverter();
// mmonthFont = (string)fc.ConvertTo(value, typeof(string));
// }
// }
// private structGradient mtimelineGradient;
// public structGradient timelineGradient
// {
// get
// {
// return mtimelineGradient;
// }
// set
// {
// mtimelineGradient = value;
// }
// }
private bool mUseBackgroundColor = true;
/// <summary>
/// If true shape inherits the background color
/// Otherwise the shape will keep the colors from the art
/// </summary>
public bool UseBackgroundColor
{
get {return mUseBackgroundColor;}
set {mUseBackgroundColor = value;}
}
private string mImage = "";
/// <summary>
/// is the filename (no directory) of the image to use
/// looks for it in the ShipIcons directory
/// </summary>
public string Image
{
get { return mImage;}
set {mImage = value;}
}
/// <summary>
/// Serializes the XML into a string
/// </summary>
/// <returns>
/// The XM.
/// </returns>
public string GetAppearanceXML ()
{
System.Xml.Serialization.XmlSerializer x3 = null;
System.IO.StringWriter sw = null;
sw = new System.IO.StringWriter ();
//sw.Encoding = "";
x3 = new System.Xml.Serialization.XmlSerializer (typeof(AppearanceClass));
x3.Serialize (sw, this);
x3 = null;
//x3.Serialize (sw, ListAsDataObjectsOfType,ns, "utf-8");
string result = sw.ToString ();
sw.Close ();
return result;
}
public static AppearanceClass SetAsFantasy ()
{
AppearanceClass newApp = new AppearanceClass();
newApp.Name="fantasy";
newApp.mcaptionFont = "Georgia, 12pt"; //1
newApp.mnHeaderHeight = 28; //2
newApp.HeaderBorderStyle = BorderStyle.FixedSingle; //3
newApp.mainPanelBorderStyle = BorderStyle.None; //4
newApp.mcaptionBackground =-663885; //5
newApp.mcaptionForeground = -16777216; //6
newApp.mmainBackground =-663885; //7
newApp.UseBackgroundColor = true;
newApp.SecondaryForeground = newApp.mcaptionForeground;
return newApp;
}
public static AppearanceClass SetAsSciFI ()
{
AppearanceClass newApp = new AppearanceClass();
newApp.Name = "scifi";
// doing this inside the class to have access to private members to set them to numbers
newApp.mcaptionFont = "Verdana, 18pt, style=Bold";
newApp.mnHeaderHeight = 28;
newApp.HeaderBorderStyle = BorderStyle.None;
newApp.mainPanelBorderStyle = BorderStyle.None;
newApp.mcaptionBackground = -12156236;
//newApp.mcaptionForeground = -2894893;
newApp.mcaptionForeground = Color.DarkGray.ToArgb();//-2894893;
newApp.mmainBackground = -2894893;
newApp.UseBackgroundColor = true;
newApp.SecondaryForeground = newApp.mcaptionForeground;
return newApp;
}
public static AppearanceClass SetAsResearch()
{
AppearanceClass newApp = new AppearanceClass();
newApp.Name = "research";
// doing this inside the class to have access to private members to set them to numbers
newApp.mcaptionFont = "Times New Roman, 10pt, style=Bold";
newApp.mnHeaderHeight = 20;
newApp.HeaderBorderStyle = BorderStyle.FixedSingle;
newApp.mainPanelBorderStyle = BorderStyle.FixedSingle;
newApp.mcaptionBackground = -12490271;
newApp.mcaptionForeground = -16777216;
newApp.mmainBackground =-984833;
newApp.UseBackgroundColor = true;
newApp.SecondaryForeground = newApp.mcaptionForeground;
return newApp;
}
public static AppearanceClass SetAsClassic()
{
AppearanceClass newApp = new AppearanceClass();
newApp.Name = "classic";
// doing this inside the class to have access to private members to set them to numbers
newApp.mcaptionFont = "Times New Roman, 10pt, style=Bold";
newApp.mnHeaderHeight = 20;
newApp.HeaderBorderStyle = BorderStyle.FixedSingle;
newApp.mainPanelBorderStyle = BorderStyle.FixedSingle;
newApp.mcaptionBackground = -2987746;
newApp.mcaptionForeground = -16777216;
newApp.mmainBackground = Color.White.ToArgb();
newApp.UseBackgroundColor = true;
newApp.SecondaryForeground = newApp.mcaptionForeground;
return newApp;
// February 2013
// I removed the timeline colors from this because it does not make sense
// what should be happening with timelines is that they instead take the base
// colors and apply them to the timeline in some way
// monthFont = new Font("Georgia", 20.0);
// mtimelineZoomOutPanelBackground = -5383962;
// mmonthFontColor = -65536;
// timelineGradient.Color1 = -7876885;
// timelineGradient .Color2 = -657931;
// timelineGradient.GradientMode =System.Drawing.Drawing2D.LinearGradientMode.Horizontal;
}
public static AppearanceClass SetAsProgrammer()
{
AppearanceClass newApp = new AppearanceClass();
newApp.Name = "programmer";
// doing this inside the class to have access to private members to set them to numbers
newApp.mcaptionFont = "Verdana, 12pt, style=Bold";
newApp.mnHeaderHeight = 20;
newApp.HeaderBorderStyle = BorderStyle.FixedSingle;
newApp.mainPanelBorderStyle = BorderStyle.FixedSingle;
newApp.mcaptionBackground =-16777216;
newApp.mcaptionForeground = -256;
newApp.mmainBackground =-16777216;
newApp.UseBackgroundColor = true;
newApp.SecondaryForeground = newApp.mcaptionForeground;
return newApp;
}
public static AppearanceClass SetAsNote()
{
AppearanceClass newApp = new AppearanceClass();
newApp.Name = "note";
// doing this inside the class to have access to private members to set them to numbers
newApp.mcaptionFont = "Verdana, 10pt, style=Bold";
newApp.mnHeaderHeight = 20;
newApp.HeaderBorderStyle = BorderStyle.None;
newApp.mainPanelBorderStyle = BorderStyle.None;
newApp.mcaptionBackground =-128;
newApp.mcaptionForeground = -16777216;
newApp.mmainBackground =-128;
newApp.UseBackgroundColor = true;
newApp.SecondaryForeground = newApp.mcaptionForeground;
return newApp;
}
public static AppearanceClass SetAsModern()
{
AppearanceClass newApp = new AppearanceClass();
newApp.Name = "modern";
// doing this inside the class to have access to private members to set them to numbers
newApp.mcaptionFont = "Arial Black, 12pt, style=Bold";
newApp.mnHeaderHeight = 28;
newApp.HeaderBorderStyle = BorderStyle.None;
newApp.mainPanelBorderStyle = BorderStyle.None;
newApp.mcaptionBackground =-6972;
newApp.mcaptionForeground = -16777216;
newApp.mmainBackground =-1468806;
newApp.UseBackgroundColor = true;
newApp.SecondaryForeground = newApp.mcaptionForeground;
return newApp;
}
public static AppearanceClass SetAsBlue()
{
AppearanceClass newApp = new AppearanceClass();
newApp.Name = "blue";
// doing this inside the class to have access to private members to set them to numbers
newApp.mcaptionFont = "Verdana, 12pt, style=Bold";
newApp.mnHeaderHeight = 26;
newApp.HeaderBorderStyle = BorderStyle.None;
newApp.mainPanelBorderStyle = BorderStyle.None;
newApp.mcaptionBackground =-12490271;
newApp.mcaptionForeground = -657931;
newApp.mmainBackground =-12490271;
newApp.UseBackgroundColor = true;
newApp.SecondaryForeground = newApp.mcaptionForeground;
return newApp;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.